_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
|
---|---|---|---|---|---|---|---|---|
f2e1a33fb59c5cb72d436d4de7e5eeb7738c8e6f2053dfc736d5ffbbc6c30723
|
composewell/streamly
|
Array.hs
|
-- |
Module : Streamly . Test . Data . Array
Copyright : ( c ) 2019 Composewell technologies
-- License : BSD-3-Clause
-- Maintainer :
-- Stability : experimental
Portability : GHC
module Streamly.Test.Data.Array (main) where
import Data.Char (isLower)
import Data.List (sort)
import Data.Proxy (Proxy(..))
import Data.Word(Word8)
import Foreign.Storable (peek)
import GHC.Ptr (plusPtr)
import Streamly.Internal.Data.Unboxed (Unbox, sizeOf)
import Streamly.Internal.Data.Array.Mut.Type (MutArray)
import Test.QuickCheck (chooseInt, listOf)
import qualified Streamly.Internal.Data.Array as A
import qualified Streamly.Internal.Data.Array.Type as A
import qualified Streamly.Internal.Data.Array.Mut.Type as MA
#include "Streamly/Test/Data/Array/CommonImports.hs"
type Array = A.Array
moduleName :: String
moduleName = "Data.Array"
#include "Streamly/Test/Data/Array/Common.hs"
testFromStreamToStream :: Property
testFromStreamToStream = genericTestFromTo (const A.fromStream) A.read (==)
testFoldUnfold :: Property
testFoldUnfold =
genericTestFromTo (const (S.fold A.write)) (S.unfold A.reader) (==)
testFromList :: Property
testFromList =
forAll (choose (0, maxArrLen)) $ \len ->
forAll (vectorOf len (arbitrary :: Gen Int)) $ \list ->
monadicIO $ do
let arr = A.fromList list
xs <- run $ S.fold Fold.toList $ S.unfold A.reader arr
assert (xs == list)
testLengthFromStream :: Property
testLengthFromStream = genericTestFrom (const A.fromStream)
unsafeWriteIndex :: [Int] -> Int -> Int -> IO Bool
unsafeWriteIndex xs i x = do
arr <- MA.fromList xs
MA.putIndexUnsafe i arr x
x1 <- MA.getIndexUnsafe i arr
return $ x1 == x
lastN :: Int -> [a] -> [a]
lastN n l = drop (length l - n) l
testLastN :: Property
testLastN =
forAll (choose (0, maxArrLen)) $ \len ->
forAll (choose (0, len)) $ \n ->
forAll (vectorOf len (arbitrary :: Gen Int)) $ \list ->
monadicIO $ do
xs <- run
$ fmap A.toList
$ S.fold (A.writeLastN n)
$ S.fromList list
assert (xs == lastN n list)
testLastN_LN :: Int -> Int -> IO Bool
testLastN_LN len n = do
let list = [1..len]
l1 <- fmap A.toList $ S.fold (A.writeLastN n) $ S.fromList list
let l2 = lastN n list
return $ l1 == l2
testStrip :: IO Bool
testStrip = do
dt <- MA.fromList "abcDEFgeh"
dt' <- MA.strip isLower dt
x <- MA.toList dt'
return $ x == "DEF"
testStripLeft :: IO Bool
testStripLeft = do
dt <- MA.fromList "abcDEF"
dt' <- MA.strip isLower dt
x <- MA.toList dt'
return $ x == "DEF"
testStripRight :: IO Bool
testStripRight = do
dt <- MA.fromList "DEFgeh"
dt' <- MA.strip isLower dt
x <- MA.toList dt'
return $ x == "DEF"
testStripZero :: IO Bool
testStripZero = do
dt <- MA.fromList "DEF"
dt' <- MA.strip isLower dt
x <- MA.toList dt'
return $ x == "DEF"
testStripEmpty :: IO Bool
testStripEmpty = do
dt <- MA.fromList "abc"
dt' <- MA.strip isLower dt
x <- MA.toList dt'
return $ x == ""
testStripNull :: IO Bool
testStripNull = do
dt <- MA.fromList ""
dt' <- MA.strip isLower dt
x <- MA.toList dt'
return $ x == ""
unsafeSlice :: Int -> Int -> [Int] -> Bool
unsafeSlice i n list =
let lst = take n $ drop i list
arr = A.toList $ A.getSliceUnsafe i n $ A.fromList list
in arr == lst
testBubbleWith :: Bool -> Property
testBubbleWith asc =
forAll (listOf (chooseInt (-50, 100))) $ \ls0 ->
monadicIO $ action ls0
where
action ls = do
x <- S.fold (fldm ls) $ S.fromList ls
lst <- MA.toList x
if asc
then assert (sort ls == lst)
else assert (sort ls == reverse lst)
fldm ls =
Fold.foldlM'
(\b a -> do
arr <- MA.snoc b a
if asc
then MA.bubble compare arr
else MA.bubble (flip compare) arr
return arr
)
(MA.newPinned $ length ls)
testBubbleAsc :: Property
testBubbleAsc = testBubbleWith True
testBubbleDesc :: Property
testBubbleDesc = testBubbleWith False
testByteLengthWithMA :: forall a. Unbox a => a -> IO ()
testByteLengthWithMA _ = do
arrA <- MA.newPinned 100 :: IO (MutArray a)
let arrW8 = MA.castUnsafe arrA :: MutArray Word8
MA.byteLength arrA `shouldBe` MA.length arrW8
testBreakOn :: [Word8] -> Word8 -> [Word8] -> Maybe [Word8] -> IO ()
testBreakOn inp sep bef aft = do
(bef_, aft_) <- A.breakOn sep (A.fromList inp)
bef_ `shouldBe` A.fromList bef
aft_ `shouldBe` fmap A.fromList aft
testWrite :: [Char] -> IO ()
testWrite inp = do
arr <- S.fold A.write (S.fromList inp)
A.toList arr `shouldBe` inp
testFromToList :: [Char] -> IO ()
testFromToList inp = A.toList (A.fromList inp) `shouldBe` inp
testUnsafeIndxedFromList :: [Char] -> IO ()
testUnsafeIndxedFromList inp =
let arr = A.fromList inp
in fmap (`A.unsafeIndex` arr) [0 .. (length inp - 1)] `shouldBe` inp
testAsPtrUnsafeMA :: IO ()
testAsPtrUnsafeMA = do
arr <- MA.fromList ([0 .. 99] :: [Int])
MA.asPtrUnsafe arr (getList (0 :: Int)) `shouldReturn` [0 .. 99]
where
sizeOfInt = sizeOf (Proxy :: Proxy Int)
We need to be careful here . We assume and are compatible
with each other . For , they are compatible .
getList i _
| i >= 100 = return []
getList i p = do
val <- peek p
rest <- getList (i + 1) (p `plusPtr` sizeOfInt)
return $ val : rest
reallocMA :: Property
reallocMA =
let len = 10000
bSize = len * sizeOf (Proxy :: Proxy Char)
in forAll (vectorOf len (arbitrary :: Gen Char)) $ \vec ->
forAll (chooseInt (bSize - 2000, bSize + 2000)) $ \newBLen -> do
arr <- MA.fromList vec
arr1 <- MA.realloc newBLen arr
lst <- MA.toList arr
lst1 <- MA.toList arr1
lst `shouldBe` lst1
main :: IO ()
main =
hspec $
H.parallel $
modifyMaxSuccess (const maxTestCount) $ do
describe moduleName $ do
commonMain
describe "Construction" $ do
-- XXX There is an issue
--prop "testAppend" testAppend
prop "testBubbleAsc" testBubbleAsc
prop "testBubbleDesc" testBubbleDesc
prop "length . fromStream === n" testLengthFromStream
prop "toStream . fromStream === id" testFromStreamToStream
prop "read . write === id" testFoldUnfold
prop "fromList" testFromList
prop "foldMany with writeNUnsafe concats to original"
(foldManyWith (\n -> Fold.take n (A.writeNUnsafe n)))
describe "unsafeSlice" $ do
it "partial" $ unsafeSlice 2 4 [1..10]
it "none" $ unsafeSlice 10 0 [1..10]
it "full" $ unsafeSlice 0 10 [1..10]
describe "Mut.unsafeWriteIndex" $ do
it "first" (unsafeWriteIndex [1..10] 0 0 `shouldReturn` True)
it "middle" (unsafeWriteIndex [1..10] 5 0 `shouldReturn` True)
it "last" (unsafeWriteIndex [1..10] 9 0 `shouldReturn` True)
describe "Fold" $ do
prop "writeLastN : 0 <= n <= len" testLastN
describe "writeLastN boundary conditions" $ do
it "writeLastN -1" (testLastN_LN 10 (-1) `shouldReturn` True)
it "writeLastN 0" (testLastN_LN 10 0 `shouldReturn` True)
it "writeLastN length" (testLastN_LN 10 10 `shouldReturn` True)
it "writeLastN (length + 1)" (testLastN_LN 10 11 `shouldReturn` True)
describe "Strip" $ do
it "strip" (testStrip `shouldReturn` True)
it "stripLeft" (testStripLeft `shouldReturn` True)
it "stripRight" (testStripRight `shouldReturn` True)
it "stripZero" (testStripZero `shouldReturn` True)
it "stripEmpty" (testStripEmpty `shouldReturn` True)
it "stripNull" (testStripNull `shouldReturn` True)
describe "Mut" $ do
it "testByteLengthWithMA Int"
(testByteLengthWithMA (undefined :: Int))
it "testByteLengthWithMA Char"
(testByteLengthWithMA (undefined :: Char))
it "testAsPtrUnsafeMA" testAsPtrUnsafeMA
it "reallocMA" reallocMA
describe "breakOn" $ do
it "testBreakOn [1, 0, 2] 0"
(testBreakOn [1, 0, 2] 0 [1] (Just [2]))
it "testBreakOn [1, 0] 0" (testBreakOn [1, 0] 0 [1] (Just []))
it "testBreakOn [1] 0" (testBreakOn [1] 0 [1] Nothing)
describe "toList . fromList" $ do
it "testFromToList abc" (testFromToList "abc")
it "testFromToList \\22407" (testFromToList "\22407")
describe "unsafeIndex . fromList" $ do
it "testUnsafeIndxedFromList abc" (testUnsafeIndxedFromList "abc")
it "testUnsafeIndxedFromList \\22407"
(testUnsafeIndxedFromList "\22407")
describe "write" $ do
it "testWrite abc" (testWrite "abc")
it "testWrite \\22407" (testWrite "\22407")
| null |
https://raw.githubusercontent.com/composewell/streamly/34b2b4987629420cb3140e0b32a2b46daf9e5981/test/Streamly/Test/Data/Array.hs
|
haskell
|
|
License : BSD-3-Clause
Maintainer :
Stability : experimental
XXX There is an issue
prop "testAppend" testAppend
|
Module : Streamly . Test . Data . Array
Copyright : ( c ) 2019 Composewell technologies
Portability : GHC
module Streamly.Test.Data.Array (main) where
import Data.Char (isLower)
import Data.List (sort)
import Data.Proxy (Proxy(..))
import Data.Word(Word8)
import Foreign.Storable (peek)
import GHC.Ptr (plusPtr)
import Streamly.Internal.Data.Unboxed (Unbox, sizeOf)
import Streamly.Internal.Data.Array.Mut.Type (MutArray)
import Test.QuickCheck (chooseInt, listOf)
import qualified Streamly.Internal.Data.Array as A
import qualified Streamly.Internal.Data.Array.Type as A
import qualified Streamly.Internal.Data.Array.Mut.Type as MA
#include "Streamly/Test/Data/Array/CommonImports.hs"
type Array = A.Array
moduleName :: String
moduleName = "Data.Array"
#include "Streamly/Test/Data/Array/Common.hs"
testFromStreamToStream :: Property
testFromStreamToStream = genericTestFromTo (const A.fromStream) A.read (==)
testFoldUnfold :: Property
testFoldUnfold =
genericTestFromTo (const (S.fold A.write)) (S.unfold A.reader) (==)
testFromList :: Property
testFromList =
forAll (choose (0, maxArrLen)) $ \len ->
forAll (vectorOf len (arbitrary :: Gen Int)) $ \list ->
monadicIO $ do
let arr = A.fromList list
xs <- run $ S.fold Fold.toList $ S.unfold A.reader arr
assert (xs == list)
testLengthFromStream :: Property
testLengthFromStream = genericTestFrom (const A.fromStream)
unsafeWriteIndex :: [Int] -> Int -> Int -> IO Bool
unsafeWriteIndex xs i x = do
arr <- MA.fromList xs
MA.putIndexUnsafe i arr x
x1 <- MA.getIndexUnsafe i arr
return $ x1 == x
lastN :: Int -> [a] -> [a]
lastN n l = drop (length l - n) l
testLastN :: Property
testLastN =
forAll (choose (0, maxArrLen)) $ \len ->
forAll (choose (0, len)) $ \n ->
forAll (vectorOf len (arbitrary :: Gen Int)) $ \list ->
monadicIO $ do
xs <- run
$ fmap A.toList
$ S.fold (A.writeLastN n)
$ S.fromList list
assert (xs == lastN n list)
testLastN_LN :: Int -> Int -> IO Bool
testLastN_LN len n = do
let list = [1..len]
l1 <- fmap A.toList $ S.fold (A.writeLastN n) $ S.fromList list
let l2 = lastN n list
return $ l1 == l2
testStrip :: IO Bool
testStrip = do
dt <- MA.fromList "abcDEFgeh"
dt' <- MA.strip isLower dt
x <- MA.toList dt'
return $ x == "DEF"
testStripLeft :: IO Bool
testStripLeft = do
dt <- MA.fromList "abcDEF"
dt' <- MA.strip isLower dt
x <- MA.toList dt'
return $ x == "DEF"
testStripRight :: IO Bool
testStripRight = do
dt <- MA.fromList "DEFgeh"
dt' <- MA.strip isLower dt
x <- MA.toList dt'
return $ x == "DEF"
testStripZero :: IO Bool
testStripZero = do
dt <- MA.fromList "DEF"
dt' <- MA.strip isLower dt
x <- MA.toList dt'
return $ x == "DEF"
testStripEmpty :: IO Bool
testStripEmpty = do
dt <- MA.fromList "abc"
dt' <- MA.strip isLower dt
x <- MA.toList dt'
return $ x == ""
testStripNull :: IO Bool
testStripNull = do
dt <- MA.fromList ""
dt' <- MA.strip isLower dt
x <- MA.toList dt'
return $ x == ""
unsafeSlice :: Int -> Int -> [Int] -> Bool
unsafeSlice i n list =
let lst = take n $ drop i list
arr = A.toList $ A.getSliceUnsafe i n $ A.fromList list
in arr == lst
testBubbleWith :: Bool -> Property
testBubbleWith asc =
forAll (listOf (chooseInt (-50, 100))) $ \ls0 ->
monadicIO $ action ls0
where
action ls = do
x <- S.fold (fldm ls) $ S.fromList ls
lst <- MA.toList x
if asc
then assert (sort ls == lst)
else assert (sort ls == reverse lst)
fldm ls =
Fold.foldlM'
(\b a -> do
arr <- MA.snoc b a
if asc
then MA.bubble compare arr
else MA.bubble (flip compare) arr
return arr
)
(MA.newPinned $ length ls)
testBubbleAsc :: Property
testBubbleAsc = testBubbleWith True
testBubbleDesc :: Property
testBubbleDesc = testBubbleWith False
testByteLengthWithMA :: forall a. Unbox a => a -> IO ()
testByteLengthWithMA _ = do
arrA <- MA.newPinned 100 :: IO (MutArray a)
let arrW8 = MA.castUnsafe arrA :: MutArray Word8
MA.byteLength arrA `shouldBe` MA.length arrW8
testBreakOn :: [Word8] -> Word8 -> [Word8] -> Maybe [Word8] -> IO ()
testBreakOn inp sep bef aft = do
(bef_, aft_) <- A.breakOn sep (A.fromList inp)
bef_ `shouldBe` A.fromList bef
aft_ `shouldBe` fmap A.fromList aft
testWrite :: [Char] -> IO ()
testWrite inp = do
arr <- S.fold A.write (S.fromList inp)
A.toList arr `shouldBe` inp
testFromToList :: [Char] -> IO ()
testFromToList inp = A.toList (A.fromList inp) `shouldBe` inp
testUnsafeIndxedFromList :: [Char] -> IO ()
testUnsafeIndxedFromList inp =
let arr = A.fromList inp
in fmap (`A.unsafeIndex` arr) [0 .. (length inp - 1)] `shouldBe` inp
testAsPtrUnsafeMA :: IO ()
testAsPtrUnsafeMA = do
arr <- MA.fromList ([0 .. 99] :: [Int])
MA.asPtrUnsafe arr (getList (0 :: Int)) `shouldReturn` [0 .. 99]
where
sizeOfInt = sizeOf (Proxy :: Proxy Int)
We need to be careful here . We assume and are compatible
with each other . For , they are compatible .
getList i _
| i >= 100 = return []
getList i p = do
val <- peek p
rest <- getList (i + 1) (p `plusPtr` sizeOfInt)
return $ val : rest
reallocMA :: Property
reallocMA =
let len = 10000
bSize = len * sizeOf (Proxy :: Proxy Char)
in forAll (vectorOf len (arbitrary :: Gen Char)) $ \vec ->
forAll (chooseInt (bSize - 2000, bSize + 2000)) $ \newBLen -> do
arr <- MA.fromList vec
arr1 <- MA.realloc newBLen arr
lst <- MA.toList arr
lst1 <- MA.toList arr1
lst `shouldBe` lst1
main :: IO ()
main =
hspec $
H.parallel $
modifyMaxSuccess (const maxTestCount) $ do
describe moduleName $ do
commonMain
describe "Construction" $ do
prop "testBubbleAsc" testBubbleAsc
prop "testBubbleDesc" testBubbleDesc
prop "length . fromStream === n" testLengthFromStream
prop "toStream . fromStream === id" testFromStreamToStream
prop "read . write === id" testFoldUnfold
prop "fromList" testFromList
prop "foldMany with writeNUnsafe concats to original"
(foldManyWith (\n -> Fold.take n (A.writeNUnsafe n)))
describe "unsafeSlice" $ do
it "partial" $ unsafeSlice 2 4 [1..10]
it "none" $ unsafeSlice 10 0 [1..10]
it "full" $ unsafeSlice 0 10 [1..10]
describe "Mut.unsafeWriteIndex" $ do
it "first" (unsafeWriteIndex [1..10] 0 0 `shouldReturn` True)
it "middle" (unsafeWriteIndex [1..10] 5 0 `shouldReturn` True)
it "last" (unsafeWriteIndex [1..10] 9 0 `shouldReturn` True)
describe "Fold" $ do
prop "writeLastN : 0 <= n <= len" testLastN
describe "writeLastN boundary conditions" $ do
it "writeLastN -1" (testLastN_LN 10 (-1) `shouldReturn` True)
it "writeLastN 0" (testLastN_LN 10 0 `shouldReturn` True)
it "writeLastN length" (testLastN_LN 10 10 `shouldReturn` True)
it "writeLastN (length + 1)" (testLastN_LN 10 11 `shouldReturn` True)
describe "Strip" $ do
it "strip" (testStrip `shouldReturn` True)
it "stripLeft" (testStripLeft `shouldReturn` True)
it "stripRight" (testStripRight `shouldReturn` True)
it "stripZero" (testStripZero `shouldReturn` True)
it "stripEmpty" (testStripEmpty `shouldReturn` True)
it "stripNull" (testStripNull `shouldReturn` True)
describe "Mut" $ do
it "testByteLengthWithMA Int"
(testByteLengthWithMA (undefined :: Int))
it "testByteLengthWithMA Char"
(testByteLengthWithMA (undefined :: Char))
it "testAsPtrUnsafeMA" testAsPtrUnsafeMA
it "reallocMA" reallocMA
describe "breakOn" $ do
it "testBreakOn [1, 0, 2] 0"
(testBreakOn [1, 0, 2] 0 [1] (Just [2]))
it "testBreakOn [1, 0] 0" (testBreakOn [1, 0] 0 [1] (Just []))
it "testBreakOn [1] 0" (testBreakOn [1] 0 [1] Nothing)
describe "toList . fromList" $ do
it "testFromToList abc" (testFromToList "abc")
it "testFromToList \\22407" (testFromToList "\22407")
describe "unsafeIndex . fromList" $ do
it "testUnsafeIndxedFromList abc" (testUnsafeIndxedFromList "abc")
it "testUnsafeIndxedFromList \\22407"
(testUnsafeIndxedFromList "\22407")
describe "write" $ do
it "testWrite abc" (testWrite "abc")
it "testWrite \\22407" (testWrite "\22407")
|
c83ad264776adc243a5ab231b0ef642f87d3626646743b71d4765480417392bc
|
con-kitty/categorifier
|
Instances.hs
|
# OPTIONS_GHC -Wno - orphans #
module Categorifier.Test.Vec.Instances
( module Categorifier.Test.Hask,
module Categorifier.Test.Term,
)
where
import Categorifier.Test.Hask
import Categorifier.Test.Term
import Data.Pointed (Pointed (..))
import qualified Data.Type.Nat as Nat
import Data.Vec.Lazy (Vec)
instance Nat.SNatI n => Pointed (Vec n) where
point = pure
| null |
https://raw.githubusercontent.com/con-kitty/categorifier/8b33d0bdcab8172a0b53cb202a6449ad1b4a6992/integrations/vec/integration-test/Categorifier/Test/Vec/Instances.hs
|
haskell
|
# OPTIONS_GHC -Wno - orphans #
module Categorifier.Test.Vec.Instances
( module Categorifier.Test.Hask,
module Categorifier.Test.Term,
)
where
import Categorifier.Test.Hask
import Categorifier.Test.Term
import Data.Pointed (Pointed (..))
import qualified Data.Type.Nat as Nat
import Data.Vec.Lazy (Vec)
instance Nat.SNatI n => Pointed (Vec n) where
point = pure
|
|
055380d19c42f84a2945b0572458ae7984921fc0a18f2bd8a23403f03fc11775
|
aphyr/prism
|
project.clj
|
(defproject com.aphyr/prism "0.1.3"
:description "Re-run lein tests automatically"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[filevents "0.1.0"]])
| null |
https://raw.githubusercontent.com/aphyr/prism/9a7a2165d287ab2f929c4a697b0668d7e7126753/project.clj
|
clojure
|
(defproject com.aphyr/prism "0.1.3"
:description "Re-run lein tests automatically"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[filevents "0.1.0"]])
|
|
53fb9910cb7aa70793fc076d5b87c82531b8941b4f2f12266ab3519e630cce0b
|
MinaProtocol/mina
|
blockchain_snark_state.ml
|
open Core_kernel
open Snark_params
open Tick
open Mina_base
open Mina_state
open Pickles_types
include struct
open Snarky_backendless.Request
type _ t +=
| Prev_state : Protocol_state.Value.t t
| Prev_state_proof : (Nat.N2.n, Nat.N2.n) Pickles.Proof.t t
| Transition : Snark_transition.Value.t t
| Txn_snark : Transaction_snark.Statement.With_sok.t t
| Txn_snark_proof : (Nat.N2.n, Nat.N2.n) Pickles.Proof.t t
end
module Witness = struct
type t =
{ prev_state : Protocol_state.Value.t
; prev_state_proof : (Nat.N2.n, Nat.N2.n) Pickles.Proof.t
; transition : Snark_transition.Value.t
; txn_snark : Transaction_snark.Statement.With_sok.t
; txn_snark_proof : (Nat.N2.n, Nat.N2.n) Pickles.Proof.t
}
end
let blockchain_handler on_unhandled
{ Witness.prev_state
; prev_state_proof
; transition
; txn_snark
; txn_snark_proof
} =
let open Snarky_backendless.Request in
fun (With { request; respond } as r) ->
let k x = respond (Provide x) in
match request with
| Prev_state ->
k prev_state
| Prev_state_proof ->
k prev_state_proof
| Transition ->
k transition
| Txn_snark ->
k txn_snark
| Txn_snark_proof ->
k txn_snark_proof
| _ ->
on_unhandled r
let wrap_handler h w =
match h with
| None ->
blockchain_handler
(fun (Snarky_backendless.Request.With { respond; _ }) ->
respond Unhandled )
w
| Some h ->
(* TODO: Clean up the handler composition interface. *)
fun r -> blockchain_handler h w r
let with_handler k w ?handler =
let h = wrap_handler handler w in
k ?handler:(Some h)
module Impl = Pickles.Impls.Step
let non_pc_registers_equal_var t1 t2 =
Impl.make_checked (fun () ->
let module F = Core_kernel.Field in
let ( ! ) eq x1 x2 = Impl.run_checked (eq x1 x2) in
let f eq acc field = eq (F.get field t1) (F.get field t2) :: acc in
Registers.Fields.fold ~init:[]
~first_pass_ledger:(f !Frozen_ledger_hash.equal_var)
~second_pass_ledger:(f !Frozen_ledger_hash.equal_var)
~pending_coinbase_stack:(fun acc f ->
let () = F.get f t1 and () = F.get f t2 in
acc )
~local_state:(fun acc f ->
Local_state.Checked.equal' (F.get f t1) (F.get f t2) @ acc )
|> Impl.Boolean.all )
let txn_statement_ledger_hashes_equal
(s1 : Transaction_snark.Statement.Checked.t)
(s2 : Transaction_snark.Statement.Checked.t) =
Impl.make_checked (fun () ->
let module F = Core_kernel.Field in
let ( ! ) x = Impl.run_checked x in
let source_eq =
!(non_pc_registers_equal_var
{ s1.source with pending_coinbase_stack = () }
{ s2.source with pending_coinbase_stack = () } )
in
let target_eq =
!(non_pc_registers_equal_var
{ s1.target with pending_coinbase_stack = () }
{ s2.target with pending_coinbase_stack = () } )
in
let left_ledger_eq =
!(Frozen_ledger_hash.equal_var s1.connecting_ledger_left
s2.connecting_ledger_left )
in
let right_ledger_eq =
!(Frozen_ledger_hash.equal_var s1.connecting_ledger_right
s2.connecting_ledger_right )
in
let supply_increase_eq =
!(Currency.Amount.Signed.Checked.equal s1.supply_increase
s2.supply_increase )
in
Impl.Boolean.all
[ source_eq
; target_eq
; left_ledger_eq
; right_ledger_eq
; supply_increase_eq
] )
Blockchain_snark ~old ~nonce ~ledger_snark ~ledger_hash ~timestamp ~new_hash
Input :
old : Blockchain.t
old_snark : proof
nonce : int
: proof
ledger_hash : Ledger_hash.t
timestamp : Time.t
new_hash : State_hash.t
Witness :
transition : Transition.t
such that
the old_snark verifies against old
new = update_with_asserts(old , nonce , timestamp , ledger_hash )
hash(new ) = new_hash
the work_snark verifies against the old.ledger_hash and new_ledger_hash
new.timestamp > old.timestamp
transition consensus data is valid
new consensus state is a function of the old consensus state
Input:
old : Blockchain.t
old_snark : proof
nonce : int
work_snark : proof
ledger_hash : Ledger_hash.t
timestamp : Time.t
new_hash : State_hash.t
Witness:
transition : Transition.t
such that
the old_snark verifies against old
new = update_with_asserts(old, nonce, timestamp, ledger_hash)
hash(new) = new_hash
the work_snark verifies against the old.ledger_hash and new_ledger_hash
new.timestamp > old.timestamp
transition consensus data is valid
new consensus state is a function of the old consensus state
*)
let%snarkydef_ step ~(logger : Logger.t)
~(proof_level : Genesis_constants.Proof_level.t)
~(constraint_constants : Genesis_constants.Constraint_constants.t) new_state
: _ Tick.Checked.t =
let new_state_hash =
State_hash.var_of_hash_packed (Data_as_hash.hash new_state)
in
let%bind transition =
with_label __LOC__ (fun () ->
exists Snark_transition.typ ~request:(As_prover.return Transition) )
in
let%bind txn_snark =
with_label __LOC__ (fun () ->
exists Transaction_snark.Statement.With_sok.typ
~request:(As_prover.return Txn_snark) )
in
let%bind ( previous_state
, previous_state_hash
, previous_blockchain_proof_input
, previous_state_body_hash ) =
let%bind prev_state_ref =
with_label __LOC__ (fun () ->
exists (Typ.Internal.ref ()) ~request:(As_prover.return Prev_state) )
in
let%bind t =
with_label __LOC__ (fun () ->
exists
(Protocol_state.typ ~constraint_constants)
~compute:(As_prover.Ref.get prev_state_ref) )
in
let%map previous_state_hash, body = Protocol_state.hash_checked t in
let previous_blockchain_proof_input =
Data_as_hash.make_unsafe
(State_hash.var_to_field previous_state_hash)
prev_state_ref
in
(t, previous_state_hash, previous_blockchain_proof_input, body)
in
let%bind txn_stmt_ledger_hashes_didn't_change =
txn_statement_ledger_hashes_equal
(previous_state |> Protocol_state.blockchain_state).ledger_proof_statement
{ txn_snark with sok_digest = () }
in
let%bind supply_increase =
(* only increase the supply if the txn statement represents a new ledger transition *)
Currency.Amount.(
Signed.Checked.if_ txn_stmt_ledger_hashes_didn't_change
~then_:
(Signed.create_var ~magnitude:(var_of_t zero) ~sgn:Sgn.Checked.pos)
~else_:txn_snark.supply_increase)
in
let%bind `Success updated_consensus_state, consensus_state =
with_label __LOC__ (fun () ->
Consensus_state_hooks.next_state_checked ~constraint_constants
~prev_state:previous_state ~prev_state_hash:previous_state_hash
transition supply_increase )
in
let global_slot =
Consensus.Data.Consensus_state.global_slot_since_genesis_var consensus_state
in
let supercharge_coinbase =
Consensus.Data.Consensus_state.supercharge_coinbase_var consensus_state
in
let prev_pending_coinbase_root =
previous_state |> Protocol_state.blockchain_state
|> Blockchain_state.staged_ledger_hash
|> Staged_ledger_hash.pending_coinbase_hash_var
in
let%bind genesis_state_hash =
get the genesis state hash from previous state unless previous state is the genesis state
Protocol_state.genesis_state_hash_checked ~state_hash:previous_state_hash
previous_state
in
let%bind new_state, is_base_case =
let t =
Protocol_state.create_var ~previous_state_hash ~genesis_state_hash
~blockchain_state:(Snark_transition.blockchain_state transition)
~consensus_state
~constants:(Protocol_state.constants previous_state)
in
let%bind is_base_case =
Protocol_state.consensus_state t
|> Consensus.Data.Consensus_state.is_genesis_state_var
in
let%bind previous_state_hash =
match constraint_constants.fork with
| Some { previous_state_hash = fork_prev; _ } ->
State_hash.if_ is_base_case
~then_:(State_hash.var_of_t fork_prev)
~else_:t.previous_state_hash
| None ->
Checked.return t.previous_state_hash
in
let t = { t with previous_state_hash } in
let%map () =
let%bind h, _ = Protocol_state.hash_checked t in
with_label __LOC__ (fun () -> State_hash.assert_equal h new_state_hash)
in
(t, is_base_case)
in
let%bind txn_snark_should_verify, success =
let%bind new_pending_coinbase_hash, deleted_stack, no_coinbases_popped =
let coinbase_receiver =
Consensus.Data.Consensus_state.coinbase_receiver_var consensus_state
in
let%bind root_after_delete, deleted_stack =
Pending_coinbase.Checked.pop_coinbases ~constraint_constants
prev_pending_coinbase_root
~proof_emitted:(Boolean.not txn_stmt_ledger_hashes_didn't_change)
in
(*If snarked ledger hash did not change (no new ledger proof) then pop_coinbases should be a no-op*)
let%bind no_coinbases_popped =
Pending_coinbase.Hash.equal_var root_after_delete
prev_pending_coinbase_root
in
new stack or update one
let%map new_root =
with_label __LOC__ (fun () ->
Pending_coinbase.Checked.add_coinbase ~constraint_constants
root_after_delete
(Snark_transition.pending_coinbase_update transition)
~coinbase_receiver ~supercharge_coinbase previous_state_body_hash
global_slot )
in
(new_root, deleted_stack, no_coinbases_popped)
in
let current_ledger_statement =
(Protocol_state.blockchain_state new_state).ledger_proof_statement
in
let pending_coinbase_source_stack =
Pending_coinbase.Stack.Checked.create_with deleted_stack
in
let%bind txn_snark_input_correct =
let open Checked in
let%bind () =
Fee_excess.(assert_equal_checked (var_of_t zero) txn_snark.fee_excess)
in
let previous_ledger_statement =
(Protocol_state.blockchain_state previous_state).ledger_proof_statement
in
let ledger_statement_valid =
Impl.make_checked (fun () ->
Snarked_ledger_state.(
valid_ledgers_at_merge_checked
(Statement_ledgers.of_statement previous_ledger_statement)
(Statement_ledgers.of_statement current_ledger_statement)) )
in
(*TODO: Any assertion about the local state and sok digest
in the statement required?*)
all
[ ledger_statement_valid
; Pending_coinbase.Stack.equal_var
txn_snark.source.pending_coinbase_stack
pending_coinbase_source_stack
; Pending_coinbase.Stack.equal_var
txn_snark.target.pending_coinbase_stack deleted_stack
]
>>= Boolean.all
in
let%bind nothing_changed =
Boolean.all [ txn_stmt_ledger_hashes_didn't_change; no_coinbases_popped ]
in
let%bind correct_coinbase_status =
let new_root =
transition |> Snark_transition.blockchain_state
|> Blockchain_state.staged_ledger_hash
|> Staged_ledger_hash.pending_coinbase_hash_var
in
Pending_coinbase.Hash.equal_var new_pending_coinbase_hash new_root
in
let%bind () =
with_label __LOC__ (fun () ->
Boolean.Assert.any [ txn_snark_input_correct; nothing_changed ] )
in
let transaction_snark_should_verifiy = Boolean.not nothing_changed in
let%bind result =
Boolean.all [ updated_consensus_state; correct_coinbase_status ]
in
let%map () =
as_prover
As_prover.(
Let_syntax.(
let%map txn_snark_input_correct =
read Boolean.typ txn_snark_input_correct
and nothing_changed = read Boolean.typ nothing_changed
and no_coinbases_popped = read Boolean.typ no_coinbases_popped
and updated_consensus_state =
read Boolean.typ updated_consensus_state
and correct_coinbase_status =
read Boolean.typ correct_coinbase_status
and result = read Boolean.typ result in
[%log trace]
"blockchain snark update success: $result = \
(transaction_snark_input_correct=$transaction_snark_input_correct \
∨ nothing_changed \
(no_coinbases_popped=$no_coinbases_popped)=$nothing_changed) ∧ \
updated_consensus_state=$updated_consensus_state ∧ \
correct_coinbase_status=$correct_coinbase_status"
~metadata:
[ ( "transaction_snark_input_correct"
, `Bool txn_snark_input_correct )
; ("nothing_changed", `Bool nothing_changed)
; ("updated_consensus_state", `Bool updated_consensus_state)
; ("correct_coinbase_status", `Bool correct_coinbase_status)
; ("result", `Bool result)
; ("no_coinbases_popped", `Bool no_coinbases_popped)
]))
in
(transaction_snark_should_verifiy, result)
in
let txn_snark_should_verify =
match proof_level with
| Check | None ->
Boolean.false_
| Full ->
txn_snark_should_verify
in
let prev_should_verify =
match proof_level with
| Check | None ->
Boolean.false_
| Full ->
Boolean.not is_base_case
in
let%bind () =
with_label __LOC__ (fun () -> Boolean.Assert.any [ is_base_case; success ])
in
let%bind previous_blockchain_proof =
exists (Typ.Internal.ref ()) ~request:(As_prover.return Prev_state_proof)
in
let%map txn_snark_proof =
exists (Typ.Internal.ref ()) ~request:(As_prover.return Txn_snark_proof)
in
( { Pickles.Inductive_rule.Previous_proof_statement.public_input =
previous_blockchain_proof_input
; proof = previous_blockchain_proof
; proof_must_verify = prev_should_verify
}
, { Pickles.Inductive_rule.Previous_proof_statement.public_input = txn_snark
; proof = txn_snark_proof
; proof_must_verify = txn_snark_should_verify
} )
module Statement = struct
type t = Protocol_state.Value.t
let to_field_elements (t : t) : Tick.Field.t array =
[| (Protocol_state.hashes t).state_hash |]
end
module Statement_var = struct
type t = Protocol_state.Value.t Data_as_hash.t
end
type tag = (Statement_var.t, Statement.t, Nat.N2.n, Nat.N1.n) Pickles.Tag.t
let typ = Data_as_hash.typ ~hash:(fun t -> (Protocol_state.hashes t).state_hash)
let check w ?handler ~proof_level ~constraint_constants new_state_hash :
unit Or_error.t =
let open Tick in
check
(Fn.flip handle (wrap_handler handler w) (fun () ->
let%bind curr =
exists typ ~compute:(As_prover.return new_state_hash)
in
step ~proof_level ~constraint_constants ~logger:(Logger.create ()) curr )
)
let rule ~proof_level ~constraint_constants transaction_snark self :
_ Pickles.Inductive_rule.t =
{ identifier = "step"
; prevs = [ self; transaction_snark ]
; main =
(fun { public_input = x } ->
let b1, b2 =
Run.run_checked
(step ~proof_level ~constraint_constants ~logger:(Logger.create ())
x )
in
{ previous_proof_statements = [ b1; b2 ]
; public_output = ()
; auxiliary_output = ()
} )
; feature_flags = Pickles_types.Plonk_types.Features.none_bool
}
module type S = sig
module Proof :
Pickles.Proof_intf
with type t = (Nat.N2.n, Nat.N2.n) Pickles.Proof.t
and type statement = Protocol_state.Value.t
val tag : tag
val cache_handle : Pickles.Cache_handle.t
open Nat
val step :
Witness.t
-> ( Protocol_state.Value.t * (Transaction_snark.Statement.With_sok.t * unit)
, N2.n * (N2.n * unit)
, N1.n * (N5.n * unit)
, Protocol_state.Value.t
, (unit * unit * Proof.t) Async.Deferred.t )
Pickles.Prover.t
val constraint_system_digests : (string * Md5_lib.t) list Lazy.t
end
let verify ts ~key = Pickles.verify (module Nat.N2) (module Statement) key ts
let constraint_system_digests ~proof_level ~constraint_constants () =
let digest = Tick.R1CS_constraint_system.digest in
[ ( "blockchain-step"
, digest
(let main x =
let open Tick in
let%map _ =
step ~proof_level ~constraint_constants ~logger:(Logger.create ())
x
in
()
in
Tick.constraint_system ~input_typ:typ
~return_typ:(Snarky_backendless.Typ.unit ())
main ) )
]
module Make (T : sig
val tag : Transaction_snark.tag
val constraint_constants : Genesis_constants.Constraint_constants.t
val proof_level : Genesis_constants.Proof_level.t
end) : S = struct
open T
let tag, cache_handle, p, Pickles.Provers.[ step ] =
Pickles.compile () ~cache:Cache_dir.cache ~public_input:(Input typ)
~auxiliary_typ:Typ.unit
~branches:(module Nat.N1)
~max_proofs_verified:(module Nat.N2)
~name:"blockchain-snark"
~constraint_constants:
(Genesis_constants.Constraint_constants.to_snark_keys_header
constraint_constants )
~choices:(fun ~self ->
[ rule ~proof_level ~constraint_constants T.tag self ] )
let step = with_handler step
let constraint_system_digests =
lazy (constraint_system_digests ~proof_level ~constraint_constants ())
module Proof = (val p)
end
| null |
https://raw.githubusercontent.com/MinaProtocol/mina/f3e74168f08a2ce65331ca718f88d214da71370f/src/lib/blockchain_snark/blockchain_snark_state.ml
|
ocaml
|
TODO: Clean up the handler composition interface.
only increase the supply if the txn statement represents a new ledger transition
If snarked ledger hash did not change (no new ledger proof) then pop_coinbases should be a no-op
TODO: Any assertion about the local state and sok digest
in the statement required?
|
open Core_kernel
open Snark_params
open Tick
open Mina_base
open Mina_state
open Pickles_types
include struct
open Snarky_backendless.Request
type _ t +=
| Prev_state : Protocol_state.Value.t t
| Prev_state_proof : (Nat.N2.n, Nat.N2.n) Pickles.Proof.t t
| Transition : Snark_transition.Value.t t
| Txn_snark : Transaction_snark.Statement.With_sok.t t
| Txn_snark_proof : (Nat.N2.n, Nat.N2.n) Pickles.Proof.t t
end
module Witness = struct
type t =
{ prev_state : Protocol_state.Value.t
; prev_state_proof : (Nat.N2.n, Nat.N2.n) Pickles.Proof.t
; transition : Snark_transition.Value.t
; txn_snark : Transaction_snark.Statement.With_sok.t
; txn_snark_proof : (Nat.N2.n, Nat.N2.n) Pickles.Proof.t
}
end
let blockchain_handler on_unhandled
{ Witness.prev_state
; prev_state_proof
; transition
; txn_snark
; txn_snark_proof
} =
let open Snarky_backendless.Request in
fun (With { request; respond } as r) ->
let k x = respond (Provide x) in
match request with
| Prev_state ->
k prev_state
| Prev_state_proof ->
k prev_state_proof
| Transition ->
k transition
| Txn_snark ->
k txn_snark
| Txn_snark_proof ->
k txn_snark_proof
| _ ->
on_unhandled r
let wrap_handler h w =
match h with
| None ->
blockchain_handler
(fun (Snarky_backendless.Request.With { respond; _ }) ->
respond Unhandled )
w
| Some h ->
fun r -> blockchain_handler h w r
let with_handler k w ?handler =
let h = wrap_handler handler w in
k ?handler:(Some h)
module Impl = Pickles.Impls.Step
let non_pc_registers_equal_var t1 t2 =
Impl.make_checked (fun () ->
let module F = Core_kernel.Field in
let ( ! ) eq x1 x2 = Impl.run_checked (eq x1 x2) in
let f eq acc field = eq (F.get field t1) (F.get field t2) :: acc in
Registers.Fields.fold ~init:[]
~first_pass_ledger:(f !Frozen_ledger_hash.equal_var)
~second_pass_ledger:(f !Frozen_ledger_hash.equal_var)
~pending_coinbase_stack:(fun acc f ->
let () = F.get f t1 and () = F.get f t2 in
acc )
~local_state:(fun acc f ->
Local_state.Checked.equal' (F.get f t1) (F.get f t2) @ acc )
|> Impl.Boolean.all )
let txn_statement_ledger_hashes_equal
(s1 : Transaction_snark.Statement.Checked.t)
(s2 : Transaction_snark.Statement.Checked.t) =
Impl.make_checked (fun () ->
let module F = Core_kernel.Field in
let ( ! ) x = Impl.run_checked x in
let source_eq =
!(non_pc_registers_equal_var
{ s1.source with pending_coinbase_stack = () }
{ s2.source with pending_coinbase_stack = () } )
in
let target_eq =
!(non_pc_registers_equal_var
{ s1.target with pending_coinbase_stack = () }
{ s2.target with pending_coinbase_stack = () } )
in
let left_ledger_eq =
!(Frozen_ledger_hash.equal_var s1.connecting_ledger_left
s2.connecting_ledger_left )
in
let right_ledger_eq =
!(Frozen_ledger_hash.equal_var s1.connecting_ledger_right
s2.connecting_ledger_right )
in
let supply_increase_eq =
!(Currency.Amount.Signed.Checked.equal s1.supply_increase
s2.supply_increase )
in
Impl.Boolean.all
[ source_eq
; target_eq
; left_ledger_eq
; right_ledger_eq
; supply_increase_eq
] )
Blockchain_snark ~old ~nonce ~ledger_snark ~ledger_hash ~timestamp ~new_hash
Input :
old : Blockchain.t
old_snark : proof
nonce : int
: proof
ledger_hash : Ledger_hash.t
timestamp : Time.t
new_hash : State_hash.t
Witness :
transition : Transition.t
such that
the old_snark verifies against old
new = update_with_asserts(old , nonce , timestamp , ledger_hash )
hash(new ) = new_hash
the work_snark verifies against the old.ledger_hash and new_ledger_hash
new.timestamp > old.timestamp
transition consensus data is valid
new consensus state is a function of the old consensus state
Input:
old : Blockchain.t
old_snark : proof
nonce : int
work_snark : proof
ledger_hash : Ledger_hash.t
timestamp : Time.t
new_hash : State_hash.t
Witness:
transition : Transition.t
such that
the old_snark verifies against old
new = update_with_asserts(old, nonce, timestamp, ledger_hash)
hash(new) = new_hash
the work_snark verifies against the old.ledger_hash and new_ledger_hash
new.timestamp > old.timestamp
transition consensus data is valid
new consensus state is a function of the old consensus state
*)
let%snarkydef_ step ~(logger : Logger.t)
~(proof_level : Genesis_constants.Proof_level.t)
~(constraint_constants : Genesis_constants.Constraint_constants.t) new_state
: _ Tick.Checked.t =
let new_state_hash =
State_hash.var_of_hash_packed (Data_as_hash.hash new_state)
in
let%bind transition =
with_label __LOC__ (fun () ->
exists Snark_transition.typ ~request:(As_prover.return Transition) )
in
let%bind txn_snark =
with_label __LOC__ (fun () ->
exists Transaction_snark.Statement.With_sok.typ
~request:(As_prover.return Txn_snark) )
in
let%bind ( previous_state
, previous_state_hash
, previous_blockchain_proof_input
, previous_state_body_hash ) =
let%bind prev_state_ref =
with_label __LOC__ (fun () ->
exists (Typ.Internal.ref ()) ~request:(As_prover.return Prev_state) )
in
let%bind t =
with_label __LOC__ (fun () ->
exists
(Protocol_state.typ ~constraint_constants)
~compute:(As_prover.Ref.get prev_state_ref) )
in
let%map previous_state_hash, body = Protocol_state.hash_checked t in
let previous_blockchain_proof_input =
Data_as_hash.make_unsafe
(State_hash.var_to_field previous_state_hash)
prev_state_ref
in
(t, previous_state_hash, previous_blockchain_proof_input, body)
in
let%bind txn_stmt_ledger_hashes_didn't_change =
txn_statement_ledger_hashes_equal
(previous_state |> Protocol_state.blockchain_state).ledger_proof_statement
{ txn_snark with sok_digest = () }
in
let%bind supply_increase =
Currency.Amount.(
Signed.Checked.if_ txn_stmt_ledger_hashes_didn't_change
~then_:
(Signed.create_var ~magnitude:(var_of_t zero) ~sgn:Sgn.Checked.pos)
~else_:txn_snark.supply_increase)
in
let%bind `Success updated_consensus_state, consensus_state =
with_label __LOC__ (fun () ->
Consensus_state_hooks.next_state_checked ~constraint_constants
~prev_state:previous_state ~prev_state_hash:previous_state_hash
transition supply_increase )
in
let global_slot =
Consensus.Data.Consensus_state.global_slot_since_genesis_var consensus_state
in
let supercharge_coinbase =
Consensus.Data.Consensus_state.supercharge_coinbase_var consensus_state
in
let prev_pending_coinbase_root =
previous_state |> Protocol_state.blockchain_state
|> Blockchain_state.staged_ledger_hash
|> Staged_ledger_hash.pending_coinbase_hash_var
in
let%bind genesis_state_hash =
get the genesis state hash from previous state unless previous state is the genesis state
Protocol_state.genesis_state_hash_checked ~state_hash:previous_state_hash
previous_state
in
let%bind new_state, is_base_case =
let t =
Protocol_state.create_var ~previous_state_hash ~genesis_state_hash
~blockchain_state:(Snark_transition.blockchain_state transition)
~consensus_state
~constants:(Protocol_state.constants previous_state)
in
let%bind is_base_case =
Protocol_state.consensus_state t
|> Consensus.Data.Consensus_state.is_genesis_state_var
in
let%bind previous_state_hash =
match constraint_constants.fork with
| Some { previous_state_hash = fork_prev; _ } ->
State_hash.if_ is_base_case
~then_:(State_hash.var_of_t fork_prev)
~else_:t.previous_state_hash
| None ->
Checked.return t.previous_state_hash
in
let t = { t with previous_state_hash } in
let%map () =
let%bind h, _ = Protocol_state.hash_checked t in
with_label __LOC__ (fun () -> State_hash.assert_equal h new_state_hash)
in
(t, is_base_case)
in
let%bind txn_snark_should_verify, success =
let%bind new_pending_coinbase_hash, deleted_stack, no_coinbases_popped =
let coinbase_receiver =
Consensus.Data.Consensus_state.coinbase_receiver_var consensus_state
in
let%bind root_after_delete, deleted_stack =
Pending_coinbase.Checked.pop_coinbases ~constraint_constants
prev_pending_coinbase_root
~proof_emitted:(Boolean.not txn_stmt_ledger_hashes_didn't_change)
in
let%bind no_coinbases_popped =
Pending_coinbase.Hash.equal_var root_after_delete
prev_pending_coinbase_root
in
new stack or update one
let%map new_root =
with_label __LOC__ (fun () ->
Pending_coinbase.Checked.add_coinbase ~constraint_constants
root_after_delete
(Snark_transition.pending_coinbase_update transition)
~coinbase_receiver ~supercharge_coinbase previous_state_body_hash
global_slot )
in
(new_root, deleted_stack, no_coinbases_popped)
in
let current_ledger_statement =
(Protocol_state.blockchain_state new_state).ledger_proof_statement
in
let pending_coinbase_source_stack =
Pending_coinbase.Stack.Checked.create_with deleted_stack
in
let%bind txn_snark_input_correct =
let open Checked in
let%bind () =
Fee_excess.(assert_equal_checked (var_of_t zero) txn_snark.fee_excess)
in
let previous_ledger_statement =
(Protocol_state.blockchain_state previous_state).ledger_proof_statement
in
let ledger_statement_valid =
Impl.make_checked (fun () ->
Snarked_ledger_state.(
valid_ledgers_at_merge_checked
(Statement_ledgers.of_statement previous_ledger_statement)
(Statement_ledgers.of_statement current_ledger_statement)) )
in
all
[ ledger_statement_valid
; Pending_coinbase.Stack.equal_var
txn_snark.source.pending_coinbase_stack
pending_coinbase_source_stack
; Pending_coinbase.Stack.equal_var
txn_snark.target.pending_coinbase_stack deleted_stack
]
>>= Boolean.all
in
let%bind nothing_changed =
Boolean.all [ txn_stmt_ledger_hashes_didn't_change; no_coinbases_popped ]
in
let%bind correct_coinbase_status =
let new_root =
transition |> Snark_transition.blockchain_state
|> Blockchain_state.staged_ledger_hash
|> Staged_ledger_hash.pending_coinbase_hash_var
in
Pending_coinbase.Hash.equal_var new_pending_coinbase_hash new_root
in
let%bind () =
with_label __LOC__ (fun () ->
Boolean.Assert.any [ txn_snark_input_correct; nothing_changed ] )
in
let transaction_snark_should_verifiy = Boolean.not nothing_changed in
let%bind result =
Boolean.all [ updated_consensus_state; correct_coinbase_status ]
in
let%map () =
as_prover
As_prover.(
Let_syntax.(
let%map txn_snark_input_correct =
read Boolean.typ txn_snark_input_correct
and nothing_changed = read Boolean.typ nothing_changed
and no_coinbases_popped = read Boolean.typ no_coinbases_popped
and updated_consensus_state =
read Boolean.typ updated_consensus_state
and correct_coinbase_status =
read Boolean.typ correct_coinbase_status
and result = read Boolean.typ result in
[%log trace]
"blockchain snark update success: $result = \
(transaction_snark_input_correct=$transaction_snark_input_correct \
∨ nothing_changed \
(no_coinbases_popped=$no_coinbases_popped)=$nothing_changed) ∧ \
updated_consensus_state=$updated_consensus_state ∧ \
correct_coinbase_status=$correct_coinbase_status"
~metadata:
[ ( "transaction_snark_input_correct"
, `Bool txn_snark_input_correct )
; ("nothing_changed", `Bool nothing_changed)
; ("updated_consensus_state", `Bool updated_consensus_state)
; ("correct_coinbase_status", `Bool correct_coinbase_status)
; ("result", `Bool result)
; ("no_coinbases_popped", `Bool no_coinbases_popped)
]))
in
(transaction_snark_should_verifiy, result)
in
let txn_snark_should_verify =
match proof_level with
| Check | None ->
Boolean.false_
| Full ->
txn_snark_should_verify
in
let prev_should_verify =
match proof_level with
| Check | None ->
Boolean.false_
| Full ->
Boolean.not is_base_case
in
let%bind () =
with_label __LOC__ (fun () -> Boolean.Assert.any [ is_base_case; success ])
in
let%bind previous_blockchain_proof =
exists (Typ.Internal.ref ()) ~request:(As_prover.return Prev_state_proof)
in
let%map txn_snark_proof =
exists (Typ.Internal.ref ()) ~request:(As_prover.return Txn_snark_proof)
in
( { Pickles.Inductive_rule.Previous_proof_statement.public_input =
previous_blockchain_proof_input
; proof = previous_blockchain_proof
; proof_must_verify = prev_should_verify
}
, { Pickles.Inductive_rule.Previous_proof_statement.public_input = txn_snark
; proof = txn_snark_proof
; proof_must_verify = txn_snark_should_verify
} )
module Statement = struct
type t = Protocol_state.Value.t
let to_field_elements (t : t) : Tick.Field.t array =
[| (Protocol_state.hashes t).state_hash |]
end
module Statement_var = struct
type t = Protocol_state.Value.t Data_as_hash.t
end
type tag = (Statement_var.t, Statement.t, Nat.N2.n, Nat.N1.n) Pickles.Tag.t
let typ = Data_as_hash.typ ~hash:(fun t -> (Protocol_state.hashes t).state_hash)
let check w ?handler ~proof_level ~constraint_constants new_state_hash :
unit Or_error.t =
let open Tick in
check
(Fn.flip handle (wrap_handler handler w) (fun () ->
let%bind curr =
exists typ ~compute:(As_prover.return new_state_hash)
in
step ~proof_level ~constraint_constants ~logger:(Logger.create ()) curr )
)
let rule ~proof_level ~constraint_constants transaction_snark self :
_ Pickles.Inductive_rule.t =
{ identifier = "step"
; prevs = [ self; transaction_snark ]
; main =
(fun { public_input = x } ->
let b1, b2 =
Run.run_checked
(step ~proof_level ~constraint_constants ~logger:(Logger.create ())
x )
in
{ previous_proof_statements = [ b1; b2 ]
; public_output = ()
; auxiliary_output = ()
} )
; feature_flags = Pickles_types.Plonk_types.Features.none_bool
}
module type S = sig
module Proof :
Pickles.Proof_intf
with type t = (Nat.N2.n, Nat.N2.n) Pickles.Proof.t
and type statement = Protocol_state.Value.t
val tag : tag
val cache_handle : Pickles.Cache_handle.t
open Nat
val step :
Witness.t
-> ( Protocol_state.Value.t * (Transaction_snark.Statement.With_sok.t * unit)
, N2.n * (N2.n * unit)
, N1.n * (N5.n * unit)
, Protocol_state.Value.t
, (unit * unit * Proof.t) Async.Deferred.t )
Pickles.Prover.t
val constraint_system_digests : (string * Md5_lib.t) list Lazy.t
end
let verify ts ~key = Pickles.verify (module Nat.N2) (module Statement) key ts
let constraint_system_digests ~proof_level ~constraint_constants () =
let digest = Tick.R1CS_constraint_system.digest in
[ ( "blockchain-step"
, digest
(let main x =
let open Tick in
let%map _ =
step ~proof_level ~constraint_constants ~logger:(Logger.create ())
x
in
()
in
Tick.constraint_system ~input_typ:typ
~return_typ:(Snarky_backendless.Typ.unit ())
main ) )
]
module Make (T : sig
val tag : Transaction_snark.tag
val constraint_constants : Genesis_constants.Constraint_constants.t
val proof_level : Genesis_constants.Proof_level.t
end) : S = struct
open T
let tag, cache_handle, p, Pickles.Provers.[ step ] =
Pickles.compile () ~cache:Cache_dir.cache ~public_input:(Input typ)
~auxiliary_typ:Typ.unit
~branches:(module Nat.N1)
~max_proofs_verified:(module Nat.N2)
~name:"blockchain-snark"
~constraint_constants:
(Genesis_constants.Constraint_constants.to_snark_keys_header
constraint_constants )
~choices:(fun ~self ->
[ rule ~proof_level ~constraint_constants T.tag self ] )
let step = with_handler step
let constraint_system_digests =
lazy (constraint_system_digests ~proof_level ~constraint_constants ())
module Proof = (val p)
end
|
633fb7542c4c6b4c68903f53827177a087a24adcc7bf94e9ecdaefb04d634ede
|
bsansouci/bsb-native
|
bytelink.ml
|
(***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
Link a set of .cmo files and produce a bytecode executable .
open Misc
open Config
open Cmo_format
type error =
File_not_found of string
| Not_an_object_file of string
| Wrong_object_name of string
| Symbol_error of string * Symtable.error
| Inconsistent_import of string * string * string
| Custom_runtime
| File_exists of string
| Cannot_open_dll of string
| Not_compatible_32
exception Error of error
type link_action =
Link_object of string * compilation_unit
(* Name of .cmo file and descriptor of the unit *)
| Link_archive of string * compilation_unit list
(* Name of .cma file and descriptors of the units to be linked. *)
(* Add C objects and options from a library descriptor *)
(* Ignore them if -noautolink or -use-runtime or -use-prim was given *)
let lib_ccobjs = ref []
let lib_ccopts = ref []
let lib_dllibs = ref []
let add_ccobjs origin l =
if not !Clflags.no_auto_link then begin
if
String.length !Clflags.use_runtime = 0
&& String.length !Clflags.use_prims = 0
then begin
if l.lib_custom then Clflags.custom_runtime := true;
lib_ccobjs := l.lib_ccobjs @ !lib_ccobjs;
let replace_origin = Misc.replace_substring ~before:"$CAMLORIGIN" ~after:origin in
lib_ccopts := List.map replace_origin l.lib_ccopts @ !lib_ccopts;
end;
lib_dllibs := l.lib_dllibs @ !lib_dllibs
end
A note on ccobj ordering :
- Clflags.ccobjs is in reverse order w.r.t . what was given on the
ocamlc command line ;
- l.lib_ccobjs is also in reverse order w.r.t . what was given on the
ocamlc -a command line when the library was created ;
- Clflags.ccobjs is reversed just before calling the C compiler for the
custom link ;
- .cma files on the command line of ocamlc are scanned right to left ;
- Before linking , we add lib_ccobjs after Clflags.ccobjs .
Thus , for ocamlc a.cma b.cma obj1 obj2
where a.cma was built with ocamlc -i ...
and was built with ocamlc -i ...
starts as [ ] ,
becomes when is scanned ,
then obja2 obja1 objb2 objb1 when a.cma is scanned .
Clflags.ccobjs was initially obj2 obj1 .
and is set to obj2 obj1 obja2 obja1 objb2 objb1 .
Finally , the C compiler is given objb1 objb2 obj1 obj2 ,
which is what we need . ( If b depends on a , a.cma must appear before
b.cma , but b 's C libraries must appear before a 's C libraries . )
- Clflags.ccobjs is in reverse order w.r.t. what was given on the
ocamlc command line;
- l.lib_ccobjs is also in reverse order w.r.t. what was given on the
ocamlc -a command line when the library was created;
- Clflags.ccobjs is reversed just before calling the C compiler for the
custom link;
- .cma files on the command line of ocamlc are scanned right to left;
- Before linking, we add lib_ccobjs after Clflags.ccobjs.
Thus, for ocamlc a.cma b.cma obj1 obj2
where a.cma was built with ocamlc -i ... obja1 obja2
and b.cma was built with ocamlc -i ... objb1 objb2
lib_ccobjs starts as [],
becomes objb2 objb1 when b.cma is scanned,
then obja2 obja1 objb2 objb1 when a.cma is scanned.
Clflags.ccobjs was initially obj2 obj1.
and is set to obj2 obj1 obja2 obja1 objb2 objb1.
Finally, the C compiler is given objb1 objb2 obja1 obja2 obj1 obj2,
which is what we need. (If b depends on a, a.cma must appear before
b.cma, but b's C libraries must appear before a's C libraries.)
*)
First pass : determine which units are needed
module IdentSet =
Set.Make(struct
type t = Ident.t
let compare = compare
end)
let missing_globals = ref IdentSet.empty
let is_required (rel, pos) =
match rel with
Reloc_setglobal id ->
IdentSet.mem id !missing_globals
| _ -> false
let add_required (rel, pos) =
match rel with
Reloc_getglobal id ->
missing_globals := IdentSet.add id !missing_globals
| _ -> ()
let remove_required (rel, pos) =
match rel with
Reloc_setglobal id ->
missing_globals := IdentSet.remove id !missing_globals
| _ -> ()
let scan_file obj_name tolink =
let file_name =
try
find_in_path !load_path obj_name
with Not_found ->
raise(Error(File_not_found obj_name)) in
let ic = open_in_bin file_name in
try
let buffer = really_input_string ic (String.length cmo_magic_number) in
if buffer = cmo_magic_number then begin
(* This is a .cmo file. It must be linked in any case.
Read the relocation information to see which modules it
requires. *)
let compunit_pos = input_binary_int ic in (* Go to descriptor *)
seek_in ic compunit_pos;
let compunit = (input_value ic : compilation_unit) in
close_in ic;
List.iter add_required compunit.cu_reloc;
Link_object(file_name, compunit) :: tolink
end
else if buffer = cma_magic_number then begin
(* This is an archive file. Each unit contained in it will be linked
in only if needed. *)
let pos_toc = input_binary_int ic in (* Go to table of contents *)
seek_in ic pos_toc;
let toc = (input_value ic : library) in
close_in ic;
add_ccobjs (Filename.dirname file_name) toc;
let required =
List.fold_right
(fun compunit reqd ->
if compunit.cu_force_link
|| !Clflags.link_everything
|| List.exists is_required compunit.cu_reloc
then begin
List.iter remove_required compunit.cu_reloc;
List.iter add_required compunit.cu_reloc;
compunit :: reqd
end else
reqd)
toc.lib_units [] in
Link_archive(file_name, required) :: tolink
end
else raise(Error(Not_an_object_file file_name))
with
End_of_file -> close_in ic; raise(Error(Not_an_object_file file_name))
| x -> close_in ic; raise x
Second pass : link in the required units
(* Consistency check between interfaces *)
let crc_interfaces = Consistbl.create ()
let interfaces = ref ([] : string list)
let implementations_defined = ref ([] : (string * string) list)
let check_consistency ppf file_name cu =
begin try
List.iter
(fun (name, crco) ->
interfaces := name :: !interfaces;
match crco with
None -> ()
| Some crc ->
if name = cu.cu_name
then Consistbl.set crc_interfaces name crc file_name
else Consistbl.check crc_interfaces name crc file_name)
cu.cu_imports
with Consistbl.Inconsistency(name, user, auth) ->
raise(Error(Inconsistent_import(name, user, auth)))
end;
begin try
let source = List.assoc cu.cu_name !implementations_defined in
Location.print_warning (Location.in_file file_name) ppf
(Warnings.Multiple_definition(cu.cu_name,
Location.show_filename file_name,
Location.show_filename source))
with Not_found -> ()
end;
implementations_defined :=
(cu.cu_name, file_name) :: !implementations_defined
let extract_crc_interfaces () =
Consistbl.extract !interfaces crc_interfaces
let clear_crc_interfaces () =
Consistbl.clear crc_interfaces;
interfaces := []
(* Record compilation events *)
let debug_info = ref ([] : (int * Instruct.debug_event list * string list) list)
(* Link in a compilation unit *)
let link_compunit ppf output_fun currpos_fun inchan file_name compunit =
check_consistency ppf file_name compunit;
seek_in inchan compunit.cu_pos;
let code_block = LongString.input_bytes inchan compunit.cu_codesize in
Symtable.ls_patch_object code_block compunit.cu_reloc;
if !Clflags.debug && compunit.cu_debug > 0 then begin
seek_in inchan compunit.cu_debug;
let debug_event_list : Instruct.debug_event list = input_value inchan in
let debug_dirs : string list = input_value inchan in
let file_path = Filename.dirname (Location.absolute_path file_name) in
let debug_dirs =
if List.mem file_path debug_dirs
then debug_dirs
else file_path :: debug_dirs in
debug_info := (currpos_fun(), debug_event_list, debug_dirs) :: !debug_info
end;
Array.iter output_fun code_block;
if !Clflags.link_everything then
List.iter Symtable.require_primitive compunit.cu_primitives
(* Link in a .cmo file *)
let link_object ppf output_fun currpos_fun file_name compunit =
let inchan = open_in_bin file_name in
try
link_compunit ppf output_fun currpos_fun inchan file_name compunit;
close_in inchan
with
Symtable.Error msg ->
close_in inchan; raise(Error(Symbol_error(file_name, msg)))
| x ->
close_in inchan; raise x
(* Link in a .cma file *)
let link_archive ppf output_fun currpos_fun file_name units_required =
let inchan = open_in_bin file_name in
try
List.iter
(fun cu ->
let name = file_name ^ "(" ^ cu.cu_name ^ ")" in
try
link_compunit ppf output_fun currpos_fun inchan name cu
with Symtable.Error msg ->
raise(Error(Symbol_error(name, msg))))
units_required;
close_in inchan
with x -> close_in inchan; raise x
(* Link in a .cmo or .cma file *)
let link_file ppf output_fun currpos_fun = function
Link_object(file_name, unit) ->
link_object ppf output_fun currpos_fun file_name unit
| Link_archive(file_name, units) ->
link_archive ppf output_fun currpos_fun file_name units
(* Output the debugging information *)
Format is :
< int32 > number of event lists
< int32 > offset of first event list
< output_value > first event list
...
< int32 > offset of last event list
< output_value > last event list
<int32> number of event lists
<int32> offset of first event list
<output_value> first event list
...
<int32> offset of last event list
<output_value> last event list *)
let output_debug_info oc =
output_binary_int oc (List.length !debug_info);
List.iter
(fun (ofs, evl, debug_dirs) ->
output_binary_int oc ofs;
output_value oc evl;
output_value oc debug_dirs)
!debug_info;
debug_info := []
(* Output a list of strings with 0-termination *)
let output_stringlist oc l =
List.iter (fun s -> output_string oc s; output_byte oc 0) l
Transform a file name into an absolute file name
let make_absolute file =
if Filename.is_relative file
then Filename.concat (Sys.getcwd()) file
else file
(* Create a bytecode executable file *)
let link_bytecode ppf tolink exec_name standalone =
(* Avoid the case where the specified exec output file is the same as
one of the objects to be linked *)
List.iter (function
| Link_object(file_name, _) when file_name = exec_name ->
raise (Error (Wrong_object_name exec_name));
| _ -> ()) tolink;
avoid permission problems , cf PR#1911
let outchan =
open_out_gen [Open_wronly; Open_trunc; Open_creat; Open_binary]
0o777 exec_name in
try
if standalone then begin
(* Copy the header *)
try
begin match Sys.os_type with
"Win32" | "Cygwin" ->
let header = if String.length !Clflags.use_runtime > 0 then "camlheader_ur" else "camlheader" ^ !Clflags.runtime_variant in
let inchan = open_in_bin (find_in_path !load_path header) in
copy_file inchan outchan;
close_in inchan
| _ ->
output_string outchan ("#!" ^ (make_absolute standard_runtime));
output_char outchan '\n';
end
with Not_found | Sys_error _ -> ()
end;
Bytesections.init_record outchan;
let ( // ) = Filename.concat in
(* The path to the bytecode interpreter (in use_runtime mode) *)
if String.length !Clflags.use_runtime > 0 then begin
output_string outchan ((make_absolute !Clflags.use_runtime));
output_char outchan '\n';
Bytesections.record outchan "RNTM"
end else begin
output_string outchan (make_absolute ((Filename.dirname Sys.executable_name) // "bin" // "ocamlrun.exe"));
output_char outchan '\n';
Bytesections.record outchan "RNTM"
end;
(* The bytecode *)
let start_code = pos_out outchan in
Symtable.init();
clear_crc_interfaces ();
let sharedobjs = List.map Dll.extract_dll_name !Clflags.dllibs in
let check_dlls = standalone && Config.target = Config.host in
if check_dlls then begin
Initialize the DLL machinery
Dll.init_compile !Clflags.no_std_include;
Dll.add_path !load_path;
try Dll.open_dlls Dll.For_checking sharedobjs
with Failure reason -> raise(Error(Cannot_open_dll reason))
end;
let output_fun = output_bytes outchan
and currpos_fun () = pos_out outchan - start_code in
List.iter (link_file ppf output_fun currpos_fun) tolink;
if check_dlls then Dll.close_all_dlls();
(* The final STOP instruction *)
output_byte outchan Opcodes.opSTOP;
output_byte outchan 0; output_byte outchan 0; output_byte outchan 0;
Bytesections.record outchan "CODE";
(* DLL stuff *)
if standalone then begin
(* The extra search path for DLLs *)
output_stringlist outchan (((Filename.dirname Sys.executable_name) // "lib" // "ocaml" // "stublibs") :: !Clflags.dllpaths);
Bytesections.record outchan "DLPT";
(* The names of the DLLs *)
output_stringlist outchan sharedobjs;
Bytesections.record outchan "DLLS"
end;
(* The names of all primitives *)
Symtable.output_primitive_names outchan;
Bytesections.record outchan "PRIM";
(* The table of global data *)
begin try
Marshal.to_channel outchan (Symtable.initial_global_table())
(if !Clflags.bytecode_compatible_32
then [Marshal.Compat_32] else [])
with Failure _ ->
raise (Error Not_compatible_32)
end;
Bytesections.record outchan "DATA";
(* The map of global identifiers *)
Symtable.output_global_map outchan;
Bytesections.record outchan "SYMB";
CRCs for modules
output_value outchan (extract_crc_interfaces());
Bytesections.record outchan "CRCS";
(* Debug info *)
if !Clflags.debug then begin
output_debug_info outchan;
Bytesections.record outchan "DBUG"
end;
(* The table of contents and the trailer *)
Bytesections.write_toc_and_trailer outchan;
close_out outchan
with x ->
close_out outchan;
remove_file exec_name;
raise x
(* Output a string as a C array of unsigned ints *)
let output_code_string_counter = ref 0
let output_code_string outchan code =
let pos = ref 0 in
let len = Bytes.length code in
while !pos < len do
let c1 = Char.code(Bytes.get code !pos) in
let c2 = Char.code(Bytes.get code (!pos + 1)) in
let c3 = Char.code(Bytes.get code (!pos + 2)) in
let c4 = Char.code(Bytes.get code (!pos + 3)) in
pos := !pos + 4;
Printf.fprintf outchan "0x%02x%02x%02x%02x, " c4 c3 c2 c1;
incr output_code_string_counter;
if !output_code_string_counter >= 6 then begin
output_char outchan '\n';
output_code_string_counter := 0
end
done
(* Output a string as a C string *)
let output_data_string outchan data =
let counter = ref 0 in
for i = 0 to String.length data - 1 do
Printf.fprintf outchan "%d, " (Char.code(data.[i]));
incr counter;
if !counter >= 12 then begin
output_string outchan "\n";
counter := 0
end
done
(* Output a debug stub *)
let output_cds_file outfile =
Misc.remove_file outfile;
let outchan =
open_out_gen [Open_wronly; Open_trunc; Open_creat; Open_binary]
0o777 outfile in
try
Bytesections.init_record outchan;
(* The map of global identifiers *)
Symtable.output_global_map outchan;
Bytesections.record outchan "SYMB";
(* Debug info *)
output_debug_info outchan;
Bytesections.record outchan "DBUG";
(* The table of contents and the trailer *)
Bytesections.write_toc_and_trailer outchan;
close_out outchan
with x ->
close_out outchan;
remove_file outfile;
raise x
(* Output a bytecode executable as a C file *)
let link_bytecode_as_c ppf tolink outfile =
let outchan = open_out outfile in
begin try
(* The bytecode *)
output_string outchan "\
#ifdef __cplusplus\
\nextern \"C\" {\
\n#endif\
\n#include <caml/mlvalues.h>\
\nCAMLextern void caml_startup_code(\
\n code_t code, asize_t code_size,\
\n char *data, asize_t data_size,\
\n char *section_table, asize_t section_table_size,\
\n char **argv);\n";
output_string outchan "static int caml_code[] = {\n";
Symtable.init();
clear_crc_interfaces ();
let currpos = ref 0 in
let output_fun code =
output_code_string outchan code;
currpos := !currpos + Bytes.length code
and currpos_fun () = !currpos in
List.iter (link_file ppf output_fun currpos_fun) tolink;
(* The final STOP instruction *)
Printf.fprintf outchan "\n0x%x};\n\n" Opcodes.opSTOP;
(* The table of global data *)
output_string outchan "static char caml_data[] = {\n";
output_data_string outchan
(Marshal.to_string (Symtable.initial_global_table()) []);
output_string outchan "\n};\n\n";
(* The sections *)
let sections =
[ "SYMB", Symtable.data_global_map();
"PRIM", Obj.repr(Symtable.data_primitive_names());
"CRCS", Obj.repr(extract_crc_interfaces()) ] in
output_string outchan "static char caml_sections[] = {\n";
output_data_string outchan
(Marshal.to_string sections []);
output_string outchan "\n};\n\n";
(* The table of primitives *)
Symtable.output_primitive_table outchan;
(* The entry point *)
output_string outchan "\
\nvoid caml_startup(char ** argv)\
\n{\
\n caml_startup_code(caml_code, sizeof(caml_code),\
\n caml_data, sizeof(caml_data),\
\n caml_sections, sizeof(caml_sections),\
\n argv);\
\n}\
\n#ifdef __cplusplus\
\n}\
\n#endif\n";
close_out outchan
with x ->
close_out outchan;
remove_file outfile;
raise x
end;
if !Clflags.debug then
output_cds_file ((Filename.chop_extension outfile) ^ ".cds")
(* Build a custom runtime *)
let build_custom_runtime prim_name exec_name =
let runtime_lib = "-lcamlrun" ^ !Clflags.runtime_variant in
Ccomp.call_linker Ccomp.Exe exec_name
([prim_name] @ List.rev !Clflags.ccobjs @ [runtime_lib])
(Clflags.std_include_flag "-I" ^ " " ^ Config.bytecomp_c_libraries)
let append_bytecode_and_cleanup bytecode_name exec_name prim_name =
let oc = open_out_gen [Open_wronly; Open_append; Open_binary] 0 exec_name in
let ic = open_in_bin bytecode_name in
copy_file ic oc;
close_in ic;
close_out oc;
remove_file bytecode_name;
remove_file prim_name
(* Fix the name of the output file, if the C compiler changes it behind
our back. *)
let fix_exec_name name =
match Sys.os_type with
"Win32" | "Cygwin" ->
if String.contains name '.' then name else name ^ ".exe"
| _ -> name
(* Main entry point (build a custom runtime if needed) *)
let link ppf objfiles output_name =
let objfiles =
if !Clflags.nopervasives then objfiles
else if !Clflags.output_c_object then "stdlib.cma" :: objfiles
else "stdlib.cma" :: (objfiles @ ["std_exit.cmo"]) in
let tolink = List.fold_right scan_file objfiles [] in
put user 's libs last
Clflags.all_ccopts := !lib_ccopts @ !Clflags.all_ccopts;
put user 's opts first
put user 's DLLs first
if not !Clflags.custom_runtime then
link_bytecode ppf tolink output_name true
else if not !Clflags.output_c_object then begin
let bytecode_name = Filename.temp_file "camlcode" "" in
let prim_name = Filename.temp_file "camlprim" ".c" in
try
link_bytecode ppf tolink bytecode_name false;
let poc = open_out prim_name in
output_string poc "\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
#ifdef _WIN64\n\
#ifdef __MINGW32__\n\
typedef long long value;\n\
#else\n\
typedef __int64 value;\n\
#endif\n\
#else\n\
typedef long value;\n\
#endif\n";
Symtable.output_primitive_table poc;
output_string poc "\
#ifdef __cplusplus\n\
}\n\
#endif\n";
close_out poc;
let exec_name = fix_exec_name output_name in
if not (build_custom_runtime prim_name exec_name)
then raise(Error Custom_runtime);
if !Clflags.make_runtime
then (remove_file bytecode_name; remove_file prim_name)
else append_bytecode_and_cleanup bytecode_name exec_name prim_name
with x ->
remove_file bytecode_name;
remove_file prim_name;
raise x
end else begin
let basename = Filename.chop_extension output_name in
let c_file =
if !Clflags.output_complete_object
then Filename.temp_file "camlobj" ".c"
else basename ^ ".c"
and obj_file =
if !Clflags.output_complete_object
then Filename.temp_file "camlobj" Config.ext_obj
else basename ^ Config.ext_obj
in
if Sys.file_exists c_file then raise(Error(File_exists c_file));
let temps = ref [] in
try
link_bytecode_as_c ppf tolink c_file;
if not (Filename.check_suffix output_name ".c") then begin
temps := c_file :: !temps;
if Ccomp.compile_file c_file <> 0 then raise(Error Custom_runtime);
if not (Filename.check_suffix output_name Config.ext_obj) ||
!Clflags.output_complete_object then begin
temps := obj_file :: !temps;
let mode, c_libs =
if Filename.check_suffix output_name Config.ext_obj
then Ccomp.Partial, ""
else Ccomp.MainDll, Config.bytecomp_c_libraries
in
if not (
let runtime_lib = "-lcamlrun" ^ !Clflags.runtime_variant in
Ccomp.call_linker mode output_name
([obj_file] @ List.rev !Clflags.ccobjs @ [runtime_lib])
c_libs
) then raise (Error Custom_runtime);
end
end;
List.iter remove_file !temps
with x ->
List.iter remove_file !temps;
raise x
end
(* Error report *)
open Format
let report_error ppf = function
| File_not_found name ->
fprintf ppf "Cannot find file %a" Location.print_filename name
| Not_an_object_file name ->
fprintf ppf "The file %a is not a bytecode object file"
Location.print_filename name
| Wrong_object_name name ->
fprintf ppf "The output file %s has the wrong name. The extension implies\
\ an object file but the link step was requested" name
| Symbol_error(name, err) ->
fprintf ppf "Error while linking %a:@ %a" Location.print_filename name
Symtable.report_error err
| Inconsistent_import(intf, file1, file2) ->
fprintf ppf
"@[<hov>Files %a@ and %a@ \
make inconsistent assumptions over interface %s@]"
Location.print_filename file1
Location.print_filename file2
intf
| Custom_runtime ->
fprintf ppf "Error while building custom runtime system"
| File_exists file ->
fprintf ppf "Cannot overwrite existing file %a"
Location.print_filename file
| Cannot_open_dll file ->
fprintf ppf "Error on dynamically loaded library: %a"
Location.print_filename file
| Not_compatible_32 ->
fprintf ppf "Generated bytecode executable cannot be run\
\ on a 32-bit platform"
let () =
Location.register_error_of_exn
(function
| Error err -> Some (Location.error_of_printer_file report_error err)
| _ -> None
)
let reset () =
lib_ccobjs := [];
lib_ccopts := [];
lib_dllibs := [];
missing_globals := IdentSet.empty;
Consistbl.clear crc_interfaces;
implementations_defined := [];
debug_info := [];
output_code_string_counter := 0
| null |
https://raw.githubusercontent.com/bsansouci/bsb-native/9a89457783d6e80deb0fba9ca7372c10a768a9ea/vendor/ocaml/bytecomp/bytelink.ml
|
ocaml
|
*********************************************************************
OCaml
*********************************************************************
Name of .cmo file and descriptor of the unit
Name of .cma file and descriptors of the units to be linked.
Add C objects and options from a library descriptor
Ignore them if -noautolink or -use-runtime or -use-prim was given
This is a .cmo file. It must be linked in any case.
Read the relocation information to see which modules it
requires.
Go to descriptor
This is an archive file. Each unit contained in it will be linked
in only if needed.
Go to table of contents
Consistency check between interfaces
Record compilation events
Link in a compilation unit
Link in a .cmo file
Link in a .cma file
Link in a .cmo or .cma file
Output the debugging information
Output a list of strings with 0-termination
Create a bytecode executable file
Avoid the case where the specified exec output file is the same as
one of the objects to be linked
Copy the header
The path to the bytecode interpreter (in use_runtime mode)
The bytecode
The final STOP instruction
DLL stuff
The extra search path for DLLs
The names of the DLLs
The names of all primitives
The table of global data
The map of global identifiers
Debug info
The table of contents and the trailer
Output a string as a C array of unsigned ints
Output a string as a C string
Output a debug stub
The map of global identifiers
Debug info
The table of contents and the trailer
Output a bytecode executable as a C file
The bytecode
The final STOP instruction
The table of global data
The sections
The table of primitives
The entry point
Build a custom runtime
Fix the name of the output file, if the C compiler changes it behind
our back.
Main entry point (build a custom runtime if needed)
Error report
|
, projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
Link a set of .cmo files and produce a bytecode executable .
open Misc
open Config
open Cmo_format
type error =
File_not_found of string
| Not_an_object_file of string
| Wrong_object_name of string
| Symbol_error of string * Symtable.error
| Inconsistent_import of string * string * string
| Custom_runtime
| File_exists of string
| Cannot_open_dll of string
| Not_compatible_32
exception Error of error
type link_action =
Link_object of string * compilation_unit
| Link_archive of string * compilation_unit list
let lib_ccobjs = ref []
let lib_ccopts = ref []
let lib_dllibs = ref []
let add_ccobjs origin l =
if not !Clflags.no_auto_link then begin
if
String.length !Clflags.use_runtime = 0
&& String.length !Clflags.use_prims = 0
then begin
if l.lib_custom then Clflags.custom_runtime := true;
lib_ccobjs := l.lib_ccobjs @ !lib_ccobjs;
let replace_origin = Misc.replace_substring ~before:"$CAMLORIGIN" ~after:origin in
lib_ccopts := List.map replace_origin l.lib_ccopts @ !lib_ccopts;
end;
lib_dllibs := l.lib_dllibs @ !lib_dllibs
end
A note on ccobj ordering :
- Clflags.ccobjs is in reverse order w.r.t . what was given on the
ocamlc command line ;
- l.lib_ccobjs is also in reverse order w.r.t . what was given on the
ocamlc -a command line when the library was created ;
- Clflags.ccobjs is reversed just before calling the C compiler for the
custom link ;
- .cma files on the command line of ocamlc are scanned right to left ;
- Before linking , we add lib_ccobjs after Clflags.ccobjs .
Thus , for ocamlc a.cma b.cma obj1 obj2
where a.cma was built with ocamlc -i ...
and was built with ocamlc -i ...
starts as [ ] ,
becomes when is scanned ,
then obja2 obja1 objb2 objb1 when a.cma is scanned .
Clflags.ccobjs was initially obj2 obj1 .
and is set to obj2 obj1 obja2 obja1 objb2 objb1 .
Finally , the C compiler is given objb1 objb2 obj1 obj2 ,
which is what we need . ( If b depends on a , a.cma must appear before
b.cma , but b 's C libraries must appear before a 's C libraries . )
- Clflags.ccobjs is in reverse order w.r.t. what was given on the
ocamlc command line;
- l.lib_ccobjs is also in reverse order w.r.t. what was given on the
ocamlc -a command line when the library was created;
- Clflags.ccobjs is reversed just before calling the C compiler for the
custom link;
- .cma files on the command line of ocamlc are scanned right to left;
- Before linking, we add lib_ccobjs after Clflags.ccobjs.
Thus, for ocamlc a.cma b.cma obj1 obj2
where a.cma was built with ocamlc -i ... obja1 obja2
and b.cma was built with ocamlc -i ... objb1 objb2
lib_ccobjs starts as [],
becomes objb2 objb1 when b.cma is scanned,
then obja2 obja1 objb2 objb1 when a.cma is scanned.
Clflags.ccobjs was initially obj2 obj1.
and is set to obj2 obj1 obja2 obja1 objb2 objb1.
Finally, the C compiler is given objb1 objb2 obja1 obja2 obj1 obj2,
which is what we need. (If b depends on a, a.cma must appear before
b.cma, but b's C libraries must appear before a's C libraries.)
*)
First pass : determine which units are needed
module IdentSet =
Set.Make(struct
type t = Ident.t
let compare = compare
end)
let missing_globals = ref IdentSet.empty
let is_required (rel, pos) =
match rel with
Reloc_setglobal id ->
IdentSet.mem id !missing_globals
| _ -> false
let add_required (rel, pos) =
match rel with
Reloc_getglobal id ->
missing_globals := IdentSet.add id !missing_globals
| _ -> ()
let remove_required (rel, pos) =
match rel with
Reloc_setglobal id ->
missing_globals := IdentSet.remove id !missing_globals
| _ -> ()
let scan_file obj_name tolink =
let file_name =
try
find_in_path !load_path obj_name
with Not_found ->
raise(Error(File_not_found obj_name)) in
let ic = open_in_bin file_name in
try
let buffer = really_input_string ic (String.length cmo_magic_number) in
if buffer = cmo_magic_number then begin
seek_in ic compunit_pos;
let compunit = (input_value ic : compilation_unit) in
close_in ic;
List.iter add_required compunit.cu_reloc;
Link_object(file_name, compunit) :: tolink
end
else if buffer = cma_magic_number then begin
seek_in ic pos_toc;
let toc = (input_value ic : library) in
close_in ic;
add_ccobjs (Filename.dirname file_name) toc;
let required =
List.fold_right
(fun compunit reqd ->
if compunit.cu_force_link
|| !Clflags.link_everything
|| List.exists is_required compunit.cu_reloc
then begin
List.iter remove_required compunit.cu_reloc;
List.iter add_required compunit.cu_reloc;
compunit :: reqd
end else
reqd)
toc.lib_units [] in
Link_archive(file_name, required) :: tolink
end
else raise(Error(Not_an_object_file file_name))
with
End_of_file -> close_in ic; raise(Error(Not_an_object_file file_name))
| x -> close_in ic; raise x
Second pass : link in the required units
let crc_interfaces = Consistbl.create ()
let interfaces = ref ([] : string list)
let implementations_defined = ref ([] : (string * string) list)
let check_consistency ppf file_name cu =
begin try
List.iter
(fun (name, crco) ->
interfaces := name :: !interfaces;
match crco with
None -> ()
| Some crc ->
if name = cu.cu_name
then Consistbl.set crc_interfaces name crc file_name
else Consistbl.check crc_interfaces name crc file_name)
cu.cu_imports
with Consistbl.Inconsistency(name, user, auth) ->
raise(Error(Inconsistent_import(name, user, auth)))
end;
begin try
let source = List.assoc cu.cu_name !implementations_defined in
Location.print_warning (Location.in_file file_name) ppf
(Warnings.Multiple_definition(cu.cu_name,
Location.show_filename file_name,
Location.show_filename source))
with Not_found -> ()
end;
implementations_defined :=
(cu.cu_name, file_name) :: !implementations_defined
let extract_crc_interfaces () =
Consistbl.extract !interfaces crc_interfaces
let clear_crc_interfaces () =
Consistbl.clear crc_interfaces;
interfaces := []
let debug_info = ref ([] : (int * Instruct.debug_event list * string list) list)
let link_compunit ppf output_fun currpos_fun inchan file_name compunit =
check_consistency ppf file_name compunit;
seek_in inchan compunit.cu_pos;
let code_block = LongString.input_bytes inchan compunit.cu_codesize in
Symtable.ls_patch_object code_block compunit.cu_reloc;
if !Clflags.debug && compunit.cu_debug > 0 then begin
seek_in inchan compunit.cu_debug;
let debug_event_list : Instruct.debug_event list = input_value inchan in
let debug_dirs : string list = input_value inchan in
let file_path = Filename.dirname (Location.absolute_path file_name) in
let debug_dirs =
if List.mem file_path debug_dirs
then debug_dirs
else file_path :: debug_dirs in
debug_info := (currpos_fun(), debug_event_list, debug_dirs) :: !debug_info
end;
Array.iter output_fun code_block;
if !Clflags.link_everything then
List.iter Symtable.require_primitive compunit.cu_primitives
let link_object ppf output_fun currpos_fun file_name compunit =
let inchan = open_in_bin file_name in
try
link_compunit ppf output_fun currpos_fun inchan file_name compunit;
close_in inchan
with
Symtable.Error msg ->
close_in inchan; raise(Error(Symbol_error(file_name, msg)))
| x ->
close_in inchan; raise x
let link_archive ppf output_fun currpos_fun file_name units_required =
let inchan = open_in_bin file_name in
try
List.iter
(fun cu ->
let name = file_name ^ "(" ^ cu.cu_name ^ ")" in
try
link_compunit ppf output_fun currpos_fun inchan name cu
with Symtable.Error msg ->
raise(Error(Symbol_error(name, msg))))
units_required;
close_in inchan
with x -> close_in inchan; raise x
let link_file ppf output_fun currpos_fun = function
Link_object(file_name, unit) ->
link_object ppf output_fun currpos_fun file_name unit
| Link_archive(file_name, units) ->
link_archive ppf output_fun currpos_fun file_name units
Format is :
< int32 > number of event lists
< int32 > offset of first event list
< output_value > first event list
...
< int32 > offset of last event list
< output_value > last event list
<int32> number of event lists
<int32> offset of first event list
<output_value> first event list
...
<int32> offset of last event list
<output_value> last event list *)
let output_debug_info oc =
output_binary_int oc (List.length !debug_info);
List.iter
(fun (ofs, evl, debug_dirs) ->
output_binary_int oc ofs;
output_value oc evl;
output_value oc debug_dirs)
!debug_info;
debug_info := []
let output_stringlist oc l =
List.iter (fun s -> output_string oc s; output_byte oc 0) l
Transform a file name into an absolute file name
let make_absolute file =
if Filename.is_relative file
then Filename.concat (Sys.getcwd()) file
else file
let link_bytecode ppf tolink exec_name standalone =
List.iter (function
| Link_object(file_name, _) when file_name = exec_name ->
raise (Error (Wrong_object_name exec_name));
| _ -> ()) tolink;
avoid permission problems , cf PR#1911
let outchan =
open_out_gen [Open_wronly; Open_trunc; Open_creat; Open_binary]
0o777 exec_name in
try
if standalone then begin
try
begin match Sys.os_type with
"Win32" | "Cygwin" ->
let header = if String.length !Clflags.use_runtime > 0 then "camlheader_ur" else "camlheader" ^ !Clflags.runtime_variant in
let inchan = open_in_bin (find_in_path !load_path header) in
copy_file inchan outchan;
close_in inchan
| _ ->
output_string outchan ("#!" ^ (make_absolute standard_runtime));
output_char outchan '\n';
end
with Not_found | Sys_error _ -> ()
end;
Bytesections.init_record outchan;
let ( // ) = Filename.concat in
if String.length !Clflags.use_runtime > 0 then begin
output_string outchan ((make_absolute !Clflags.use_runtime));
output_char outchan '\n';
Bytesections.record outchan "RNTM"
end else begin
output_string outchan (make_absolute ((Filename.dirname Sys.executable_name) // "bin" // "ocamlrun.exe"));
output_char outchan '\n';
Bytesections.record outchan "RNTM"
end;
let start_code = pos_out outchan in
Symtable.init();
clear_crc_interfaces ();
let sharedobjs = List.map Dll.extract_dll_name !Clflags.dllibs in
let check_dlls = standalone && Config.target = Config.host in
if check_dlls then begin
Initialize the DLL machinery
Dll.init_compile !Clflags.no_std_include;
Dll.add_path !load_path;
try Dll.open_dlls Dll.For_checking sharedobjs
with Failure reason -> raise(Error(Cannot_open_dll reason))
end;
let output_fun = output_bytes outchan
and currpos_fun () = pos_out outchan - start_code in
List.iter (link_file ppf output_fun currpos_fun) tolink;
if check_dlls then Dll.close_all_dlls();
output_byte outchan Opcodes.opSTOP;
output_byte outchan 0; output_byte outchan 0; output_byte outchan 0;
Bytesections.record outchan "CODE";
if standalone then begin
output_stringlist outchan (((Filename.dirname Sys.executable_name) // "lib" // "ocaml" // "stublibs") :: !Clflags.dllpaths);
Bytesections.record outchan "DLPT";
output_stringlist outchan sharedobjs;
Bytesections.record outchan "DLLS"
end;
Symtable.output_primitive_names outchan;
Bytesections.record outchan "PRIM";
begin try
Marshal.to_channel outchan (Symtable.initial_global_table())
(if !Clflags.bytecode_compatible_32
then [Marshal.Compat_32] else [])
with Failure _ ->
raise (Error Not_compatible_32)
end;
Bytesections.record outchan "DATA";
Symtable.output_global_map outchan;
Bytesections.record outchan "SYMB";
CRCs for modules
output_value outchan (extract_crc_interfaces());
Bytesections.record outchan "CRCS";
if !Clflags.debug then begin
output_debug_info outchan;
Bytesections.record outchan "DBUG"
end;
Bytesections.write_toc_and_trailer outchan;
close_out outchan
with x ->
close_out outchan;
remove_file exec_name;
raise x
let output_code_string_counter = ref 0
let output_code_string outchan code =
let pos = ref 0 in
let len = Bytes.length code in
while !pos < len do
let c1 = Char.code(Bytes.get code !pos) in
let c2 = Char.code(Bytes.get code (!pos + 1)) in
let c3 = Char.code(Bytes.get code (!pos + 2)) in
let c4 = Char.code(Bytes.get code (!pos + 3)) in
pos := !pos + 4;
Printf.fprintf outchan "0x%02x%02x%02x%02x, " c4 c3 c2 c1;
incr output_code_string_counter;
if !output_code_string_counter >= 6 then begin
output_char outchan '\n';
output_code_string_counter := 0
end
done
let output_data_string outchan data =
let counter = ref 0 in
for i = 0 to String.length data - 1 do
Printf.fprintf outchan "%d, " (Char.code(data.[i]));
incr counter;
if !counter >= 12 then begin
output_string outchan "\n";
counter := 0
end
done
let output_cds_file outfile =
Misc.remove_file outfile;
let outchan =
open_out_gen [Open_wronly; Open_trunc; Open_creat; Open_binary]
0o777 outfile in
try
Bytesections.init_record outchan;
Symtable.output_global_map outchan;
Bytesections.record outchan "SYMB";
output_debug_info outchan;
Bytesections.record outchan "DBUG";
Bytesections.write_toc_and_trailer outchan;
close_out outchan
with x ->
close_out outchan;
remove_file outfile;
raise x
let link_bytecode_as_c ppf tolink outfile =
let outchan = open_out outfile in
begin try
output_string outchan "\
#ifdef __cplusplus\
\nextern \"C\" {\
\n#endif\
\n#include <caml/mlvalues.h>\
\nCAMLextern void caml_startup_code(\
\n code_t code, asize_t code_size,\
\n char *data, asize_t data_size,\
\n char *section_table, asize_t section_table_size,\
\n char **argv);\n";
output_string outchan "static int caml_code[] = {\n";
Symtable.init();
clear_crc_interfaces ();
let currpos = ref 0 in
let output_fun code =
output_code_string outchan code;
currpos := !currpos + Bytes.length code
and currpos_fun () = !currpos in
List.iter (link_file ppf output_fun currpos_fun) tolink;
Printf.fprintf outchan "\n0x%x};\n\n" Opcodes.opSTOP;
output_string outchan "static char caml_data[] = {\n";
output_data_string outchan
(Marshal.to_string (Symtable.initial_global_table()) []);
output_string outchan "\n};\n\n";
let sections =
[ "SYMB", Symtable.data_global_map();
"PRIM", Obj.repr(Symtable.data_primitive_names());
"CRCS", Obj.repr(extract_crc_interfaces()) ] in
output_string outchan "static char caml_sections[] = {\n";
output_data_string outchan
(Marshal.to_string sections []);
output_string outchan "\n};\n\n";
Symtable.output_primitive_table outchan;
output_string outchan "\
\nvoid caml_startup(char ** argv)\
\n{\
\n caml_startup_code(caml_code, sizeof(caml_code),\
\n caml_data, sizeof(caml_data),\
\n caml_sections, sizeof(caml_sections),\
\n argv);\
\n}\
\n#ifdef __cplusplus\
\n}\
\n#endif\n";
close_out outchan
with x ->
close_out outchan;
remove_file outfile;
raise x
end;
if !Clflags.debug then
output_cds_file ((Filename.chop_extension outfile) ^ ".cds")
let build_custom_runtime prim_name exec_name =
let runtime_lib = "-lcamlrun" ^ !Clflags.runtime_variant in
Ccomp.call_linker Ccomp.Exe exec_name
([prim_name] @ List.rev !Clflags.ccobjs @ [runtime_lib])
(Clflags.std_include_flag "-I" ^ " " ^ Config.bytecomp_c_libraries)
let append_bytecode_and_cleanup bytecode_name exec_name prim_name =
let oc = open_out_gen [Open_wronly; Open_append; Open_binary] 0 exec_name in
let ic = open_in_bin bytecode_name in
copy_file ic oc;
close_in ic;
close_out oc;
remove_file bytecode_name;
remove_file prim_name
let fix_exec_name name =
match Sys.os_type with
"Win32" | "Cygwin" ->
if String.contains name '.' then name else name ^ ".exe"
| _ -> name
let link ppf objfiles output_name =
let objfiles =
if !Clflags.nopervasives then objfiles
else if !Clflags.output_c_object then "stdlib.cma" :: objfiles
else "stdlib.cma" :: (objfiles @ ["std_exit.cmo"]) in
let tolink = List.fold_right scan_file objfiles [] in
put user 's libs last
Clflags.all_ccopts := !lib_ccopts @ !Clflags.all_ccopts;
put user 's opts first
put user 's DLLs first
if not !Clflags.custom_runtime then
link_bytecode ppf tolink output_name true
else if not !Clflags.output_c_object then begin
let bytecode_name = Filename.temp_file "camlcode" "" in
let prim_name = Filename.temp_file "camlprim" ".c" in
try
link_bytecode ppf tolink bytecode_name false;
let poc = open_out prim_name in
output_string poc "\
#ifdef __cplusplus\n\
extern \"C\" {\n\
#endif\n\
#ifdef _WIN64\n\
#ifdef __MINGW32__\n\
typedef long long value;\n\
#else\n\
typedef __int64 value;\n\
#endif\n\
#else\n\
typedef long value;\n\
#endif\n";
Symtable.output_primitive_table poc;
output_string poc "\
#ifdef __cplusplus\n\
}\n\
#endif\n";
close_out poc;
let exec_name = fix_exec_name output_name in
if not (build_custom_runtime prim_name exec_name)
then raise(Error Custom_runtime);
if !Clflags.make_runtime
then (remove_file bytecode_name; remove_file prim_name)
else append_bytecode_and_cleanup bytecode_name exec_name prim_name
with x ->
remove_file bytecode_name;
remove_file prim_name;
raise x
end else begin
let basename = Filename.chop_extension output_name in
let c_file =
if !Clflags.output_complete_object
then Filename.temp_file "camlobj" ".c"
else basename ^ ".c"
and obj_file =
if !Clflags.output_complete_object
then Filename.temp_file "camlobj" Config.ext_obj
else basename ^ Config.ext_obj
in
if Sys.file_exists c_file then raise(Error(File_exists c_file));
let temps = ref [] in
try
link_bytecode_as_c ppf tolink c_file;
if not (Filename.check_suffix output_name ".c") then begin
temps := c_file :: !temps;
if Ccomp.compile_file c_file <> 0 then raise(Error Custom_runtime);
if not (Filename.check_suffix output_name Config.ext_obj) ||
!Clflags.output_complete_object then begin
temps := obj_file :: !temps;
let mode, c_libs =
if Filename.check_suffix output_name Config.ext_obj
then Ccomp.Partial, ""
else Ccomp.MainDll, Config.bytecomp_c_libraries
in
if not (
let runtime_lib = "-lcamlrun" ^ !Clflags.runtime_variant in
Ccomp.call_linker mode output_name
([obj_file] @ List.rev !Clflags.ccobjs @ [runtime_lib])
c_libs
) then raise (Error Custom_runtime);
end
end;
List.iter remove_file !temps
with x ->
List.iter remove_file !temps;
raise x
end
open Format
let report_error ppf = function
| File_not_found name ->
fprintf ppf "Cannot find file %a" Location.print_filename name
| Not_an_object_file name ->
fprintf ppf "The file %a is not a bytecode object file"
Location.print_filename name
| Wrong_object_name name ->
fprintf ppf "The output file %s has the wrong name. The extension implies\
\ an object file but the link step was requested" name
| Symbol_error(name, err) ->
fprintf ppf "Error while linking %a:@ %a" Location.print_filename name
Symtable.report_error err
| Inconsistent_import(intf, file1, file2) ->
fprintf ppf
"@[<hov>Files %a@ and %a@ \
make inconsistent assumptions over interface %s@]"
Location.print_filename file1
Location.print_filename file2
intf
| Custom_runtime ->
fprintf ppf "Error while building custom runtime system"
| File_exists file ->
fprintf ppf "Cannot overwrite existing file %a"
Location.print_filename file
| Cannot_open_dll file ->
fprintf ppf "Error on dynamically loaded library: %a"
Location.print_filename file
| Not_compatible_32 ->
fprintf ppf "Generated bytecode executable cannot be run\
\ on a 32-bit platform"
let () =
Location.register_error_of_exn
(function
| Error err -> Some (Location.error_of_printer_file report_error err)
| _ -> None
)
let reset () =
lib_ccobjs := [];
lib_ccopts := [];
lib_dllibs := [];
missing_globals := IdentSet.empty;
Consistbl.clear crc_interfaces;
implementations_defined := [];
debug_info := [];
output_code_string_counter := 0
|
cefd25ff8f1315eb52f1ad8406c0a59babcc44c9fd80f63f342f60b500b415ce
|
Engil/Goodboy
|
cpu.ml
|
open Registers
type t = {
sp : int;
pc : int;
rg : Registers.t;
ime : bool;
t : int;
m : int;
halted : bool;
}
let make () = {
sp = 0;
pc = 0;
rg = Registers.make ();
ime = false;
t = 0;
m = 0;
halted = false;
}
let get_register { rg; _ } r = get rg r
let set_register { rg; _ } r = set rg r
let get_register_pair { rg; _ } r = get_pair rg r
let set_register_pair { rg; _ } r = set_pair rg r
let tick cpu n =
let t = cpu.t + n in
let m = cpu.m + (n / 4) in
{ cpu with t; m; }
| null |
https://raw.githubusercontent.com/Engil/Goodboy/2e9abc243b929d8bdfb7c5d4874ddb8a07c55fac/lib/cpu.ml
|
ocaml
|
open Registers
type t = {
sp : int;
pc : int;
rg : Registers.t;
ime : bool;
t : int;
m : int;
halted : bool;
}
let make () = {
sp = 0;
pc = 0;
rg = Registers.make ();
ime = false;
t = 0;
m = 0;
halted = false;
}
let get_register { rg; _ } r = get rg r
let set_register { rg; _ } r = set rg r
let get_register_pair { rg; _ } r = get_pair rg r
let set_register_pair { rg; _ } r = set_pair rg r
let tick cpu n =
let t = cpu.t + n in
let m = cpu.m + (n / 4) in
{ cpu with t; m; }
|
|
cb0e5e5c9e2ee2be1ec5684a6dd537f3b0fd0faea23f0ce06218e131f93d5ba2
|
ijvcms/chuanqi_dev
|
guild_config.erl
|
%%%-------------------------------------------------------------------
@author zhengsiying
%%% @doc
%%% 自动生成文件,不要手动修改
%%% @end
Created : 2016/10/12
%%%-------------------------------------------------------------------
-module(guild_config).
-include("common.hrl").
-include("config.hrl").
-compile([export_all]).
get_list_conf() ->
[ guild_config:get(X) || X <- get_list() ].
get_list() ->
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
get(1) ->
#guild_conf{
key = 1,
exp = 9000,
member_limit = 40
};
get(2) ->
#guild_conf{
key = 2,
exp = 20000,
member_limit = 45
};
get(3) ->
#guild_conf{
key = 3,
exp = 60000,
member_limit = 50
};
get(4) ->
#guild_conf{
key = 4,
exp = 130000,
member_limit = 55
};
get(5) ->
#guild_conf{
key = 5,
exp = 260000,
member_limit = 60
};
get(6) ->
#guild_conf{
key = 6,
exp = 520000,
member_limit = 65
};
get(7) ->
#guild_conf{
key = 7,
exp = 1040000,
member_limit = 70
};
get(8) ->
#guild_conf{
key = 8,
exp = 2080000,
member_limit = 75
};
get(9) ->
#guild_conf{
key = 9,
exp = 4160000,
member_limit = 80
};
get(10) ->
#guild_conf{
key = 10,
exp = 9999999999,
member_limit = 85
};
get(_Key) ->
?ERR("undefined key from guild_config ~p", [_Key]).
| null |
https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/config/guild_config.erl
|
erlang
|
-------------------------------------------------------------------
@doc
自动生成文件,不要手动修改
@end
-------------------------------------------------------------------
|
@author zhengsiying
Created : 2016/10/12
-module(guild_config).
-include("common.hrl").
-include("config.hrl").
-compile([export_all]).
get_list_conf() ->
[ guild_config:get(X) || X <- get_list() ].
get_list() ->
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
get(1) ->
#guild_conf{
key = 1,
exp = 9000,
member_limit = 40
};
get(2) ->
#guild_conf{
key = 2,
exp = 20000,
member_limit = 45
};
get(3) ->
#guild_conf{
key = 3,
exp = 60000,
member_limit = 50
};
get(4) ->
#guild_conf{
key = 4,
exp = 130000,
member_limit = 55
};
get(5) ->
#guild_conf{
key = 5,
exp = 260000,
member_limit = 60
};
get(6) ->
#guild_conf{
key = 6,
exp = 520000,
member_limit = 65
};
get(7) ->
#guild_conf{
key = 7,
exp = 1040000,
member_limit = 70
};
get(8) ->
#guild_conf{
key = 8,
exp = 2080000,
member_limit = 75
};
get(9) ->
#guild_conf{
key = 9,
exp = 4160000,
member_limit = 80
};
get(10) ->
#guild_conf{
key = 10,
exp = 9999999999,
member_limit = 85
};
get(_Key) ->
?ERR("undefined key from guild_config ~p", [_Key]).
|
bb25d2983c2bb2202388894e2833b828901e008664635c42672d149f317c8c84
|
johnlawrenceaspden/hobby-code
|
quadraticregression.clj
|
What is the best fit for a+bx+cxx here ?
(defn fit [[ a b c]]
(let [predictions (map #(+ a (* b %) (* c % %)) (range 1 8))]
[(reduce + (map #(* % %)
(map - predictions
[2 6 14 26 40 60 96])))
[a b c]
predictions]))
(defn improve-guess [a b c delta]
(let [candidates (list [a b c]
[(+ a delta) b c]
[(- a delta) b c]
[a (+ b delta) c]
[a (- b delta) c]
[a b (+ c delta)]
[a b (- c delta)])
scores (sort (map fit candidates))
]
(first scores)))
- > [ 639 [ 1 5 1 ] ( 7 15 25 37 51 67 85 ) ]
- > [ 407 [ -3 5 1 ] ( 3 11 21 33 47 63 81 ) ]
- > [ 399 [ -7 5 1 ] ( -1 7 17 29 43 59 77 ) ]
- > [ 399 [ -7 5 1 ] ( -1 7 17 29 43 59 77 ) ]
- > [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ]
- > [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ]
- > [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ]
- > [ 362.0 [ -5 5.5 1 ] ( 1.5 10.0 20.5 33.0 47.5 64.0 82.5 ) ]
(defn refine [a b c delta]
(let [[score [na nb nc ] predictions ] (improve-guess a b c delta)]
(if (= [na nb nc] [a b c])
[[score [na nb nc ] predictions ]]
(refine na nb nc delta))))
;; [2 6 14 26 40 60 96]
- > [ [ 203.7099999999998 [ -7.89999999999999 4.200000000000003 1.3000000000000003 ] ( -2.3999999999999866 5.700000000000017 16.40000000000002 29.700000000000024 45.60000000000003 64.10000000000004 85.20000000000005 ) ] ]
- > [ [ 125.31000000000004 [ -3.1000000000000014 1.0 1.7000000000000006 ] ( -0.4000000000000008 5.700000000000001 15.200000000000003 28.10000000000001 44.40000000000001 64.10000000000002 87.20000000000002 ) ] ]
- > [ [ 50.068 [ 4.42 -4.49 2.42 ] ( 2.3499999999999996 5.119999999999999 12.73 25.18 42.47 64.6 91.57 ) ] ]
(refine 4.42 -4.49 2.42 0.005)
- > [ [ 399 [ -7 5 1 ] ( -1 7 17 29 43 59 77 ) ] [ 399 [ -7 5 1 ] ( -1 7 17 29 43 59 77 ) ] ]
- > [ [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ] [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ] ]
- > [ [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ] [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ] ]
- > [ [ 330.0 [ -7.0 5.5 1 ] ( -0.5 8.0 18.5 31.0 45.5 62.0 80.5 ) ] [ 330.0 [ -7.0 5.5 1 ] ( -0.5 8.0 18.5 31.0 45.5 62.0 80.5 ) ] ]
- > [ [ 227.50999999999982 [ -9.099999999999993 5.000000000000002 1.2000000000000002 ] ( -2.8999999999999906 5.700000000000012 16.700000000000014 30.100000000000016 45.90000000000002 64.10000000000002 84.70000000000003 ) ] [ 227.50999999999982 [ -9.099999999999993 5.000000000000002 1.2000000000000002 ] ( -2.8999999999999906 5.700000000000012 16.700000000000014 30.100000000000016 45.90000000000002 64.10000000000002 84.70000000000003 ) ] ]
(refine 1 1 1 4)
| null |
https://raw.githubusercontent.com/johnlawrenceaspden/hobby-code/48e2a89d28557994c72299962cd8e3ace6a75b2d/quadraticregression.clj
|
clojure
|
[2 6 14 26 40 60 96]
|
What is the best fit for a+bx+cxx here ?
(defn fit [[ a b c]]
(let [predictions (map #(+ a (* b %) (* c % %)) (range 1 8))]
[(reduce + (map #(* % %)
(map - predictions
[2 6 14 26 40 60 96])))
[a b c]
predictions]))
(defn improve-guess [a b c delta]
(let [candidates (list [a b c]
[(+ a delta) b c]
[(- a delta) b c]
[a (+ b delta) c]
[a (- b delta) c]
[a b (+ c delta)]
[a b (- c delta)])
scores (sort (map fit candidates))
]
(first scores)))
- > [ 639 [ 1 5 1 ] ( 7 15 25 37 51 67 85 ) ]
- > [ 407 [ -3 5 1 ] ( 3 11 21 33 47 63 81 ) ]
- > [ 399 [ -7 5 1 ] ( -1 7 17 29 43 59 77 ) ]
- > [ 399 [ -7 5 1 ] ( -1 7 17 29 43 59 77 ) ]
- > [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ]
- > [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ]
- > [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ]
- > [ 362.0 [ -5 5.5 1 ] ( 1.5 10.0 20.5 33.0 47.5 64.0 82.5 ) ]
(defn refine [a b c delta]
(let [[score [na nb nc ] predictions ] (improve-guess a b c delta)]
(if (= [na nb nc] [a b c])
[[score [na nb nc ] predictions ]]
(refine na nb nc delta))))
- > [ [ 203.7099999999998 [ -7.89999999999999 4.200000000000003 1.3000000000000003 ] ( -2.3999999999999866 5.700000000000017 16.40000000000002 29.700000000000024 45.60000000000003 64.10000000000004 85.20000000000005 ) ] ]
- > [ [ 125.31000000000004 [ -3.1000000000000014 1.0 1.7000000000000006 ] ( -0.4000000000000008 5.700000000000001 15.200000000000003 28.10000000000001 44.40000000000001 64.10000000000002 87.20000000000002 ) ] ]
- > [ [ 50.068 [ 4.42 -4.49 2.42 ] ( 2.3499999999999996 5.119999999999999 12.73 25.18 42.47 64.6 91.57 ) ] ]
(refine 4.42 -4.49 2.42 0.005)
- > [ [ 399 [ -7 5 1 ] ( -1 7 17 29 43 59 77 ) ] [ 399 [ -7 5 1 ] ( -1 7 17 29 43 59 77 ) ] ]
- > [ [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ] [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ] ]
- > [ [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ] [ 375 [ -5 5 1 ] ( 1 9 19 31 45 61 79 ) ] ]
- > [ [ 330.0 [ -7.0 5.5 1 ] ( -0.5 8.0 18.5 31.0 45.5 62.0 80.5 ) ] [ 330.0 [ -7.0 5.5 1 ] ( -0.5 8.0 18.5 31.0 45.5 62.0 80.5 ) ] ]
- > [ [ 227.50999999999982 [ -9.099999999999993 5.000000000000002 1.2000000000000002 ] ( -2.8999999999999906 5.700000000000012 16.700000000000014 30.100000000000016 45.90000000000002 64.10000000000002 84.70000000000003 ) ] [ 227.50999999999982 [ -9.099999999999993 5.000000000000002 1.2000000000000002 ] ( -2.8999999999999906 5.700000000000012 16.700000000000014 30.100000000000016 45.90000000000002 64.10000000000002 84.70000000000003 ) ] ]
(refine 1 1 1 4)
|
470adadadd9807634082af6bca9162f4eb6a3b28296096fc2b5f049c87112e29
|
richmit/mjrcalc
|
use-colorized.lisp
|
;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;; @file use-colorized.lisp
@author < >
@brief of discrete spaces ( Z_n).@EOL
;; @std Common Lisp
@parblock
Copyright ( c ) 1996,1997,2008,2010,2015 , < > All rights reserved .
;;
;; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
;;
1 . Redistributions of source code must retain the above copyright notice , this list of conditions , and the following disclaimer .
;;
2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions , and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
3 . Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
;; DAMAGE.
;; @endparblock
;; @todo Add some color brewer-like schemes (by index and pallet).@EOL@EOL
;; @todo Add some schemes for color blind people (by index and pallet).@EOL@EOL
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defpackage :MJR_COLORIZED
(:USE :COMMON-LISP
:MJR_COLOR)
(:DOCUMENTATION "Brief: Colorization of discrete spaces (Z_n).;")
(:EXPORT #:mjr_colorized_help
;; Utilities: Gradients & Pallets
#:mjr_colorized_ut-tru-from-gradient
#:mjr_colorized_ut-tru-from-pallet #:mjr_colorized_ut-pallet-length
#:mjr_colorized_ut-pallet-from-gradient #:mjr_colorized_ut-gradient-length
Colorize via 16 - bit povray
#:mjr_colorized_povray
Colorize Function Factories : Gradients & Pallets
#:mjr_colorized_factory-from-gradient
#:mjr_colorized_factory-from-pallet
))
(in-package :MJR_COLORIZED)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_colorized_help ()
"Colorize desecrate spaces of dimensions one (i.e. $Z_n=\{0,1,...,n-1\}$ -- used for visualization.
All colors are returned as :cs-tru (i.e. RGB components are integers in [0,255]).
For real RGB components in [0,1], see :MJR_COLORIZER.
For color theory computations (space conversions, mixing, etc...), see :MJR_COLOR
Such color schemes are frequently based on gradients, and several common gradients included (see ramCanvas for more info):
Several common gradients include:
* 0GR ....... Povray
* RYGCBMR ... cmpClrCubeRainbow
* CR ........ cmpDiagRampCR
* MG ........ cmpDiagRampMG
* YB ........ cmpDiagRampYB
* CMYC ...... cmpConstTwoRamp
* BRGB ...... cmpConstOneRamp
* 0W ........ cmpGreyRGB
* YC ........ cmpUpDownRampBr
* YM ........ cmpUpDownRampBg
* MC ........ cmpUpDownRampGr
* MY ........ cmpUpDownRampGb
* CM ........ cmpUpDownRampRg
* CY ........ cmpUpDownRampRb
* 0RYW ...... cmpSumRampRGB
* 0BCW ...... cmpSumRampBGR
* 0GYW ...... cmpSumRampGRB
* 0GCW ...... cmpSumRampGBR
* 0BMW ...... cmpSumRampBRG
* 0RMW ...... cmpSumRampRBG
* BCGYR ..... cmpColdToHot
* WCBYR ..... cmpIceToWaterToHot"
(documentation 'mjr_colorized_help 'function))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_colorized_ut-gradient-length (gradient)
""
(let* ((len (length gradient))
(sln (if (= len 1)
1
(- (* 256 (- len 1)) (- len 2)))))
(values sln len)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_colorized_ut-tru-from-gradient (x &optional (gradient "RYGCBMR"))
""
(let ((x (truncate x)))
(multiple-value-bind (sln len) (mjr_colorized_ut-gradient-length gradient)
(cond ((>= (+ x 1) sln) (mjr_color_make-tru-from-spec (aref gradient (1- len))))
((<= x 0) (mjr_color_make-tru-from-spec (aref gradient 0)))
('t (let* ((wid (/ (1- sln) (- len 1)))
(buk (floor (/ x wid)))
(xn (* wid buk))
(cn (mjr_color_make-tru-from-spec (aref gradient buk)))
(cn+1 (mjr_color_make-tru-from-spec (aref gradient (1+ buk))))
(d (/ (- x xn) wid)))
(map 'vector (lambda (c1 c2) (truncate (+ (* c1 (- 1 d)) (* c2 d)))) cn cn+1)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_colorized_ut-pallet-from-gradient (gradient)
""
(let ((len (mjr_colorized_ut-gradient-length gradient)))
(make-array len :initial-contents (loop for i from 0 upto (1- len)
collect (mjr_colorized_ut-tru-from-gradient i gradient)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_colorized_ut-pallet-length (pallet)
""
(length pallet))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_colorized_ut-tru-from-pallet (i pallet &optional (i-over :clip) (i-under :clip))
"Return the I'th color from PALLET using the I-OVER/I-UNDER behavior for out of range values of I.
Possible behaviors when index is out of range:
* :recycle
* :clip
* :error"
(let ((i (truncate i))
(len (mjr_colorized_ut-pallet-length pallet)))
(cond ((< i 0) (case i-under
(:recycle (aref pallet (mod i len)))
(:clip (aref pallet 0))
(:error (error "mjr_colorized_ut-tru-from-pallet: i too small!"))))
((> i (1- len)) (case i-over
(:recycle (aref pallet (mod i len)))
(:clip (aref pallet (1- len)))
(:error (error "mjr_colorized_ut-tru-from-pallet: i too big!"))))
('t (aref pallet i)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_colorized_povray (value)
"Convert an number in $[0,2^{16}-1]$ into a :cs-tru color representing a povray height."
(if (integerp value)
(vector (ldb (byte 8 8) value) (ldb (byte 8 0) value) 0)
(mjr_colorized_povray (truncate value))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_colorized_factory-from-pallet (pallet)
"Return a function that takes an integer, and returns a color"
(lambda (i) (mjr_colorized_ut-tru-from-pallet i pallet)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_colorized_factory-from-gradient (gradient)
"Return a function that takes an integer, and returns a color.
NOTE: The resulting function will be much faster than repeatedly calling mjr_colorized_ut-tru-from-pallet."
(mjr_colorized_factory-from-pallet (mjr_colorized_ut-pallet-from-gradient gradient)))
| null |
https://raw.githubusercontent.com/richmit/mjrcalc/96f66d030034754e7d3421688ff201f4f1db4833/use-colorized.lisp
|
lisp
|
-*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*-
@file use-colorized.lisp
@std Common Lisp
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
and/or other materials provided with the distribution.
without specific prior written permission.
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.
@endparblock
@todo Add some color brewer-like schemes (by index and pallet).@EOL@EOL
@todo Add some schemes for color blind people (by index and pallet).@EOL@EOL
Utilities: Gradients & Pallets
|
@author < >
@brief of discrete spaces ( Z_n).@EOL
@parblock
Copyright ( c ) 1996,1997,2008,2010,2015 , < > All rights reserved .
1 . Redistributions of source code must retain the above copyright notice , this list of conditions , and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions , and the following disclaimer in the documentation
3 . Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
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
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS
(defpackage :MJR_COLORIZED
(:USE :COMMON-LISP
:MJR_COLOR)
(:DOCUMENTATION "Brief: Colorization of discrete spaces (Z_n).;")
(:EXPORT #:mjr_colorized_help
#:mjr_colorized_ut-tru-from-gradient
#:mjr_colorized_ut-tru-from-pallet #:mjr_colorized_ut-pallet-length
#:mjr_colorized_ut-pallet-from-gradient #:mjr_colorized_ut-gradient-length
Colorize via 16 - bit povray
#:mjr_colorized_povray
Colorize Function Factories : Gradients & Pallets
#:mjr_colorized_factory-from-gradient
#:mjr_colorized_factory-from-pallet
))
(in-package :MJR_COLORIZED)
(defun mjr_colorized_help ()
"Colorize desecrate spaces of dimensions one (i.e. $Z_n=\{0,1,...,n-1\}$ -- used for visualization.
All colors are returned as :cs-tru (i.e. RGB components are integers in [0,255]).
For real RGB components in [0,1], see :MJR_COLORIZER.
For color theory computations (space conversions, mixing, etc...), see :MJR_COLOR
Such color schemes are frequently based on gradients, and several common gradients included (see ramCanvas for more info):
Several common gradients include:
* 0GR ....... Povray
* RYGCBMR ... cmpClrCubeRainbow
* CR ........ cmpDiagRampCR
* MG ........ cmpDiagRampMG
* YB ........ cmpDiagRampYB
* CMYC ...... cmpConstTwoRamp
* BRGB ...... cmpConstOneRamp
* 0W ........ cmpGreyRGB
* YC ........ cmpUpDownRampBr
* YM ........ cmpUpDownRampBg
* MC ........ cmpUpDownRampGr
* MY ........ cmpUpDownRampGb
* CM ........ cmpUpDownRampRg
* CY ........ cmpUpDownRampRb
* 0RYW ...... cmpSumRampRGB
* 0BCW ...... cmpSumRampBGR
* 0GYW ...... cmpSumRampGRB
* 0GCW ...... cmpSumRampGBR
* 0BMW ...... cmpSumRampBRG
* 0RMW ...... cmpSumRampRBG
* BCGYR ..... cmpColdToHot
* WCBYR ..... cmpIceToWaterToHot"
(documentation 'mjr_colorized_help 'function))
(defun mjr_colorized_ut-gradient-length (gradient)
""
(let* ((len (length gradient))
(sln (if (= len 1)
1
(- (* 256 (- len 1)) (- len 2)))))
(values sln len)))
(defun mjr_colorized_ut-tru-from-gradient (x &optional (gradient "RYGCBMR"))
""
(let ((x (truncate x)))
(multiple-value-bind (sln len) (mjr_colorized_ut-gradient-length gradient)
(cond ((>= (+ x 1) sln) (mjr_color_make-tru-from-spec (aref gradient (1- len))))
((<= x 0) (mjr_color_make-tru-from-spec (aref gradient 0)))
('t (let* ((wid (/ (1- sln) (- len 1)))
(buk (floor (/ x wid)))
(xn (* wid buk))
(cn (mjr_color_make-tru-from-spec (aref gradient buk)))
(cn+1 (mjr_color_make-tru-from-spec (aref gradient (1+ buk))))
(d (/ (- x xn) wid)))
(map 'vector (lambda (c1 c2) (truncate (+ (* c1 (- 1 d)) (* c2 d)))) cn cn+1)))))))
(defun mjr_colorized_ut-pallet-from-gradient (gradient)
""
(let ((len (mjr_colorized_ut-gradient-length gradient)))
(make-array len :initial-contents (loop for i from 0 upto (1- len)
collect (mjr_colorized_ut-tru-from-gradient i gradient)))))
(defun mjr_colorized_ut-pallet-length (pallet)
""
(length pallet))
(defun mjr_colorized_ut-tru-from-pallet (i pallet &optional (i-over :clip) (i-under :clip))
"Return the I'th color from PALLET using the I-OVER/I-UNDER behavior for out of range values of I.
Possible behaviors when index is out of range:
* :recycle
* :clip
* :error"
(let ((i (truncate i))
(len (mjr_colorized_ut-pallet-length pallet)))
(cond ((< i 0) (case i-under
(:recycle (aref pallet (mod i len)))
(:clip (aref pallet 0))
(:error (error "mjr_colorized_ut-tru-from-pallet: i too small!"))))
((> i (1- len)) (case i-over
(:recycle (aref pallet (mod i len)))
(:clip (aref pallet (1- len)))
(:error (error "mjr_colorized_ut-tru-from-pallet: i too big!"))))
('t (aref pallet i)))))
(defun mjr_colorized_povray (value)
"Convert an number in $[0,2^{16}-1]$ into a :cs-tru color representing a povray height."
(if (integerp value)
(vector (ldb (byte 8 8) value) (ldb (byte 8 0) value) 0)
(mjr_colorized_povray (truncate value))))
(defun mjr_colorized_factory-from-pallet (pallet)
"Return a function that takes an integer, and returns a color"
(lambda (i) (mjr_colorized_ut-tru-from-pallet i pallet)))
(defun mjr_colorized_factory-from-gradient (gradient)
"Return a function that takes an integer, and returns a color.
NOTE: The resulting function will be much faster than repeatedly calling mjr_colorized_ut-tru-from-pallet."
(mjr_colorized_factory-from-pallet (mjr_colorized_ut-pallet-from-gradient gradient)))
|
a2808a56c6b98c6ce0d156aa8852a77998fb01f7fe93882cd64df91ea1d03244
|
hercules-ci/hercules-ci-agent
|
Project.hs
|
# LANGUAGE TypeFamilies #
module Hercules.CLI.Project where
import qualified Data.Attoparsec.Text as A
import Data.Has (Has)
import qualified Data.UUID
import Hercules.API (ClientAuth, Id, enterApiE)
import Hercules.API.Id (Id (Id))
import Hercules.API.Name (Name (Name))
import Hercules.API.Projects (ProjectResourceGroup, ProjectsAPI (byProjectName), findProjects)
import qualified Hercules.API.Projects as Projects
import Hercules.API.Projects.Project (Project)
import qualified Hercules.API.Projects.Project as Project
import qualified Hercules.API.Repos as Repos
import qualified Hercules.API.Repos.RepoKey as RepoKey
import Hercules.CLI.Client (HerculesClientEnv, HerculesClientToken, projectsClient, reposClient, runHerculesClient, runHerculesClientEither)
import Hercules.CLI.Common (exitMsg)
import qualified Hercules.CLI.Git as Git
import Hercules.CLI.Options (attoparsecReader, packSome)
import Hercules.Error (escalate, escalateAs)
import Network.HTTP.Types (Status (Status, statusCode))
import Options.Applicative (bashCompleter, completer, help, long, metavar, option, strOption)
import qualified Options.Applicative as Optparse
import Protolude
import RIO (RIO)
import Servant.Client.Core (ClientError (FailureResponse), ResponseF (responseStatusCode))
import Servant.Client.Core.Response (ResponseF (Response))
import Servant.Client.Generic (AsClientT)
import Servant.Client.Streaming (ClientM)
import UnliftIO.Environment (lookupEnv)
import qualified Prelude
data ProjectPath = ProjectPath
{ projectPathSite :: Text,
projectPathOwner :: Text,
projectPathProject :: Text
}
instance Prelude.Show ProjectPath where
show = toS . projectPathText
projectPathText :: ProjectPath -> Text
projectPathText = projectPathSite <> const "/" <> projectPathOwner <> const "/" <> projectPathProject
projectOption :: Optparse.Parser ProjectPath
projectOption =
option projectPathReadM $
long "project" <> metavar "PROJECT" <> help "Project path, e.g. github/my-org/my-project"
nameOption :: Optparse.Parser Text
nameOption = strOption $ long "name" <> metavar "NAME" <> help "Name of the state file"
fileOption :: Optparse.Parser FilePath
fileOption = strOption $ long "file" <> metavar "FILE" <> help "Local path of the state file or - for stdio" <> completer (bashCompleter "file")
projectPathReadM :: Optparse.ReadM ProjectPath
projectPathReadM = attoparsecReader parseProjectPath
parseProjectPath :: A.Parser ProjectPath
parseProjectPath =
pure ProjectPath
<*> packSome (A.satisfy (/= '/'))
<* A.char '/'
<*> packSome (A.satisfy (/= '/'))
<* A.char '/'
<*> packSome (A.satisfy (/= '/'))
parseProjectPathFromText :: Text -> Either [Char] ProjectPath
parseProjectPathFromText = A.parseOnly parseProjectPath
getProjectPath :: (Has HerculesClientToken r, Has HerculesClientEnv r) => Maybe ProjectPath -> RIO r ProjectPath
getProjectPath maybeProjectPathParam =
case maybeProjectPathParam of
Nothing -> snd <$> findProjectContextually
Just projectKey -> pure projectKey
getProjectIdAndPath :: (Has HerculesClientToken r, Has HerculesClientEnv r) => Maybe ProjectPath -> RIO r (Maybe (Id Project), ProjectPath)
getProjectIdAndPath maybeProjectPathParam = do
case maybeProjectPathParam of
Nothing -> findProjectContextually
Just projectKey -> do
project <- findProjectByKey projectKey
pure (Project.id <$> project, projectKey)
findProjectByKey :: (Has HerculesClientToken r, Has HerculesClientEnv r) => ProjectPath -> RIO r (Maybe Project.Project)
findProjectByKey path =
runHerculesClient
( Projects.findProjects
projectsClient
(Just $ Name $ projectPathSite path)
(Just $ Name $ projectPathOwner path)
(Just $ Name $ projectPathProject path)
)
<&> head
findProjectContextually :: (Has HerculesClientToken r, Has HerculesClientEnv r) => RIO r (Maybe (Id Project), ProjectPath)
findProjectContextually = do
projectIdMaybe <- lookupEnv "HERCULES_CI_PROJECT_ID"
projectIdPathMaybe <- lookupEnv "HERCULES_CI_PROJECT_PATH"
case (,) <$> projectIdMaybe <*> projectIdPathMaybe of
Nothing -> findProjectByCurrentRepo
Just (id, pathText) -> do
projectPath <- parseProjectPathFromText (toS pathText) & escalateAs (\e -> FatalError $ "Invalid HERCULES_CI_PROJECT_PATH supplied: " <> toS e)
uuid <- Data.UUID.fromString id & maybeToEither (FatalError "Invalid UUID in HERCULES_CI_PROJECT_ID") & escalate
pure (Just (Id uuid), projectPath)
findProjectByCurrentRepo :: (Has HerculesClientToken r, Has HerculesClientEnv r) => RIO r (Maybe (Id Project), ProjectPath)
findProjectByCurrentRepo = do
url <- liftIO Git.getUpstreamURL
rs <- runHerculesClientEither (Repos.parseGitURL reposClient url)
case rs of
Left (FailureResponse _req Response {responseStatusCode = Status {statusCode = 404}}) -> do
exitMsg "Repository not recognized by Hercules CI. Make sure you're in the right repository, and if you're running Hercules CI Enterprise, make sure you're using the right HERCULES_CI_API_BASE_URL. Alternatively, use the --project option."
Left e -> throwIO e
Right r ->
pure
( RepoKey.projectId r,
ProjectPath
{ projectPathSite = RepoKey.siteName r,
projectPathOwner = RepoKey.ownerName r,
projectPathProject = RepoKey.repoName r
}
)
findProject :: (Has HerculesClientToken r, Has HerculesClientEnv r) => ProjectPath -> RIO r Project.Project
findProject project = do
rs <-
runHerculesClient
( findProjects
projectsClient
(Just $ Name $ projectPathSite project)
(Just $ Name $ projectPathOwner project)
(Just $ Name $ projectPathProject project)
)
case rs of
[] -> do
exitMsg $ "Project not found: " <> show project
[p] -> pure p
_ -> do
exitMsg $ "Project ambiguous: " <> show project
projectResourceClientByPath :: ProjectPath -> ProjectResourceGroup ClientAuth (AsClientT ClientM)
projectResourceClientByPath projectPath =
projectsClient `enterApiE` \api ->
byProjectName
api
(Name $ projectPathSite projectPath)
(Name $ projectPathOwner projectPath)
(Name $ projectPathProject projectPath)
| null |
https://raw.githubusercontent.com/hercules-ci/hercules-ci-agent/43ca2239f768905be0cc5d8627699f15e1a60519/hercules-ci-cli/src/Hercules/CLI/Project.hs
|
haskell
|
# LANGUAGE TypeFamilies #
module Hercules.CLI.Project where
import qualified Data.Attoparsec.Text as A
import Data.Has (Has)
import qualified Data.UUID
import Hercules.API (ClientAuth, Id, enterApiE)
import Hercules.API.Id (Id (Id))
import Hercules.API.Name (Name (Name))
import Hercules.API.Projects (ProjectResourceGroup, ProjectsAPI (byProjectName), findProjects)
import qualified Hercules.API.Projects as Projects
import Hercules.API.Projects.Project (Project)
import qualified Hercules.API.Projects.Project as Project
import qualified Hercules.API.Repos as Repos
import qualified Hercules.API.Repos.RepoKey as RepoKey
import Hercules.CLI.Client (HerculesClientEnv, HerculesClientToken, projectsClient, reposClient, runHerculesClient, runHerculesClientEither)
import Hercules.CLI.Common (exitMsg)
import qualified Hercules.CLI.Git as Git
import Hercules.CLI.Options (attoparsecReader, packSome)
import Hercules.Error (escalate, escalateAs)
import Network.HTTP.Types (Status (Status, statusCode))
import Options.Applicative (bashCompleter, completer, help, long, metavar, option, strOption)
import qualified Options.Applicative as Optparse
import Protolude
import RIO (RIO)
import Servant.Client.Core (ClientError (FailureResponse), ResponseF (responseStatusCode))
import Servant.Client.Core.Response (ResponseF (Response))
import Servant.Client.Generic (AsClientT)
import Servant.Client.Streaming (ClientM)
import UnliftIO.Environment (lookupEnv)
import qualified Prelude
data ProjectPath = ProjectPath
{ projectPathSite :: Text,
projectPathOwner :: Text,
projectPathProject :: Text
}
instance Prelude.Show ProjectPath where
show = toS . projectPathText
projectPathText :: ProjectPath -> Text
projectPathText = projectPathSite <> const "/" <> projectPathOwner <> const "/" <> projectPathProject
projectOption :: Optparse.Parser ProjectPath
projectOption =
option projectPathReadM $
long "project" <> metavar "PROJECT" <> help "Project path, e.g. github/my-org/my-project"
nameOption :: Optparse.Parser Text
nameOption = strOption $ long "name" <> metavar "NAME" <> help "Name of the state file"
fileOption :: Optparse.Parser FilePath
fileOption = strOption $ long "file" <> metavar "FILE" <> help "Local path of the state file or - for stdio" <> completer (bashCompleter "file")
projectPathReadM :: Optparse.ReadM ProjectPath
projectPathReadM = attoparsecReader parseProjectPath
parseProjectPath :: A.Parser ProjectPath
parseProjectPath =
pure ProjectPath
<*> packSome (A.satisfy (/= '/'))
<* A.char '/'
<*> packSome (A.satisfy (/= '/'))
<* A.char '/'
<*> packSome (A.satisfy (/= '/'))
parseProjectPathFromText :: Text -> Either [Char] ProjectPath
parseProjectPathFromText = A.parseOnly parseProjectPath
getProjectPath :: (Has HerculesClientToken r, Has HerculesClientEnv r) => Maybe ProjectPath -> RIO r ProjectPath
getProjectPath maybeProjectPathParam =
case maybeProjectPathParam of
Nothing -> snd <$> findProjectContextually
Just projectKey -> pure projectKey
getProjectIdAndPath :: (Has HerculesClientToken r, Has HerculesClientEnv r) => Maybe ProjectPath -> RIO r (Maybe (Id Project), ProjectPath)
getProjectIdAndPath maybeProjectPathParam = do
case maybeProjectPathParam of
Nothing -> findProjectContextually
Just projectKey -> do
project <- findProjectByKey projectKey
pure (Project.id <$> project, projectKey)
findProjectByKey :: (Has HerculesClientToken r, Has HerculesClientEnv r) => ProjectPath -> RIO r (Maybe Project.Project)
findProjectByKey path =
runHerculesClient
( Projects.findProjects
projectsClient
(Just $ Name $ projectPathSite path)
(Just $ Name $ projectPathOwner path)
(Just $ Name $ projectPathProject path)
)
<&> head
findProjectContextually :: (Has HerculesClientToken r, Has HerculesClientEnv r) => RIO r (Maybe (Id Project), ProjectPath)
findProjectContextually = do
projectIdMaybe <- lookupEnv "HERCULES_CI_PROJECT_ID"
projectIdPathMaybe <- lookupEnv "HERCULES_CI_PROJECT_PATH"
case (,) <$> projectIdMaybe <*> projectIdPathMaybe of
Nothing -> findProjectByCurrentRepo
Just (id, pathText) -> do
projectPath <- parseProjectPathFromText (toS pathText) & escalateAs (\e -> FatalError $ "Invalid HERCULES_CI_PROJECT_PATH supplied: " <> toS e)
uuid <- Data.UUID.fromString id & maybeToEither (FatalError "Invalid UUID in HERCULES_CI_PROJECT_ID") & escalate
pure (Just (Id uuid), projectPath)
findProjectByCurrentRepo :: (Has HerculesClientToken r, Has HerculesClientEnv r) => RIO r (Maybe (Id Project), ProjectPath)
findProjectByCurrentRepo = do
url <- liftIO Git.getUpstreamURL
rs <- runHerculesClientEither (Repos.parseGitURL reposClient url)
case rs of
Left (FailureResponse _req Response {responseStatusCode = Status {statusCode = 404}}) -> do
exitMsg "Repository not recognized by Hercules CI. Make sure you're in the right repository, and if you're running Hercules CI Enterprise, make sure you're using the right HERCULES_CI_API_BASE_URL. Alternatively, use the --project option."
Left e -> throwIO e
Right r ->
pure
( RepoKey.projectId r,
ProjectPath
{ projectPathSite = RepoKey.siteName r,
projectPathOwner = RepoKey.ownerName r,
projectPathProject = RepoKey.repoName r
}
)
findProject :: (Has HerculesClientToken r, Has HerculesClientEnv r) => ProjectPath -> RIO r Project.Project
findProject project = do
rs <-
runHerculesClient
( findProjects
projectsClient
(Just $ Name $ projectPathSite project)
(Just $ Name $ projectPathOwner project)
(Just $ Name $ projectPathProject project)
)
case rs of
[] -> do
exitMsg $ "Project not found: " <> show project
[p] -> pure p
_ -> do
exitMsg $ "Project ambiguous: " <> show project
projectResourceClientByPath :: ProjectPath -> ProjectResourceGroup ClientAuth (AsClientT ClientM)
projectResourceClientByPath projectPath =
projectsClient `enterApiE` \api ->
byProjectName
api
(Name $ projectPathSite projectPath)
(Name $ projectPathOwner projectPath)
(Name $ projectPathProject projectPath)
|
|
a30b3df230e7e6df8e06cfa0897e1a0ce80ef04a232b39b0664f6e3a3f7d84ff
|
rurban/clisp
|
floatprint.lisp
|
;; Printing of Floating-Point-Numbers with PRINT and FORMAT
10.2.1990 - 26.3.1990
8.9.1990 - 10.9.1990
Translation : 2003 - 04 - 26
The German variable names ' unten ' and ' oben ' where translated with
' below ' resp . ' above ' in English !
wlog = = without loss of generality
2004 - 03 - 27 : Fixed printing of short floats like 1782592s0 .
;; basic idea:
;; Each real-number /= 0 represents an (open) interval. We print the
;; decimal number with as few digits as possible, that is situated in
;; this interval.
In order to also treat big exponents , powers of 2 are approximately
turned into powers of 10 . If necessary , the computing accuracy is
;; increased. Here we utilize long-floats of arbitrary precision.
(in-package "SYSTEM")
;; based on:
;; (sys::log2 digits) returns ln(2) with at least DIGITS mantissa bits.
;; (sys::log10 digits) returns ln(10) with at least DIGITS mantissa bits.
;; (sys::decimal-string integer) returns for an integer >0
;; a simple-string with its decimal presentation.
( substring string start [ end ] ) like SUBSEQ , however faster for strings .
;; the main function for conversion of floats into the decimal system:
For a float X we calculate a Simple - String AS and three Integers K , E , S
;; with the following properties:
;; s = sign(x).
If , consider |x| instead of x. Thus , wlog , let .
;; Let x1 and x2 be the next smaller resp. the next bigger number for x
;; of the same floating-point-format. Consequently, the number x represents
the open interval from ( to ( x+x2)/2 .
A is an integer > 0 , with exactly K decimal places ( K > = 1 ) , and
( x+x1)/2 < a*10^(-k+e ) < ( x+x2)/2 .
K is minimal , so A is not divisible by 10 .
If fixed - point - adjust is true and 1 < = |x| < 10 ^ 7 , more precision
is provided by assuming that K needs only to be > = E+1 , and no effort
is made to minimize K below E+1 if it would discard nonzero digits .
if x=0 , then a=0 , k=1 , e=0 .
AS is the sequence of digits of A , of length K.
(defun decode-float-decimal (x fixed-point-adjust)
(declare (type float x))
(multiple-value-bind (binmant binexpo sign) (integer-decode-float x)
x=0 ?
a=0 , k=1 , e=0 , s=0
;; x/=0, so sign is the sign of x and
|x| = 2^binexpo * float(binmant , x ) . From now on , let , wlog .
x = 2^binexpo * float(binmant , x ) .
(let* ((l (integer-length binmant)) ; number of bits of binmant
2*binmant
(above (1+ 2*binmant)) ; upper interval boundary is
( x+x2)/2 = 2^(binexpo-1 ) * above
(below (1- 2*binmant)) ; lower interval boundary is
( x+x1)/2 = 2^(binexpo-1 - belowshift ) * below
(when (eql (integer-length below) l)
;; normally, integerlength(below) = 1+integerlength(binmant).
;; Here, integerlength(below) = l = integerlength(binmant),
thus , binmant was a power of two . In this case the tolerance
upwards is 1/2 unit , but the tolerance downwards is only
1/4 unit : ( x+x1)/2 = 2^(binexpo-2 ) * ( 4*binmant-1 )
(setq below (1- (ash 2*binmant 1)) belowshift 1))
determine d ( integer ) and a1,a2 ( integer , > 0 ) thus that
the integer a with ( < 10^d * a < ( x+x2)/2 are exactly
the integer a with a1 < = a < = a2 and 0 < = a2 - a1 < 20 .
Therefore , convert 2^e : = 2^(binexpo-1 ) into the decimal system .
(let* ((e (- binexpo 1))
(e-gross (> (abs e) (ash l 1))) ; if |e| is very large, >2*l ?
g f ; auxiliary variables in case that |e| is large
auxiliary variable 10^|d| in case that |e| is small
d a1 a2); result variables
(if e-gross ; is |e| really big?
;; As 2^e can work only approximately, we need safety bits.
number of safety bits , must be > = 3
new-safety-bits
target : 2^e ~= 10^d * f/2^g , with 1 < = f/2^g < 10 .
(setq g (+ l h)) ; number of valid bits of f
;; Estimate d = floor(e*lg(2))
;; with help of the rational approximations of lg(2):
0 1/3 3/10 28/93 59/196 146/485 643/2136 4004/13301
8651/28738 12655/42039 21306/70777 76573/254370 97879/325147
;; 1838395/6107016 1936274/6432163 13456039/44699994
15392313/51132157 44240665/146964308 59632978/198096465
103873643/345060773 475127550/1578339557 579001193/1923400330
;; e>=0 : choose lg(2) < a/b < lg(2) + 1/e,
;; then d <= floor(e*a/b) <= d+1 .
;; e<0 : then lg(2) - 1/abs(e) < a/b < lg(2),
;; then d <= floor(e*a/b) <= d+1 .
It is known that abs(e ) < = 2 ^ 31 + 2 ^ 20 .
;; Let d be := floor(e*a/b)-1.
(setq d (1- (if (minusp e)
(if (>= e -970)
3/10
(floor (* e 21306) 70777)) ; 21306/70777
(if (<= e 22000)
28/93
12655/42039
;; The true d is either matched by this estimation
or undervalued by 1 .
In other " words " : 0 < e*log(2)-d*log(10 ) < 2*log(10 ) .
;; now, calculate f/2^g as exp(e*log(2)-d*log(10)) .
As f < 100 * 2^g < 2^(g+7 ) , we need g+7 bits relative accuracy
;; of the result, i.e g+7 bits absolute accuracy of
;; e*log(2)-d*log(10) . With l'=integer-length(e)
log(2 ): g+7+l ' bits abs . accuracy , g+7+l ' bits rel . acc . ,
log(10 ): g+7+l ' bits abs . accuracy , g+7+l'+2 bits rel . acc .
(let ((f/2^g (let ((gen (+ g (integer-length e) 9))) ; accuracy
(exp (- (* e (sys::log2 gen))
(* d (sys::log10 gen)))))))
the calculated f/2^g is > 1 , < 100 .
multiply with 2^g and round to an integer number :
(setq f (round (scale-float f/2^g g)))) ; returns f
;; Possibly correct f and d:
f > = 10 * 2^g ?
(setq f (floor f 10) d (+ d 1)))
Now 2^e ~= 10^d * f/2^g , with 1 < = f/2^g < 10 and
f an Integer , that deviates from the true value at most by 1 :
10^d * ( f-1)/2^g < 2^e < 10^d * ( f+1)/2^g
;; we make the open interval now smaller
from ( x+x1)/2 = 2^(binexpo-1 - belowshift ) * below
to ( x+x2)/2 = 2^(binexpo-1 ) * above
;; into a closed interval
from 10^d * ( f+1)/2^(g+belowshift ) * below
to 10^d * ( f-1)/2^g * above
;; and search therein numbers of the form a*10^d with integer a.
since above - below/2^belowshift > = 3/2
and above + below/2^belowshift < = 4*binmant+1 < 2^(l+2 ) < = 2^(g-1 )
;; the interval-length is
= 10^d * ( ( f-1)*above - ( f+1)*below/2^belowshift ) / 2^g
= 10^d * ( f * ( above - below/2^belowshift )
- ( above + below/2^belowshift ) ) / 2^g
> = 10^d * ( 2^g * 3/2 - 2^(g-1 ) ) / 2^g
= 10^d * ( 3/2 - 2^(-1 ) ) = 10^d
and hence , there is at least one number of this form
;; in this interval.
The numbers of the form 10^d * a in this intervall are those
;; with a1 <= a <= a2, and a2 = floor((f-1)*above/2^g) and
;; a1 = ceiling((f+1)*below/2^(g+belowshift))
;; = floor(((f+1)*below-1)/2^(g+belowshift))+1 .
;; We have now seen, that a1 <= a2 .
(setq a1 (1+ (ash (1- (* (+ f 1) below)) (- (+ g belowshift)))))
(setq a2 (ash (* (- f 1) above) (- g)))
;; We can also nest the open interval
from ( x+x1)/2 = 2^(binexpo-1 - belowshift ) * below
to ( x+x2)/2 = 2^(binexpo-1 ) * above
;; into the (closed) interval
from 10^d * ( f-1)/2^(g+belowshift ) * below
to 10^d * ( f+1)/2^g * above
Herein are the numbers of the form 10^d * a
;; with a1' <= a <= a2', with a1' <= a1 <= a2 <= a2' and that
;; can be calculated with a1' and a2' analogous to a1 and a2.
As ( f-1)*above/2^g and ( f+1)*above/2^g differ by 2*above/2^g
< 2^(l+2 - g ) < 1 , a2 and
;; a2' differ by at most 1.
;; Likewise, if 'above' is replaced by 'below/2^belowshift':
;; a1' and a1 differ by at most 1.
If a1 ' < a1 or a2 < a2 ' , then the power - of-2 - approximation-
10^d * f/2^g for 2^e has not been accurate enough ,
;; and we have to repeat everything with increased h.
;; Exception (when even higer precision does not help):
If the upper or lower interval boundary ( x+x2)/2 resp .
( x+x1)/2 has itself the shape 10^d * a with integer a.
;; This is tested via:
( x+x2)/2 = 2^e * above = = 10^d * a with integer a , if
- for e>=0 , ( then 0 < = d < = e ): 5^d | above ,
- for e<0 , ( then e < = d < 0 ): 2^(d - e ) | above , which is
;; the case only for d-e=0 .
( = 2^(e - belowshift ) * below = = 10^d * a
;; with integer a, if
- for e>0 , ( then 0 < = d < e ): 5^d | below ,
- for e<=0 , ( then e < = d < = 0 ): 2^(d - e+belowshift ) | below ,
;; which is only the case for d-e+belowshift=0.
;; As we deal here with higher |e| , this exceptional cause
;; cannot happen here at all!
Then in case of e>=0 : e>=2*l and l>=11 imply
;; e >= (l+2)*ln(10)/ln(5) + ln(10)/ln(2),
;; d >= e*ln(2)/ln(10)-1 >= (l+2)*ln(2)/ln(5),
5^d > = 2^(l+2 ) ,
and because of 0 < below < 2^(l+2 ) and 0 < above < 2^(l+1 )
below and above are not divisible by 5^d .
;; And in case e<=0: From -e>=2*l and l>=6 can be implied
;; -e >= (l+2)*ln(10)/ln(5),
;; d-e >= e*ln(2)/ln(10)-1-e = (1-ln(2)/ln(10))*(-e)-1
;; = (-e)*ln(5)/ln(10)-1 >= l+1,
;; 2^(d-e) >= 2^(l+1),
and because of 0 < below < 2^(l+1+belowshift ) , below is not
divisible by 2^(d - e+belowshift ) , and because of
0 < above < 2^(l+1 ) , above is not divisible by 2^(d - e ) .
(when (or (< (1+ (ash (1- (* (- f 1) below))
(- (+ g belowshift)))) ; a1'
a1)
(< a2 (ash (* (+ f 1) above) (- g)))) ; a2<a2'
(setq h (ash h 1)) ; double h
(go new-safety-bits)) ; and repeat everything
;; Now a1 is the smallest and a2 is the biggest value, that is
;; possible for a.
Because of above - below/2^belowshift < = 2
;; the above interval-length is
= 10^d * ( ( f-1)*above - ( f+1)*below/2^belowshift ) / 2^g
< 10^d * ( ( f-1)*above - ( f-1)*below/2^belowshift ) / 2^g
= 10^d * ( f-1)/2^g * ( above - below/2^belowshift )
< 10^d * 10 * 2 ,
so there are at most 20 possible values for a.
) ; PROG is done
|e| is relatively small - > can calculate 2^e and 10^d exactly
(if (not (minusp e))
;; e >= 0. Estimate d = floor(e*lg(2)) as above.
e<=2*l<2 ^ 21 .
(progn
(setq d (if (<= e 22000)
28/93
4004/13301
;; The true d is either matched by this estimate
or overestimated by 1 , but we can find this out easily .
ten - d = 10^d
if 2^e < 10^d ,
(setq d (- d 1) ten-d (floor ten-d 10))) ; correct estimate
Now 10^d < = 2^e < 10^(d+1 ) and ten - d = 10^d .
(if (and fixed-point-adjust
(<= binmant (ash 9999999 (- binexpo))))
|x| < 10 ^ 7 and we want fixed - point notation . Force d
;; to stay <= -1, i.e. return more digits than we would do
;; in scientific notation.
(progn
Set d = -1 and a1 = a2 = 2^e * 2*binmant / 10^d .
;; Or, since we know that e>=0 implies that these a1 and a2
end in a trailing zero and the caller can add zeroes
;; at the end on his own:
Set d = 0 and a1 = a2 = 2^e * 2*binmant / 10^d .
(setq d 0)
(setq a1 (setq a2 (ash binmant (1+ e)))))
(progn
;; let a1 be the smallest integer
a > 2^(e - belowshift ) * below / 10^d ,
let a2 be the largest integer a < 2^e * above / 10^d .
;; a1 = 1+floor(below*2^e/(2^belowshift*10^d)),
;; a2 = floor((above*2^e-1)/10^d).
(setq a1 (1+ (floor (ash below e) (ash ten-d belowshift))))
even represent top - inclusive intervals
(setq a2 (if (evenp binmant)
(floor (ash above e) ten-d)
(floor (1- (ash above e)) ten-d))))))
;; e < 0. Estimate d = floor(e*lg(2)) like above.
|e|<=2*l<2 ^ 21 .
(progn
(setq d (if (>= e -970)
3/10
643/2136
;; The true d is either matched by this estimate
or overestimated by 1 , but we can find this out easily .
(setq ten-d (expt 10 (- d))) ; ten-d = 10^(-d)
if 2^e < 10^d ,
(setq d (- d 1) ten-d (* ten-d 10))) ; correct estimate
now 10^d < = 2^e < 10^(d+1 ) and ten - d = 10^(-d ) .
;; let a1 be the smallest integer
a > 2^(e - belowshift ) * below / 10^d ,
let a2 be the largest integer a < 2^e * above / 10^d .
;; a1 = 1+floor(below*10^(-d)/2^(-e+belowshift)),
;; a2 = floor((above*10^(-d)-1)/2^(-e))
(setq a1 (1+ (ash (* below ten-d) (- e belowshift))))
;; for some reason the (evenp binmant) does not make a
;; difference here
(setq a2 (ash (1- (* above ten-d)) e)))))
Now the integer a 's with ( < 10^d * a < ( x+x2)/2 are
;; exactly the integer a's with a1 <= a <= a2. There are at most 20.
These are reduced to a single one with three steps :
1 . Does the region contain a number a that is divisible by 10 ?
;; yes -> set a1:=ceiling(a1/10), a2:=floor(a2/10), d:=d+1.
;; After that, the region a1 <= a <= a2 contains at most 10
;; possible values for a.
2 . If now one of the possible values is divisible by 10
( there can be only one ... :-) ) ,
;; it is chosen, the others are forgotten.
3 . Else , the closest value to x is chosen among the other
;; possible values.
flag , if d was incremented in the first step
a) ; the chosen a
1 .
(let ((b1 (ceiling a1 10))
(b2 (floor a2 10)))
still a number divisible by 10 ?
(setq a1 b1 a2 b2 d (+ d 1) d-shift t)
(go no-10-more)))
2 .
(when (>= (* 10 (setq a (floor a2 10))) a1)
Still a number divisible by 10 - > divide by 10 .
increase d , ten - d not needed anymore
;; Now convert a into a decimal string
;; and then discard the zeroes at the tail:
digit sequence for a>0
(las (length as)) ; length of the digit sequence
(k las) ; length without the discarded zeroes at the tail
a * 10^d = a * 10^(-k+ee )
(loop
(let ((k-1 (- k 1)))
(unless (eql (schar as k-1) #\0) ; a 0 at the end?
(return))
yes - > a : = a / 10 ( but is not needed anymore ) ,
;; d := d+1 (but is not needed anymore),
(setq k k-1))) ; k := k-1.
(when (< k las) (setq as (substring as 0 k)))
(return (values as k ee sign))))
3 .
no-10-more
(setq a
(if (eql a1 a2) ; a1=a2 -> there is no more choice:
a1
a1 < a2 - > choose 10^d*a closest to x :
;; choose a = round(f*2*binmant/2^g/(1oder10)) (any rounding)
;; = ceiling(floor(f*2*binmant/(1oder10)/2^(g-1))/2)
(ash (1+ (ash (let ((z (* f 2*binmant)))
(if d-shift (floor z 10) z))
(- 1 g)))
-1)
;; |e| small -> analogous as a2 was computed above
(if (not (minusp e))
;; e>=0: a = round(2^e*2*binmant/10^d)
10^d according to d - shift
(if d-shift (* 10 ten-d) ten-d))
e<0 , so d<0 , now ( because of step 1 ) d<=0 .
;; a = round(2*binmant*10^(-d)/2^(-e))
(ash (1+ (ash
(* 2*binmant ; 10^(-d) according to d-shift
(if d-shift (floor ten-d 10) ten-d))
(+ e 1)))
-1)))))
(let* ((as (sys::decimal-string a)) ; digit sequence of a
(k (length as)))
(return (values as k (+ k d) sign)))))))))
;; output function for PRINT/WRITE of floats:
(defun write-float-decimal (stream arg #| &optional (plus-sign-flag nil) |# )
(unless (floatp arg)
(error-of-type 'type-error
:datum arg :expected-type 'float
(TEXT "argument is not a float: ~S")
arg))
(multiple-value-bind (mantstring mantlen expo sign)
(decode-float-decimal arg t)
arg in decimal representation : + /- 0.mant * 10^expo , whereby
;; mant is the mantissa: as Simple-String mantstring of length mantlen,
;; expo is the decimal-exponent,
sign is the sign ( -1 or 0 or 1 ) .
(if (eql sign -1) ; arg < 0 ?
(write-char #\- stream)
#| (if plus-sign-flag (write-char #\+ stream)) |#
)
arg=0 or 10 ^ -3 < = ( abs arg ) < 10 ^ 7 ?
;; What to print? definition by cases:
;; flag set -> "fixed-point notation":
expo < = 0 - > zero , decimal dot , -expo zeroes , all digits
;; 0 < expo < mantlen ->
the first expo digits , decimal dot , the remaining digits
expo > = mantlen - > all digits , expo - mantlen zeroes , decimal dot , zero
;; if possible, no exponent; if necessary, exponent 0.
;; flag deleted -> "scientific notation":
first digit , decimal dot , the remaining digits , with mantlen=1
a zero exponent .
(if (and flag (not (plusp expo)))
" fixed - point notation " with expo < = 0
first null and decimal dot , then -expo zeroes , then all digits
(progn
(write-char #\0 stream)
(write-char #\. stream)
(do ((i expo (+ i 1)))
((eql i 0))
(write-char #\0 stream))
(write-string mantstring stream)
(setq expo 0)) ; exponent to print is 0
;; "fixed-point notation" with expo > 0 or "scientific notation"
(let ((scale (if flag expo 1)))
;; the decimal dot is shifted by scale digits to the right,
;; i.e. there are scale digits in front of the dot. scale > 0.
(if (< scale mantlen)
first scale digits , then decimal dot , then remaining digits :
(progn
(write-string mantstring stream :end scale)
(write-char #\. stream)
(write-string mantstring stream :start scale))
;; scale>=mantlen -> there are no digits behind the dot.
all digits , then scale - mantlen zeroes , then dot and zero
(progn
(write-string mantstring stream)
(do ((i mantlen (+ i 1)))
((eql i scale))
(write-char #\0 stream))
(write-char #\. stream)
(write-char #\0 stream)))
(decf expo scale))) ; the exponent to print is smaller by scale.
;; now let's go for the exponent:
(let ((e-marker
(cond ((and (not *PRINT-READABLY*)
(case *READ-DEFAULT-FLOAT-FORMAT*
(SHORT-FLOAT (short-float-p arg))
(SINGLE-FLOAT (single-float-p arg))
(DOUBLE-FLOAT (double-float-p arg))
(LONG-FLOAT (long-float-p arg))))
#\E)
((short-float-p arg) #\s)
((single-float-p arg) #\f)
((double-float-p arg) #\d)
((long-float-p arg) #\L))))
poss . omit Exponent entirely
(write-char e-marker stream)
(write expo :base 10 :radix nil :readably nil :stream stream))))))
| null |
https://raw.githubusercontent.com/rurban/clisp/75ed2995ff8f5364bcc18727cde9438cca4e7c2c/src/floatprint.lisp
|
lisp
|
Printing of Floating-Point-Numbers with PRINT and FORMAT
basic idea:
Each real-number /= 0 represents an (open) interval. We print the
decimal number with as few digits as possible, that is situated in
this interval.
increased. Here we utilize long-floats of arbitrary precision.
based on:
(sys::log2 digits) returns ln(2) with at least DIGITS mantissa bits.
(sys::log10 digits) returns ln(10) with at least DIGITS mantissa bits.
(sys::decimal-string integer) returns for an integer >0
a simple-string with its decimal presentation.
the main function for conversion of floats into the decimal system:
with the following properties:
s = sign(x).
Let x1 and x2 be the next smaller resp. the next bigger number for x
of the same floating-point-format. Consequently, the number x represents
x/=0, so sign is the sign of x and
number of bits of binmant
upper interval boundary is
lower interval boundary is
normally, integerlength(below) = 1+integerlength(binmant).
Here, integerlength(below) = l = integerlength(binmant),
if |e| is very large, >2*l ?
auxiliary variables in case that |e| is large
result variables
is |e| really big?
As 2^e can work only approximately, we need safety bits.
number of valid bits of f
Estimate d = floor(e*lg(2))
with help of the rational approximations of lg(2):
1838395/6107016 1936274/6432163 13456039/44699994
e>=0 : choose lg(2) < a/b < lg(2) + 1/e,
then d <= floor(e*a/b) <= d+1 .
e<0 : then lg(2) - 1/abs(e) < a/b < lg(2),
then d <= floor(e*a/b) <= d+1 .
Let d be := floor(e*a/b)-1.
21306/70777
The true d is either matched by this estimation
now, calculate f/2^g as exp(e*log(2)-d*log(10)) .
of the result, i.e g+7 bits absolute accuracy of
e*log(2)-d*log(10) . With l'=integer-length(e)
accuracy
returns f
Possibly correct f and d:
we make the open interval now smaller
into a closed interval
and search therein numbers of the form a*10^d with integer a.
the interval-length is
in this interval.
with a1 <= a <= a2, and a2 = floor((f-1)*above/2^g) and
a1 = ceiling((f+1)*below/2^(g+belowshift))
= floor(((f+1)*below-1)/2^(g+belowshift))+1 .
We have now seen, that a1 <= a2 .
We can also nest the open interval
into the (closed) interval
with a1' <= a <= a2', with a1' <= a1 <= a2 <= a2' and that
can be calculated with a1' and a2' analogous to a1 and a2.
a2' differ by at most 1.
Likewise, if 'above' is replaced by 'below/2^belowshift':
a1' and a1 differ by at most 1.
and we have to repeat everything with increased h.
Exception (when even higer precision does not help):
This is tested via:
the case only for d-e=0 .
with integer a, if
which is only the case for d-e+belowshift=0.
As we deal here with higher |e| , this exceptional cause
cannot happen here at all!
e >= (l+2)*ln(10)/ln(5) + ln(10)/ln(2),
d >= e*ln(2)/ln(10)-1 >= (l+2)*ln(2)/ln(5),
And in case e<=0: From -e>=2*l and l>=6 can be implied
-e >= (l+2)*ln(10)/ln(5),
d-e >= e*ln(2)/ln(10)-1-e = (1-ln(2)/ln(10))*(-e)-1
= (-e)*ln(5)/ln(10)-1 >= l+1,
2^(d-e) >= 2^(l+1),
a1'
a2<a2'
double h
and repeat everything
Now a1 is the smallest and a2 is the biggest value, that is
possible for a.
the above interval-length is
PROG is done
e >= 0. Estimate d = floor(e*lg(2)) as above.
The true d is either matched by this estimate
correct estimate
to stay <= -1, i.e. return more digits than we would do
in scientific notation.
Or, since we know that e>=0 implies that these a1 and a2
at the end on his own:
let a1 be the smallest integer
a1 = 1+floor(below*2^e/(2^belowshift*10^d)),
a2 = floor((above*2^e-1)/10^d).
e < 0. Estimate d = floor(e*lg(2)) like above.
The true d is either matched by this estimate
ten-d = 10^(-d)
correct estimate
let a1 be the smallest integer
a1 = 1+floor(below*10^(-d)/2^(-e+belowshift)),
a2 = floor((above*10^(-d)-1)/2^(-e))
for some reason the (evenp binmant) does not make a
difference here
exactly the integer a's with a1 <= a <= a2. There are at most 20.
yes -> set a1:=ceiling(a1/10), a2:=floor(a2/10), d:=d+1.
After that, the region a1 <= a <= a2 contains at most 10
possible values for a.
it is chosen, the others are forgotten.
possible values.
the chosen a
Now convert a into a decimal string
and then discard the zeroes at the tail:
length of the digit sequence
length without the discarded zeroes at the tail
a 0 at the end?
d := d+1 (but is not needed anymore),
k := k-1.
a1=a2 -> there is no more choice:
choose a = round(f*2*binmant/2^g/(1oder10)) (any rounding)
= ceiling(floor(f*2*binmant/(1oder10)/2^(g-1))/2)
|e| small -> analogous as a2 was computed above
e>=0: a = round(2^e*2*binmant/10^d)
a = round(2*binmant*10^(-d)/2^(-e))
10^(-d) according to d-shift
digit sequence of a
output function for PRINT/WRITE of floats:
&optional (plus-sign-flag nil)
mant is the mantissa: as Simple-String mantstring of length mantlen,
expo is the decimal-exponent,
arg < 0 ?
(if plus-sign-flag (write-char #\+ stream))
What to print? definition by cases:
flag set -> "fixed-point notation":
0 < expo < mantlen ->
if possible, no exponent; if necessary, exponent 0.
flag deleted -> "scientific notation":
exponent to print is 0
"fixed-point notation" with expo > 0 or "scientific notation"
the decimal dot is shifted by scale digits to the right,
i.e. there are scale digits in front of the dot. scale > 0.
scale>=mantlen -> there are no digits behind the dot.
the exponent to print is smaller by scale.
now let's go for the exponent:
|
10.2.1990 - 26.3.1990
8.9.1990 - 10.9.1990
Translation : 2003 - 04 - 26
The German variable names ' unten ' and ' oben ' where translated with
' below ' resp . ' above ' in English !
wlog = = without loss of generality
2004 - 03 - 27 : Fixed printing of short floats like 1782592s0 .
In order to also treat big exponents , powers of 2 are approximately
turned into powers of 10 . If necessary , the computing accuracy is
(in-package "SYSTEM")
( substring string start [ end ] ) like SUBSEQ , however faster for strings .
For a float X we calculate a Simple - String AS and three Integers K , E , S
If , consider |x| instead of x. Thus , wlog , let .
the open interval from ( to ( x+x2)/2 .
A is an integer > 0 , with exactly K decimal places ( K > = 1 ) , and
( x+x1)/2 < a*10^(-k+e ) < ( x+x2)/2 .
K is minimal , so A is not divisible by 10 .
If fixed - point - adjust is true and 1 < = |x| < 10 ^ 7 , more precision
is provided by assuming that K needs only to be > = E+1 , and no effort
is made to minimize K below E+1 if it would discard nonzero digits .
if x=0 , then a=0 , k=1 , e=0 .
AS is the sequence of digits of A , of length K.
(defun decode-float-decimal (x fixed-point-adjust)
(declare (type float x))
(multiple-value-bind (binmant binexpo sign) (integer-decode-float x)
x=0 ?
a=0 , k=1 , e=0 , s=0
|x| = 2^binexpo * float(binmant , x ) . From now on , let , wlog .
x = 2^binexpo * float(binmant , x ) .
2*binmant
( x+x2)/2 = 2^(binexpo-1 ) * above
( x+x1)/2 = 2^(binexpo-1 - belowshift ) * below
(when (eql (integer-length below) l)
thus , binmant was a power of two . In this case the tolerance
upwards is 1/2 unit , but the tolerance downwards is only
1/4 unit : ( x+x1)/2 = 2^(binexpo-2 ) * ( 4*binmant-1 )
(setq below (1- (ash 2*binmant 1)) belowshift 1))
determine d ( integer ) and a1,a2 ( integer , > 0 ) thus that
the integer a with ( < 10^d * a < ( x+x2)/2 are exactly
the integer a with a1 < = a < = a2 and 0 < = a2 - a1 < 20 .
Therefore , convert 2^e : = 2^(binexpo-1 ) into the decimal system .
(let* ((e (- binexpo 1))
auxiliary variable 10^|d| in case that |e| is small
number of safety bits , must be > = 3
new-safety-bits
target : 2^e ~= 10^d * f/2^g , with 1 < = f/2^g < 10 .
0 1/3 3/10 28/93 59/196 146/485 643/2136 4004/13301
8651/28738 12655/42039 21306/70777 76573/254370 97879/325147
15392313/51132157 44240665/146964308 59632978/198096465
103873643/345060773 475127550/1578339557 579001193/1923400330
It is known that abs(e ) < = 2 ^ 31 + 2 ^ 20 .
(setq d (1- (if (minusp e)
(if (>= e -970)
3/10
(if (<= e 22000)
28/93
12655/42039
or undervalued by 1 .
In other " words " : 0 < e*log(2)-d*log(10 ) < 2*log(10 ) .
As f < 100 * 2^g < 2^(g+7 ) , we need g+7 bits relative accuracy
log(2 ): g+7+l ' bits abs . accuracy , g+7+l ' bits rel . acc . ,
log(10 ): g+7+l ' bits abs . accuracy , g+7+l'+2 bits rel . acc .
(exp (- (* e (sys::log2 gen))
(* d (sys::log10 gen)))))))
the calculated f/2^g is > 1 , < 100 .
multiply with 2^g and round to an integer number :
f > = 10 * 2^g ?
(setq f (floor f 10) d (+ d 1)))
Now 2^e ~= 10^d * f/2^g , with 1 < = f/2^g < 10 and
f an Integer , that deviates from the true value at most by 1 :
10^d * ( f-1)/2^g < 2^e < 10^d * ( f+1)/2^g
from ( x+x1)/2 = 2^(binexpo-1 - belowshift ) * below
to ( x+x2)/2 = 2^(binexpo-1 ) * above
from 10^d * ( f+1)/2^(g+belowshift ) * below
to 10^d * ( f-1)/2^g * above
since above - below/2^belowshift > = 3/2
and above + below/2^belowshift < = 4*binmant+1 < 2^(l+2 ) < = 2^(g-1 )
= 10^d * ( ( f-1)*above - ( f+1)*below/2^belowshift ) / 2^g
= 10^d * ( f * ( above - below/2^belowshift )
- ( above + below/2^belowshift ) ) / 2^g
> = 10^d * ( 2^g * 3/2 - 2^(g-1 ) ) / 2^g
= 10^d * ( 3/2 - 2^(-1 ) ) = 10^d
and hence , there is at least one number of this form
The numbers of the form 10^d * a in this intervall are those
(setq a1 (1+ (ash (1- (* (+ f 1) below)) (- (+ g belowshift)))))
(setq a2 (ash (* (- f 1) above) (- g)))
from ( x+x1)/2 = 2^(binexpo-1 - belowshift ) * below
to ( x+x2)/2 = 2^(binexpo-1 ) * above
from 10^d * ( f-1)/2^(g+belowshift ) * below
to 10^d * ( f+1)/2^g * above
Herein are the numbers of the form 10^d * a
As ( f-1)*above/2^g and ( f+1)*above/2^g differ by 2*above/2^g
< 2^(l+2 - g ) < 1 , a2 and
If a1 ' < a1 or a2 < a2 ' , then the power - of-2 - approximation-
10^d * f/2^g for 2^e has not been accurate enough ,
If the upper or lower interval boundary ( x+x2)/2 resp .
( x+x1)/2 has itself the shape 10^d * a with integer a.
( x+x2)/2 = 2^e * above = = 10^d * a with integer a , if
- for e>=0 , ( then 0 < = d < = e ): 5^d | above ,
- for e<0 , ( then e < = d < 0 ): 2^(d - e ) | above , which is
( = 2^(e - belowshift ) * below = = 10^d * a
- for e>0 , ( then 0 < = d < e ): 5^d | below ,
- for e<=0 , ( then e < = d < = 0 ): 2^(d - e+belowshift ) | below ,
Then in case of e>=0 : e>=2*l and l>=11 imply
5^d > = 2^(l+2 ) ,
and because of 0 < below < 2^(l+2 ) and 0 < above < 2^(l+1 )
below and above are not divisible by 5^d .
and because of 0 < below < 2^(l+1+belowshift ) , below is not
divisible by 2^(d - e+belowshift ) , and because of
0 < above < 2^(l+1 ) , above is not divisible by 2^(d - e ) .
(when (or (< (1+ (ash (1- (* (- f 1) below))
a1)
Because of above - below/2^belowshift < = 2
= 10^d * ( ( f-1)*above - ( f+1)*below/2^belowshift ) / 2^g
< 10^d * ( ( f-1)*above - ( f-1)*below/2^belowshift ) / 2^g
= 10^d * ( f-1)/2^g * ( above - below/2^belowshift )
< 10^d * 10 * 2 ,
so there are at most 20 possible values for a.
|e| is relatively small - > can calculate 2^e and 10^d exactly
(if (not (minusp e))
e<=2*l<2 ^ 21 .
(progn
(setq d (if (<= e 22000)
28/93
4004/13301
or overestimated by 1 , but we can find this out easily .
ten - d = 10^d
if 2^e < 10^d ,
Now 10^d < = 2^e < 10^(d+1 ) and ten - d = 10^d .
(if (and fixed-point-adjust
(<= binmant (ash 9999999 (- binexpo))))
|x| < 10 ^ 7 and we want fixed - point notation . Force d
(progn
Set d = -1 and a1 = a2 = 2^e * 2*binmant / 10^d .
end in a trailing zero and the caller can add zeroes
Set d = 0 and a1 = a2 = 2^e * 2*binmant / 10^d .
(setq d 0)
(setq a1 (setq a2 (ash binmant (1+ e)))))
(progn
a > 2^(e - belowshift ) * below / 10^d ,
let a2 be the largest integer a < 2^e * above / 10^d .
(setq a1 (1+ (floor (ash below e) (ash ten-d belowshift))))
even represent top - inclusive intervals
(setq a2 (if (evenp binmant)
(floor (ash above e) ten-d)
(floor (1- (ash above e)) ten-d))))))
|e|<=2*l<2 ^ 21 .
(progn
(setq d (if (>= e -970)
3/10
643/2136
or overestimated by 1 , but we can find this out easily .
if 2^e < 10^d ,
now 10^d < = 2^e < 10^(d+1 ) and ten - d = 10^(-d ) .
a > 2^(e - belowshift ) * below / 10^d ,
let a2 be the largest integer a < 2^e * above / 10^d .
(setq a1 (1+ (ash (* below ten-d) (- e belowshift))))
(setq a2 (ash (1- (* above ten-d)) e)))))
Now the integer a 's with ( < 10^d * a < ( x+x2)/2 are
These are reduced to a single one with three steps :
1 . Does the region contain a number a that is divisible by 10 ?
2 . If now one of the possible values is divisible by 10
( there can be only one ... :-) ) ,
3 . Else , the closest value to x is chosen among the other
flag , if d was incremented in the first step
1 .
(let ((b1 (ceiling a1 10))
(b2 (floor a2 10)))
still a number divisible by 10 ?
(setq a1 b1 a2 b2 d (+ d 1) d-shift t)
(go no-10-more)))
2 .
(when (>= (* 10 (setq a (floor a2 10))) a1)
Still a number divisible by 10 - > divide by 10 .
increase d , ten - d not needed anymore
digit sequence for a>0
a * 10^d = a * 10^(-k+ee )
(loop
(let ((k-1 (- k 1)))
(return))
yes - > a : = a / 10 ( but is not needed anymore ) ,
(when (< k las) (setq as (substring as 0 k)))
(return (values as k ee sign))))
3 .
no-10-more
(setq a
a1
a1 < a2 - > choose 10^d*a closest to x :
(ash (1+ (ash (let ((z (* f 2*binmant)))
(if d-shift (floor z 10) z))
(- 1 g)))
-1)
(if (not (minusp e))
10^d according to d - shift
(if d-shift (* 10 ten-d) ten-d))
e<0 , so d<0 , now ( because of step 1 ) d<=0 .
(ash (1+ (ash
(if d-shift (floor ten-d 10) ten-d))
(+ e 1)))
-1)))))
(k (length as)))
(return (values as k (+ k d) sign)))))))))
(unless (floatp arg)
(error-of-type 'type-error
:datum arg :expected-type 'float
(TEXT "argument is not a float: ~S")
arg))
(multiple-value-bind (mantstring mantlen expo sign)
(decode-float-decimal arg t)
arg in decimal representation : + /- 0.mant * 10^expo , whereby
sign is the sign ( -1 or 0 or 1 ) .
(write-char #\- stream)
)
arg=0 or 10 ^ -3 < = ( abs arg ) < 10 ^ 7 ?
expo < = 0 - > zero , decimal dot , -expo zeroes , all digits
the first expo digits , decimal dot , the remaining digits
expo > = mantlen - > all digits , expo - mantlen zeroes , decimal dot , zero
first digit , decimal dot , the remaining digits , with mantlen=1
a zero exponent .
(if (and flag (not (plusp expo)))
" fixed - point notation " with expo < = 0
first null and decimal dot , then -expo zeroes , then all digits
(progn
(write-char #\0 stream)
(write-char #\. stream)
(do ((i expo (+ i 1)))
((eql i 0))
(write-char #\0 stream))
(write-string mantstring stream)
(let ((scale (if flag expo 1)))
(if (< scale mantlen)
first scale digits , then decimal dot , then remaining digits :
(progn
(write-string mantstring stream :end scale)
(write-char #\. stream)
(write-string mantstring stream :start scale))
all digits , then scale - mantlen zeroes , then dot and zero
(progn
(write-string mantstring stream)
(do ((i mantlen (+ i 1)))
((eql i scale))
(write-char #\0 stream))
(write-char #\. stream)
(write-char #\0 stream)))
(let ((e-marker
(cond ((and (not *PRINT-READABLY*)
(case *READ-DEFAULT-FLOAT-FORMAT*
(SHORT-FLOAT (short-float-p arg))
(SINGLE-FLOAT (single-float-p arg))
(DOUBLE-FLOAT (double-float-p arg))
(LONG-FLOAT (long-float-p arg))))
#\E)
((short-float-p arg) #\s)
((single-float-p arg) #\f)
((double-float-p arg) #\d)
((long-float-p arg) #\L))))
poss . omit Exponent entirely
(write-char e-marker stream)
(write expo :base 10 :radix nil :readably nil :stream stream))))))
|
88296e65da8842fae33e86676bdab076c2cfc9051c358a8e31c4aebcba529821
|
elastic/apm-agent-ocaml
|
client.mli
|
include Elastic_apm.Client_intf.S with type 'a io := 'a Async.Deferred.t
val set_reporter : Elastic_apm_async_reporter.Reporter.t option -> unit
val make_context' :
?trace_id:Elastic_apm.Id.Trace_id.t ->
?parent_id:Elastic_apm.Id.Span_id.t ->
?request:Elastic_apm.Context.Http.Request.t ->
kind:string ->
string ->
context
val make_context :
?context:context ->
?request:Elastic_apm.Context.Http.Request.t ->
kind:string ->
string ->
context
val init_reporter :
Elastic_apm_async_reporter.Reporter.Host.t ->
Elastic_apm.Metadata.Service.t ->
unit
| null |
https://raw.githubusercontent.com/elastic/apm-agent-ocaml/d17dd0bb40f92c150befbd8c33a50e7bae165556/async_client/client.mli
|
ocaml
|
include Elastic_apm.Client_intf.S with type 'a io := 'a Async.Deferred.t
val set_reporter : Elastic_apm_async_reporter.Reporter.t option -> unit
val make_context' :
?trace_id:Elastic_apm.Id.Trace_id.t ->
?parent_id:Elastic_apm.Id.Span_id.t ->
?request:Elastic_apm.Context.Http.Request.t ->
kind:string ->
string ->
context
val make_context :
?context:context ->
?request:Elastic_apm.Context.Http.Request.t ->
kind:string ->
string ->
context
val init_reporter :
Elastic_apm_async_reporter.Reporter.Host.t ->
Elastic_apm.Metadata.Service.t ->
unit
|
|
94222396909da312e72c893a7714861a989d6444e527182072cdcfd0bd99425f
|
ghc/packages-Cabal
|
Condition.hs
|
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
module Distribution.Types.Condition (
Condition(..),
cNot,
cAnd,
cOr,
simplifyCondition,
) where
import Prelude ()
import Distribution.Compat.Prelude
-- | A boolean expression parameterized over the variable type used.
data Condition c = Var c
| Lit Bool
| CNot (Condition c)
| COr (Condition c) (Condition c)
| CAnd (Condition c) (Condition c)
deriving (Show, Eq, Typeable, Data, Generic)
-- | Boolean negation of a 'Condition' value.
cNot :: Condition a -> Condition a
cNot (Lit b) = Lit (not b)
cNot (CNot c) = c
cNot c = CNot c
| Boolean AND of two ' Condtion ' values .
cAnd :: Condition a -> Condition a -> Condition a
cAnd (Lit False) _ = Lit False
cAnd _ (Lit False) = Lit False
cAnd (Lit True) x = x
cAnd x (Lit True) = x
cAnd x y = CAnd x y
| Boolean OR of two ' Condition ' values .
cOr :: Eq v => Condition v -> Condition v -> Condition v
cOr (Lit True) _ = Lit True
cOr _ (Lit True) = Lit True
cOr (Lit False) x = x
cOr x (Lit False) = x
cOr c (CNot d)
| c == d = Lit True
cOr (CNot c) d
| c == d = Lit True
cOr x y = COr x y
instance Functor Condition where
f `fmap` Var c = Var (f c)
_ `fmap` Lit c = Lit c
f `fmap` CNot c = CNot (fmap f c)
f `fmap` COr c d = COr (fmap f c) (fmap f d)
f `fmap` CAnd c d = CAnd (fmap f c) (fmap f d)
instance Foldable Condition where
f `foldMap` Var c = f c
_ `foldMap` Lit _ = mempty
f `foldMap` CNot c = foldMap f c
f `foldMap` COr c d = foldMap f c `mappend` foldMap f d
f `foldMap` CAnd c d = foldMap f c `mappend` foldMap f d
instance Traversable Condition where
f `traverse` Var c = Var `fmap` f c
_ `traverse` Lit c = pure $ Lit c
f `traverse` CNot c = CNot `fmap` traverse f c
f `traverse` COr c d = COr `fmap` traverse f c <*> traverse f d
f `traverse` CAnd c d = CAnd `fmap` traverse f c <*> traverse f d
instance Applicative Condition where
pure = Var
(<*>) = ap
instance Monad Condition where
return = pure
-- Terminating cases
(>>=) (Lit x) _ = Lit x
(>>=) (Var x) f = f x
-- Recursing cases
(>>=) (CNot x ) f = CNot (x >>= f)
(>>=) (COr x y) f = COr (x >>= f) (y >>= f)
(>>=) (CAnd x y) f = CAnd (x >>= f) (y >>= f)
instance Monoid (Condition a) where
mempty = Lit False
mappend = (<>)
instance Semigroup (Condition a) where
(<>) = COr
instance Alternative Condition where
empty = mempty
(<|>) = mappend
instance MonadPlus Condition where
mzero = mempty
mplus = mappend
instance Binary c => Binary (Condition c)
instance Structured c => Structured (Condition c)
instance NFData c => NFData (Condition c) where rnf = genericRnf
-- | Simplify the condition and return its free variables.
simplifyCondition :: Condition c
-> (c -> Either d Bool) -- ^ (partial) variable assignment
-> (Condition d, [d])
simplifyCondition cond i = fv . walk $ cond
where
walk cnd = case cnd of
Var v -> either Var Lit (i v)
Lit b -> Lit b
CNot c -> case walk c of
Lit True -> Lit False
Lit False -> Lit True
c' -> CNot c'
COr c d -> case (walk c, walk d) of
(Lit False, d') -> d'
(Lit True, _) -> Lit True
(c', Lit False) -> c'
(_, Lit True) -> Lit True
(c',d') -> COr c' d'
CAnd c d -> case (walk c, walk d) of
(Lit False, _) -> Lit False
(Lit True, d') -> d'
(_, Lit False) -> Lit False
(c', Lit True) -> c'
(c',d') -> CAnd c' d'
-- gather free vars
fv c = (c, fv' c)
fv' c = case c of
Var v -> [v]
Lit _ -> []
CNot c' -> fv' c'
COr c1 c2 -> fv' c1 ++ fv' c2
CAnd c1 c2 -> fv' c1 ++ fv' c2
| null |
https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/Cabal/Distribution/Types/Condition.hs
|
haskell
|
# LANGUAGE DeriveDataTypeable #
| A boolean expression parameterized over the variable type used.
| Boolean negation of a 'Condition' value.
Terminating cases
Recursing cases
| Simplify the condition and return its free variables.
^ (partial) variable assignment
gather free vars
|
# LANGUAGE DeriveGeneric #
module Distribution.Types.Condition (
Condition(..),
cNot,
cAnd,
cOr,
simplifyCondition,
) where
import Prelude ()
import Distribution.Compat.Prelude
data Condition c = Var c
| Lit Bool
| CNot (Condition c)
| COr (Condition c) (Condition c)
| CAnd (Condition c) (Condition c)
deriving (Show, Eq, Typeable, Data, Generic)
cNot :: Condition a -> Condition a
cNot (Lit b) = Lit (not b)
cNot (CNot c) = c
cNot c = CNot c
| Boolean AND of two ' Condtion ' values .
cAnd :: Condition a -> Condition a -> Condition a
cAnd (Lit False) _ = Lit False
cAnd _ (Lit False) = Lit False
cAnd (Lit True) x = x
cAnd x (Lit True) = x
cAnd x y = CAnd x y
| Boolean OR of two ' Condition ' values .
cOr :: Eq v => Condition v -> Condition v -> Condition v
cOr (Lit True) _ = Lit True
cOr _ (Lit True) = Lit True
cOr (Lit False) x = x
cOr x (Lit False) = x
cOr c (CNot d)
| c == d = Lit True
cOr (CNot c) d
| c == d = Lit True
cOr x y = COr x y
instance Functor Condition where
f `fmap` Var c = Var (f c)
_ `fmap` Lit c = Lit c
f `fmap` CNot c = CNot (fmap f c)
f `fmap` COr c d = COr (fmap f c) (fmap f d)
f `fmap` CAnd c d = CAnd (fmap f c) (fmap f d)
instance Foldable Condition where
f `foldMap` Var c = f c
_ `foldMap` Lit _ = mempty
f `foldMap` CNot c = foldMap f c
f `foldMap` COr c d = foldMap f c `mappend` foldMap f d
f `foldMap` CAnd c d = foldMap f c `mappend` foldMap f d
instance Traversable Condition where
f `traverse` Var c = Var `fmap` f c
_ `traverse` Lit c = pure $ Lit c
f `traverse` CNot c = CNot `fmap` traverse f c
f `traverse` COr c d = COr `fmap` traverse f c <*> traverse f d
f `traverse` CAnd c d = CAnd `fmap` traverse f c <*> traverse f d
instance Applicative Condition where
pure = Var
(<*>) = ap
instance Monad Condition where
return = pure
(>>=) (Lit x) _ = Lit x
(>>=) (Var x) f = f x
(>>=) (CNot x ) f = CNot (x >>= f)
(>>=) (COr x y) f = COr (x >>= f) (y >>= f)
(>>=) (CAnd x y) f = CAnd (x >>= f) (y >>= f)
instance Monoid (Condition a) where
mempty = Lit False
mappend = (<>)
instance Semigroup (Condition a) where
(<>) = COr
instance Alternative Condition where
empty = mempty
(<|>) = mappend
instance MonadPlus Condition where
mzero = mempty
mplus = mappend
instance Binary c => Binary (Condition c)
instance Structured c => Structured (Condition c)
instance NFData c => NFData (Condition c) where rnf = genericRnf
simplifyCondition :: Condition c
-> (Condition d, [d])
simplifyCondition cond i = fv . walk $ cond
where
walk cnd = case cnd of
Var v -> either Var Lit (i v)
Lit b -> Lit b
CNot c -> case walk c of
Lit True -> Lit False
Lit False -> Lit True
c' -> CNot c'
COr c d -> case (walk c, walk d) of
(Lit False, d') -> d'
(Lit True, _) -> Lit True
(c', Lit False) -> c'
(_, Lit True) -> Lit True
(c',d') -> COr c' d'
CAnd c d -> case (walk c, walk d) of
(Lit False, _) -> Lit False
(Lit True, d') -> d'
(_, Lit False) -> Lit False
(c', Lit True) -> c'
(c',d') -> CAnd c' d'
fv c = (c, fv' c)
fv' c = case c of
Var v -> [v]
Lit _ -> []
CNot c' -> fv' c'
COr c1 c2 -> fv' c1 ++ fv' c2
CAnd c1 c2 -> fv' c1 ++ fv' c2
|
f667f822bab78d93f4ae442b8c84c05034e24fd58553e6a381a088ea10b2bb28
|
s312569/clj-biosequence
|
protocols.clj
|
(in-ns 'clj-biosequence.core)
(def return-nil (fn [_] nil))
(defprotocol fastaReduce
(fasta-reduce [this func fold]
"Applies a function to sequence data streamed line-by-line and
reduces the results using the supplied `fold` function. Uses the
core reducers library so the fold function needs to have an
'identity' value that is returned when the function is called with
no arguments."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; readers and files
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol biosequenceIO
(bs-reader [this]
"Returns a reader for a file containing biosequences. Use with
`with-open'"))
(defprotocol biosequenceParameters
(parameters [this]
"Returns parameters from a reader."))
(defprotocol biosequenceReader
(biosequence-seq [this]
"Returns a lazy sequence of biosequence objects.")
(get-biosequence [this accession]
"Returns the biosequence object with the corresponding
accession."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; annotations
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol biosequenceGoTerms
(gos [this]
"Returns go term records."))
(def ^{:doc "Default implementation of biosequenceGoTerms protocol."}
default-biosequence-goterms
{:gos return-nil})
(defprotocol biosequenceGoTerm
(go-id [this]
"The GO id.")
(go-term [this]
"The GO term.")
(go-component [this]
"The GO component, molecular function etc."))
(def ^{:doc "Default implementation of biosequenceGoTerm protocol."}
default-biosequence-goterm
{:go-id return-nil
:go-term return-nil
:go-component return-nil})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; others
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol biosequenceDbRefs
(get-db-refs [this]
"Returns db ref records."))
(def ^{:doc "Default implementation of biosequenceDbRefs protocol."}
default-biosequence-dbrefs
{:get-db-refs return-nil})
(defprotocol biosequenceDbRef
(database-name [this]
"Returns the name of the database.")
(object-id [this]
"Returns the ID of an database object.")
(db-properties [this]
"Returns properties of the reference."))
(def ^{:doc "Default implementation of biosequenceDbRef protocol."}
default-biosequence-dbref
{:database-name return-nil
:object-id return-nil
:db-properties return-nil})
(defprotocol biosequenceNotes
(notes [this]
"Returns notes."))
(def ^{:doc "Default implementation of biosequenceNotes protocol."}
default-biosequence-notes
{:notes return-nil})
(defprotocol biosequenceUrl
(url [this]
"Returns the url.")
(pre-text [this]
"Text before anchor.")
(anchor [this]
"Text to show as highlight")
(post-text [this]
"Text after anchor"))
(def ^{:doc "Default implementation of biosequenceUrl protocol."}
default-biosequence-url
{:url return-nil
:pre-text return-nil
:anchor return-nil
:post-text return-nil})
(defprotocol biosequenceDescription
(description [this]
"Returns the description of a biosequence object."))
(def ^{:doc "Default implementation of biosequenceDescription protocol."}
default-biosequence-description
{:description return-nil})
(defprotocol biosequenceSynonyms
(synonyms [this]
"Returns a list of synonyms."))
(def ^{:doc "Default implementation of biosequenceSynonyms protocol."}
default-biosequence-synonyms
{:synonyms return-nil})
(defprotocol biosequenceStatus
(status [this]
"Status of an object."))
(def ^{:doc "Default implementation of biosequenceStatus protocol."}
default-biosequence-status
{:status return-nil})
(defprotocol biosequenceID
(accession [this]
"Returns the accession of a biosequence object.")
(accessions [this]
"Returns a list of accessions for a biosequence object.")
(dataset [this]
"Returns the dataset.")
(version [this]
"Returns the version of the accession nil if none.")
(creation-date [this]
"Returns a java date object.")
(update-date [this]
"Returns a java date object.")
(discontinue-date [this]
"Returns a date object."))
(def ^{:doc "Default implementation of biosequenceID protocol."}
default-biosequence-id
{:accession return-nil
:accessions return-nil
:dataset return-nil
:version return-nil
:creation-date return-nil
:update-date return-nil
:discontinue-date return-nil})
(defprotocol biosequenceTaxonomies
(tax-refs [src]
"Returns taxonomy records."))
(def ^{:doc "Default implementation of biosequenceTaxonomies protocol."}
default-biosequence-taxonomies
{:tax-refs return-nil})
(defprotocol biosequenceTaxonomy
(tax-name [this]
"Returns the taxonomic name.")
(common-name [this]
"Returns the common name.")
(mods [this]
"Returns a list of modifications to taxonomy.")
(lineage [this]
"Returns a lineage string."))
(def ^{:doc "Default implementation of biosequenceTaxonomy protocol."}
default-biosequence-tax
{:tax-name (fn [_] nil)
:common-name (fn [_] nil)
:mods (fn [_] nil)
:lineage (fn [_] nil)})
(defprotocol biosequenceGenes
(genes [this]
"Returns sub-seq gene records."))
(def ^{:doc "Default implementation of biosequenceGenes protocol."}
default-biosequence-genes
{:genes return-nil})
(defprotocol biosequenceGene
(locus [this]
"Returns the gene locus.")
(map-location [this]
"Returns the map location.")
(locus-tag [this]
"Returns a locus tag.")
(products [this]
"The products of a gene.")
(orf [this]
"ORF associated with the gene."))
(def ^{:doc "Default implementation of biosequenceGene protocol."}
default-biosequence-gene
{:locus return-nil
:orf return-nil
:map-location return-nil
:locus-tag return-nil
:products return-nil})
(defprotocol biosequenceSummary
(summary [this]
"Returns the summary of a sequence."))
(def ^{:doc "Default implementation of biosequenceSummary protocol."}
default-biosequence-summary
{:summary return-nil})
(defprotocol biosequenceVariant
(original [this]
"Returns the original.")
(variant [this]
"Returns the variant."))
(def ^{:doc "Default implementation of biosequenceVariant protocol."}
default-biosequence-variant
{:original return-nil
:variant return-nil})
(defprotocol biosequenceEvidence
(evidence [this]
"Returns evidence records."))
(def default-biosequence-evidence
^{:doc "Default implementation of biosequenceEvidence protocol."}
{:evidence return-nil})
(defprotocol biosequenceProteins
(proteins [this]
"Returns protein sub-seq records."))
(def ^{:doc "Default implementation of biosequenceProteins protocol."}
default-biosequence-proteins
{:proteins return-nil})
(defprotocol biosequenceProtein
(ecs [this]
"Returns list of E.C numbers.")
(activities [this]
"Returns a lit of activities.")
(processed [this]
"Processing of the protein.")
(calc-mol-wt [this]
"The calculated molecular weight."))
(def ^{:doc "Default implementation of biosequenceProtein protocol."}
default-biosequence-protein
{:ec return-nil
:protein-ids return-nil
:activities return-nil
:processed return-nil})
(defprotocol biosequenceNameObject
(obj-name [this])
(obj-id [this])
(obj-description [this])
(obj-type [this])
(obj-value [this])
(obj-label [this])
(obj-heading [this])
(obj-text [this]))
(def ^{:doc "Default implementation of biosequenceNameObject protocol."}
default-biosequence-nameobject
{:obj-name return-nil
:obj-id return-nil
:obj-description return-nil
:obj-type return-nil
:obj-value return-nil
:obj-label return-nil
:obj-heading return-nil
:obj-text return-nil})
(defprotocol biosequenceComments
(comments [this]
"Returns comments.")
(filter-comments [this value]
"Filters comments based on the return value of obj-type."))
(def ^{:doc "Default implementation of biosequenceComments protocol."}
default-biosequence-comments
{:comments return-nil
:filter-comments (fn [this value]
(filter #(= value (obj-type %))
(comments this)))})
(defprotocol biosequenceName
(names [this]
"Returns the default names of a record.")
(alternate-names [this]
"Returns the alternate names.")
(allergen-names [this]
"Returns the allergen names.")
(submitted-names [this]
"Returns the submitted names.")
(biotech-names [this]
"Returns the biotech names.")
(cd-antigen-names [this]
"Returns the cd names.")
(innnames [this]
"Returns the innname."))
(def ^{:doc "Default implementation of biosequenceName protocol."}
default-biosequence-name
{:names return-nil
:alternate-names return-nil
:submitted-names return-nil
:allergen-names return-nil
:biotech-names return-nil
:cd-antigen-names return-nil
:innnames return-nil})
(defprotocol Biosequence
(bs-seq [this]
"Returns the sequence of a biosequence as a vector.")
(protein? [this]
"Returns true if a protein and false otherwise.")
(alphabet [this]
"Returns the alphabet of a biosequence.")
(moltype [this]
"Returns the moltype of a biosequence.")
(keywords [this]
"Returns a collection of keywords."))
(def ^{:doc "Default implementation of Biosequence protocol."}
default-biosequence-biosequence
{:bs-seq return-nil
:protein? (fn [_] false)
:alphabet return-nil
:moltype return-nil
:keywords return-nil})
(defprotocol biosequenceCitations
(citations [this]
"Returns a collection of references in a sequence record.")
(citation-key [this]
"Returns a citation key from a record."))
(def ^{:doc "Default implementation of biosequenceCitations protocol."}
default-biosequence-citations
{:citations return-nil
:citation-key return-nil})
(defprotocol biosequenceCitation
(title [this]
"Returns the title of a citation object.")
(journal [this]
"Returns the journal of a citation object.")
(year [this]
"Returns the year of a citation object.")
(volume [this]
"Returns the volume of a citation object.")
(pstart [this]
"Returns the start page of a citation object.")
(pend [this]
"Returns the end page of a citation object.")
(authors [this]
"Returns the authors from a citation object.")
(pubmed [this]
"Returns the pubmed id of a reference if there is one.")
(crossrefs [this]
"Returns crossrefs - DOI, ISBN etc")
(abstract [this]
"Returns the abstract"))
(def ^{:doc "Default implementation of biosequenceCitation protocol."}
default-biosequence-citation
{:title return-nil
:journal return-nil
:year return-nil
:volume return-nil
:pstart return-nil
:pend return-nil
:authors return-nil
:pubmed return-nil
:crossrefs return-nil
:notes return-nil
:abstract return-nil})
(defprotocol biosequenceTranslation
(frame [this]
"Returns the frame a sequence should be translated in.")
(trans-table [this]
"Returns the translation table code to be used.")
(translation [this]
"Returns the translation of a sequence.")
(codon-start [this]
"The start codon."))
(def ^{:doc "Default implementation of biosequenceTranslation protocol."}
default-biosequence-translation
{:frame return-nil
:codon-start return-nil
:trans-table return-nil
:translation return-nil})
(defprotocol biosequenceFile
(bs-path [this]
"Returns the path of the file as string."))
(def ^{:doc "Default implementation of biosequenceFile protocol."}
default-biosequence-file
{:bs-path (fn [this] (absolute-path (:file this)))})
(defprotocol biosequenceFeatures
(feature-seq [this]
"Returns a lazy list of features in a sequence.")
(filter-features [this name]
"Returns a list of features that return 'name' when called using
bs/bs-name from biosequenceName protocol."))
(def ^{:doc "Default implementation of biosequenceFeatures protocol."}
default-biosequence-features
{:feature-seq return-nil
:filter-features return-nil})
(defprotocol biosequenceFeature
(operator [this]
"Returns an operator for dealing with intervals."))
(def ^{:doc "Default implementation of biosequenceFeature protocol."}
default-biosequence-feature
{:operator return-nil})
(defprotocol biosequenceIntervals
(intervals [this]
"Returns a list of intervals."))
(def ^{:doc "Default implementation of biosequenceIntervals protocol."}
default-biosequence-intervals
{:intervals return-nil})
(defprotocol biosequenceInterval
(start [this]
"Returns the start position of an interval as an integer.")
(end [this]
"Returns the end position of an interval as an integer.")
(point [this]
"Returns a point interval.")
(strand [this]
"Returns '+', '-', '.' or '?' for positive, minus, not stranded or
unknwon respectively.")
(comp? [this]
"Is the interval complementary to the biosequence
sequence. Boolean"))
(def ^{:doc "Default implementation of biosequenceInterval protocol."}
default-biosequence-interval
{:start return-nil
:end return-nil
:point return-nil
:comp? (fn [_]
(throw (Throwable. "No strand information.")))})
(defprotocol biosequenceSubCellLocs
(subcell-locations [this]))
(def ^{:doc "Default implementation of biosequenceSubCellLocs protocol."}
default-biosequence-subcells
{:subcell-locations return-nil})
(defprotocol biosequenceSubCellLoc
(subcell-location [this])
(subcell-topol [this])
(subcell-orient [this]))
(def
^{:doc "Default implementation of biosequenceSubCellLoc protocol."}
default-biosequence-subcell
{:subcell-location return-nil
:subcell-topol return-nil
:subcell-orient return-nil})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; nil
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend nil
biosequenceDbRefs default-biosequence-dbrefs
biosequenceDbRef default-biosequence-dbref
biosequenceComments default-biosequence-comments
biosequenceUrl default-biosequence-url
biosequenceDescription default-biosequence-description
biosequenceSynonyms default-biosequence-synonyms
biosequenceID default-biosequence-id
biosequenceTaxonomy default-biosequence-tax
biosequenceGenes default-biosequence-genes
biosequenceGene default-biosequence-gene
biosequenceSummary default-biosequence-summary
biosequenceProteins default-biosequence-proteins
biosequenceProtein default-biosequence-protein
Biosequence default-biosequence-biosequence
biosequenceCitations default-biosequence-citations
biosequenceCitation default-biosequence-citation
biosequenceTranslation default-biosequence-translation
biosequenceFeatures default-biosequence-features
biosequenceFeature default-biosequence-feature
biosequenceIntervals default-biosequence-interval
biosequenceInterval default-biosequence-interval
biosequenceName default-biosequence-name
biosequenceNotes default-biosequence-notes
biosequenceVariant default-biosequence-variant
biosequenceEvidence default-biosequence-evidence
biosequenceStatus default-biosequence-status
biosequenceTaxonomies default-biosequence-taxonomies
biosequenceNameObject default-biosequence-nameobject
biosequenceSubCellLocs default-biosequence-subcells
biosequenceSubCellLoc default-biosequence-subcell
biosequenceGoTerms default-biosequence-goterms
biosequenceGoTerm default-biosequence-goterm)
| null |
https://raw.githubusercontent.com/s312569/clj-biosequence/b4d2a2750d8fd6a2b398d859879c193e00212415/src/clj_biosequence/protocols.clj
|
clojure
|
readers and files
annotations
others
nil
|
(in-ns 'clj-biosequence.core)
(def return-nil (fn [_] nil))
(defprotocol fastaReduce
(fasta-reduce [this func fold]
"Applies a function to sequence data streamed line-by-line and
reduces the results using the supplied `fold` function. Uses the
core reducers library so the fold function needs to have an
'identity' value that is returned when the function is called with
no arguments."))
(defprotocol biosequenceIO
(bs-reader [this]
"Returns a reader for a file containing biosequences. Use with
`with-open'"))
(defprotocol biosequenceParameters
(parameters [this]
"Returns parameters from a reader."))
(defprotocol biosequenceReader
(biosequence-seq [this]
"Returns a lazy sequence of biosequence objects.")
(get-biosequence [this accession]
"Returns the biosequence object with the corresponding
accession."))
(defprotocol biosequenceGoTerms
(gos [this]
"Returns go term records."))
(def ^{:doc "Default implementation of biosequenceGoTerms protocol."}
default-biosequence-goterms
{:gos return-nil})
(defprotocol biosequenceGoTerm
(go-id [this]
"The GO id.")
(go-term [this]
"The GO term.")
(go-component [this]
"The GO component, molecular function etc."))
(def ^{:doc "Default implementation of biosequenceGoTerm protocol."}
default-biosequence-goterm
{:go-id return-nil
:go-term return-nil
:go-component return-nil})
(defprotocol biosequenceDbRefs
(get-db-refs [this]
"Returns db ref records."))
(def ^{:doc "Default implementation of biosequenceDbRefs protocol."}
default-biosequence-dbrefs
{:get-db-refs return-nil})
(defprotocol biosequenceDbRef
(database-name [this]
"Returns the name of the database.")
(object-id [this]
"Returns the ID of an database object.")
(db-properties [this]
"Returns properties of the reference."))
(def ^{:doc "Default implementation of biosequenceDbRef protocol."}
default-biosequence-dbref
{:database-name return-nil
:object-id return-nil
:db-properties return-nil})
(defprotocol biosequenceNotes
(notes [this]
"Returns notes."))
(def ^{:doc "Default implementation of biosequenceNotes protocol."}
default-biosequence-notes
{:notes return-nil})
(defprotocol biosequenceUrl
(url [this]
"Returns the url.")
(pre-text [this]
"Text before anchor.")
(anchor [this]
"Text to show as highlight")
(post-text [this]
"Text after anchor"))
(def ^{:doc "Default implementation of biosequenceUrl protocol."}
default-biosequence-url
{:url return-nil
:pre-text return-nil
:anchor return-nil
:post-text return-nil})
(defprotocol biosequenceDescription
(description [this]
"Returns the description of a biosequence object."))
(def ^{:doc "Default implementation of biosequenceDescription protocol."}
default-biosequence-description
{:description return-nil})
(defprotocol biosequenceSynonyms
(synonyms [this]
"Returns a list of synonyms."))
(def ^{:doc "Default implementation of biosequenceSynonyms protocol."}
default-biosequence-synonyms
{:synonyms return-nil})
(defprotocol biosequenceStatus
(status [this]
"Status of an object."))
(def ^{:doc "Default implementation of biosequenceStatus protocol."}
default-biosequence-status
{:status return-nil})
(defprotocol biosequenceID
(accession [this]
"Returns the accession of a biosequence object.")
(accessions [this]
"Returns a list of accessions for a biosequence object.")
(dataset [this]
"Returns the dataset.")
(version [this]
"Returns the version of the accession nil if none.")
(creation-date [this]
"Returns a java date object.")
(update-date [this]
"Returns a java date object.")
(discontinue-date [this]
"Returns a date object."))
(def ^{:doc "Default implementation of biosequenceID protocol."}
default-biosequence-id
{:accession return-nil
:accessions return-nil
:dataset return-nil
:version return-nil
:creation-date return-nil
:update-date return-nil
:discontinue-date return-nil})
(defprotocol biosequenceTaxonomies
(tax-refs [src]
"Returns taxonomy records."))
(def ^{:doc "Default implementation of biosequenceTaxonomies protocol."}
default-biosequence-taxonomies
{:tax-refs return-nil})
(defprotocol biosequenceTaxonomy
(tax-name [this]
"Returns the taxonomic name.")
(common-name [this]
"Returns the common name.")
(mods [this]
"Returns a list of modifications to taxonomy.")
(lineage [this]
"Returns a lineage string."))
(def ^{:doc "Default implementation of biosequenceTaxonomy protocol."}
default-biosequence-tax
{:tax-name (fn [_] nil)
:common-name (fn [_] nil)
:mods (fn [_] nil)
:lineage (fn [_] nil)})
(defprotocol biosequenceGenes
(genes [this]
"Returns sub-seq gene records."))
(def ^{:doc "Default implementation of biosequenceGenes protocol."}
default-biosequence-genes
{:genes return-nil})
(defprotocol biosequenceGene
(locus [this]
"Returns the gene locus.")
(map-location [this]
"Returns the map location.")
(locus-tag [this]
"Returns a locus tag.")
(products [this]
"The products of a gene.")
(orf [this]
"ORF associated with the gene."))
(def ^{:doc "Default implementation of biosequenceGene protocol."}
default-biosequence-gene
{:locus return-nil
:orf return-nil
:map-location return-nil
:locus-tag return-nil
:products return-nil})
(defprotocol biosequenceSummary
(summary [this]
"Returns the summary of a sequence."))
(def ^{:doc "Default implementation of biosequenceSummary protocol."}
default-biosequence-summary
{:summary return-nil})
(defprotocol biosequenceVariant
(original [this]
"Returns the original.")
(variant [this]
"Returns the variant."))
(def ^{:doc "Default implementation of biosequenceVariant protocol."}
default-biosequence-variant
{:original return-nil
:variant return-nil})
(defprotocol biosequenceEvidence
(evidence [this]
"Returns evidence records."))
(def default-biosequence-evidence
^{:doc "Default implementation of biosequenceEvidence protocol."}
{:evidence return-nil})
(defprotocol biosequenceProteins
(proteins [this]
"Returns protein sub-seq records."))
(def ^{:doc "Default implementation of biosequenceProteins protocol."}
default-biosequence-proteins
{:proteins return-nil})
(defprotocol biosequenceProtein
(ecs [this]
"Returns list of E.C numbers.")
(activities [this]
"Returns a lit of activities.")
(processed [this]
"Processing of the protein.")
(calc-mol-wt [this]
"The calculated molecular weight."))
(def ^{:doc "Default implementation of biosequenceProtein protocol."}
default-biosequence-protein
{:ec return-nil
:protein-ids return-nil
:activities return-nil
:processed return-nil})
(defprotocol biosequenceNameObject
(obj-name [this])
(obj-id [this])
(obj-description [this])
(obj-type [this])
(obj-value [this])
(obj-label [this])
(obj-heading [this])
(obj-text [this]))
(def ^{:doc "Default implementation of biosequenceNameObject protocol."}
default-biosequence-nameobject
{:obj-name return-nil
:obj-id return-nil
:obj-description return-nil
:obj-type return-nil
:obj-value return-nil
:obj-label return-nil
:obj-heading return-nil
:obj-text return-nil})
(defprotocol biosequenceComments
(comments [this]
"Returns comments.")
(filter-comments [this value]
"Filters comments based on the return value of obj-type."))
(def ^{:doc "Default implementation of biosequenceComments protocol."}
default-biosequence-comments
{:comments return-nil
:filter-comments (fn [this value]
(filter #(= value (obj-type %))
(comments this)))})
(defprotocol biosequenceName
(names [this]
"Returns the default names of a record.")
(alternate-names [this]
"Returns the alternate names.")
(allergen-names [this]
"Returns the allergen names.")
(submitted-names [this]
"Returns the submitted names.")
(biotech-names [this]
"Returns the biotech names.")
(cd-antigen-names [this]
"Returns the cd names.")
(innnames [this]
"Returns the innname."))
(def ^{:doc "Default implementation of biosequenceName protocol."}
default-biosequence-name
{:names return-nil
:alternate-names return-nil
:submitted-names return-nil
:allergen-names return-nil
:biotech-names return-nil
:cd-antigen-names return-nil
:innnames return-nil})
(defprotocol Biosequence
(bs-seq [this]
"Returns the sequence of a biosequence as a vector.")
(protein? [this]
"Returns true if a protein and false otherwise.")
(alphabet [this]
"Returns the alphabet of a biosequence.")
(moltype [this]
"Returns the moltype of a biosequence.")
(keywords [this]
"Returns a collection of keywords."))
(def ^{:doc "Default implementation of Biosequence protocol."}
default-biosequence-biosequence
{:bs-seq return-nil
:protein? (fn [_] false)
:alphabet return-nil
:moltype return-nil
:keywords return-nil})
(defprotocol biosequenceCitations
(citations [this]
"Returns a collection of references in a sequence record.")
(citation-key [this]
"Returns a citation key from a record."))
(def ^{:doc "Default implementation of biosequenceCitations protocol."}
default-biosequence-citations
{:citations return-nil
:citation-key return-nil})
(defprotocol biosequenceCitation
(title [this]
"Returns the title of a citation object.")
(journal [this]
"Returns the journal of a citation object.")
(year [this]
"Returns the year of a citation object.")
(volume [this]
"Returns the volume of a citation object.")
(pstart [this]
"Returns the start page of a citation object.")
(pend [this]
"Returns the end page of a citation object.")
(authors [this]
"Returns the authors from a citation object.")
(pubmed [this]
"Returns the pubmed id of a reference if there is one.")
(crossrefs [this]
"Returns crossrefs - DOI, ISBN etc")
(abstract [this]
"Returns the abstract"))
(def ^{:doc "Default implementation of biosequenceCitation protocol."}
default-biosequence-citation
{:title return-nil
:journal return-nil
:year return-nil
:volume return-nil
:pstart return-nil
:pend return-nil
:authors return-nil
:pubmed return-nil
:crossrefs return-nil
:notes return-nil
:abstract return-nil})
(defprotocol biosequenceTranslation
(frame [this]
"Returns the frame a sequence should be translated in.")
(trans-table [this]
"Returns the translation table code to be used.")
(translation [this]
"Returns the translation of a sequence.")
(codon-start [this]
"The start codon."))
(def ^{:doc "Default implementation of biosequenceTranslation protocol."}
default-biosequence-translation
{:frame return-nil
:codon-start return-nil
:trans-table return-nil
:translation return-nil})
(defprotocol biosequenceFile
(bs-path [this]
"Returns the path of the file as string."))
(def ^{:doc "Default implementation of biosequenceFile protocol."}
default-biosequence-file
{:bs-path (fn [this] (absolute-path (:file this)))})
(defprotocol biosequenceFeatures
(feature-seq [this]
"Returns a lazy list of features in a sequence.")
(filter-features [this name]
"Returns a list of features that return 'name' when called using
bs/bs-name from biosequenceName protocol."))
(def ^{:doc "Default implementation of biosequenceFeatures protocol."}
default-biosequence-features
{:feature-seq return-nil
:filter-features return-nil})
(defprotocol biosequenceFeature
(operator [this]
"Returns an operator for dealing with intervals."))
(def ^{:doc "Default implementation of biosequenceFeature protocol."}
default-biosequence-feature
{:operator return-nil})
(defprotocol biosequenceIntervals
(intervals [this]
"Returns a list of intervals."))
(def ^{:doc "Default implementation of biosequenceIntervals protocol."}
default-biosequence-intervals
{:intervals return-nil})
(defprotocol biosequenceInterval
(start [this]
"Returns the start position of an interval as an integer.")
(end [this]
"Returns the end position of an interval as an integer.")
(point [this]
"Returns a point interval.")
(strand [this]
"Returns '+', '-', '.' or '?' for positive, minus, not stranded or
unknwon respectively.")
(comp? [this]
"Is the interval complementary to the biosequence
sequence. Boolean"))
(def ^{:doc "Default implementation of biosequenceInterval protocol."}
default-biosequence-interval
{:start return-nil
:end return-nil
:point return-nil
:comp? (fn [_]
(throw (Throwable. "No strand information.")))})
(defprotocol biosequenceSubCellLocs
(subcell-locations [this]))
(def ^{:doc "Default implementation of biosequenceSubCellLocs protocol."}
default-biosequence-subcells
{:subcell-locations return-nil})
(defprotocol biosequenceSubCellLoc
(subcell-location [this])
(subcell-topol [this])
(subcell-orient [this]))
(def
^{:doc "Default implementation of biosequenceSubCellLoc protocol."}
default-biosequence-subcell
{:subcell-location return-nil
:subcell-topol return-nil
:subcell-orient return-nil})
(extend nil
biosequenceDbRefs default-biosequence-dbrefs
biosequenceDbRef default-biosequence-dbref
biosequenceComments default-biosequence-comments
biosequenceUrl default-biosequence-url
biosequenceDescription default-biosequence-description
biosequenceSynonyms default-biosequence-synonyms
biosequenceID default-biosequence-id
biosequenceTaxonomy default-biosequence-tax
biosequenceGenes default-biosequence-genes
biosequenceGene default-biosequence-gene
biosequenceSummary default-biosequence-summary
biosequenceProteins default-biosequence-proteins
biosequenceProtein default-biosequence-protein
Biosequence default-biosequence-biosequence
biosequenceCitations default-biosequence-citations
biosequenceCitation default-biosequence-citation
biosequenceTranslation default-biosequence-translation
biosequenceFeatures default-biosequence-features
biosequenceFeature default-biosequence-feature
biosequenceIntervals default-biosequence-interval
biosequenceInterval default-biosequence-interval
biosequenceName default-biosequence-name
biosequenceNotes default-biosequence-notes
biosequenceVariant default-biosequence-variant
biosequenceEvidence default-biosequence-evidence
biosequenceStatus default-biosequence-status
biosequenceTaxonomies default-biosequence-taxonomies
biosequenceNameObject default-biosequence-nameobject
biosequenceSubCellLocs default-biosequence-subcells
biosequenceSubCellLoc default-biosequence-subcell
biosequenceGoTerms default-biosequence-goterms
biosequenceGoTerm default-biosequence-goterm)
|
2070f4c3d238da4ce357d33c1a7e7fd73f72487dcc6877b93af3178c8bd88ddc
|
ftovagliari/ocamleditor
|
oebuild_tool.ml
|
OCamlEditor
Copyright ( C ) 2010 - 2014
This file is part of OCamlEditor .
OCamlEditor 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 .
OCamlEditor 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 < / > .
OCamlEditor
Copyright (C) 2010-2014 Francesco Tovagliari
This file is part of OCamlEditor.
OCamlEditor 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.
OCamlEditor 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 </>.
*)
open Printf
open Arg
open Oebuild
(** main *)
let main () =
let enabled = ref true in
let nodep = ref false in
let dontlinkdep = ref false in
let dontaddopt = ref false in
let toplevel_modules = ref [] in
let outkind = ref Executable in
let is_clean = ref false in
let is_distclean = ref false in
let compilation = ref [] in
let prof = ref false in
let package = ref "" in
let includes = ref "" in
let cflags = ref "" in
let lflags = ref "" in
let libs = ref "" in
let mods = ref "" in
let install_flag = ref None in
let compile_only = ref false in
let annot = ref false in
let bin_annot = ref false in
let pp = ref "" in
let inline : int option ref = ref None in
let output_name = ref "" in
let run_code = ref None in
let run_args = ref [] in
let ms_paths = ref false in
let print_output_name = ref false in
let thread = ref false in
let vmthread = ref false in
let no_build = ref false in
let jobs = ref 0 in
let serial = ref false in
let verbose = ref 2 in
let add_target x = toplevel_modules := x :: !toplevel_modules in
let add_compilation x () = compilation := x :: !compilation in
let set_run_args x = run_args := x :: !run_args in
let set_run_code x () = run_code := Some x in
let set_install x = install_flag := Some x in
let dep () =
try
let deps =
Oebuild_dep.ocamldep_toplevels ~pp:!pp ~ignore_stderr:false !toplevel_modules
|> Oebuild_dep.sort_dependencies
in
printf "%s\n%!" (String.concat " " deps);
exit 0;
with Oebuild_dep.Loop_found msg -> begin
printf "%s\n%!" msg;
exit 0;
end
in
let check_restrictions restr =
let restr = Str.split (Str.regexp " *& *") restr in
enabled := check_restrictions restr
in
let speclist = Arg.align [
("-byt", Unit (add_compilation Bytecode), " Bytecode compilation (default).");
("-opt", Unit (add_compilation Native), " Native-code compilation.");
("-c", Set compile_only, " Compile only.");
("-a", Unit (fun _ -> outkind := Library), " Build a library. ");
("-shared", Unit (fun _ -> outkind := Plugin), " Build a plugin. ");
("-pack", Unit (fun _ -> outkind := Pack), " Pack object files.");
("-package", Set_string package, "\"<package-name-list>\" Option passed to ocamlfind.");
("-I", Set_string includes, "\"<paths>\" Search paths, separated by spaces.");
("-l", Set_string libs, "\"<libs>\" Libraries, separated by spaces (e.g. -l \"unix str\").
When the library name ends with \".o\" is interpreted
as compiled object file, not as library.");
("-m", Set_string mods, "\"<objects>\" Other required object files.");
("-cflags", Set_string cflags, "\"<flags>\" Flags passed to the compiler.");
("-lflags", Set_string lflags, "\"<flags>\" Flags passed to the linker.");
("-thread", Set thread, " Add -thread option to both cflags and lflags.");
("-vmthread", Set vmthread, " Add -vmthread option to both cflags and lflags.");
("-annot", Set annot, " Add -annot option to cflags.");
("-bin-annot", Set bin_annot, " Add -bin-annot option to cflags.");
("-pp", Set_string pp, "\"<command>\" Add -pp option to the compiler.");
("-inline", Int (fun x -> inline := Some x), "<n> Add -inline option to the compiler.");
("-o", Set_string output_name, "\"<filename>\" Output file name. Extension {.cm[x]a | [.opt][.exe]}
is automatically added to the resulting filename according
to the -a and -opt options and the type of O.S.");
("-dont-add-opt", Set dontaddopt, " Do not add \".opt\" to the native executable file name.");
("-run", Unit (set_run_code Unspecified), " Run the resulting executable (native-code takes precedence) giving
each argument after \"--\" on the command line
(\"-run --\" for no arguments).");
("-run-byt", Unit (set_run_code Bytecode), " Run the resulting bytecode executable.");
("-run-opt", Unit (set_run_code Native), " Run the resulting native-code executable.");
("--", Rest set_run_args, "<run-args> Command line arguments for the -run, -run-byt or -run-opt options.");
("-clean", Set is_clean, " Remove output files for the selected target and exit.");
("-dep", Unit dep, " Print dependencies and exit.");
("-no-dep", Set nodep, " Do not detect module dependencies.");
("-dont-link-dep", Set dontlinkdep, " Do not link module dependencies.");
("-when", String check_restrictions, "\"<c1&c2&...>\" Exit immediately if any condition specified here is not true.
Recognized conditions are:
FINDLIB(packages,...) : Findlib packages are installed
IS_UNIX : O.S. type is Unix
IS_WIN32 : O.S. type is Win32
IS_CYGWIN : O.S. type is Cygwin
ENV(name[{=|<>}value]) : Check environment variable
OCAML(name[{=|<>}value]) : Check OCaml configuration property
NATIVE : Native compilation is supported\n");
("-output-name", Set print_output_name, " (undocumented)");
("-msvc", Set ms_paths, " (undocumented)");
("-no-build", Set no_build, " (undocumented)");
("-install", String set_install, " (undocumented)");
("-prof", Set prof, " (undocumented)");
("-distclean", Set is_distclean, " (undocumented)");
("-jobs", Set_int jobs, " (undocumented)");
("-serial", Set serial, " (undocumented)");
("-verbose", Set_int verbose, " (undocumented)");
(* ("-cs", Set compile_separately, " Compile separately without recompiling unmodified modules.");*)
( " -install " , Set_string install , " " Copy the output to the specified directory . When building libraries the path is relative to " ^
( win32 " % OCAMLLIB% " " $ OCAMLLIB " ) ^ " . Create all non - existing directories . " ) ;
(win32 "%OCAMLLIB%" "$OCAMLLIB") ^ ". Create all non-existing directories.");*)
] in
let command_name = Filename.basename Sys.argv.(0) in
let help_message = sprintf "\nUsage:\n %s target.ml... [options]\n\nOptions:" command_name in
Arg.parse speclist add_target help_message;
let main' () =
toplevel_modules := List.rev !toplevel_modules;
if List.length !toplevel_modules = 0 then begin
Arg.usage speclist help_message;
exit 0;
end;
if not !enabled then (exit 0);
(* Compilation mode *)
let compilation = if !compilation = [] then [Bytecode] else !compilation in
let compilation = List.sort Stdlib.compare compilation in
(* print_output_name *)
if !print_output_name then begin
List.iter begin fun compilation ->
let outname = get_output_name ~compilation ~outkind:!outkind ~outname:!output_name ~dontaddopt:!dontaddopt () in
printf "%s\n%!" outname
end compilation;
exit 0;
end;
(* Clean *)
if !is_clean || !is_distclean then begin
let = Oebuild_util.crono ~label:"Oebuild_dep.find " ( ~ignore_stderr : false ) ! toplevel_modules in
let deps =
Oebuild_dep.ocamldep_toplevels ~verbose:false ~pp:!pp ~ignore_stderr:false !toplevel_modules
|> Oebuild_dep.sort_dependencies
in
if !is_clean then (clean ~deps ());
if !is_distclean then (distclean ());
end else begin
(* Build, install and run *)
let last_outname = ref None in
let outnames =
List.map begin fun compilation ->
let outname = get_output_name ~compilation ~outkind:!outkind ~outname:!output_name ~dontaddopt:!dontaddopt () in
match
if !no_build then Built_successfully, []
else begin
let deps =
if !nodep then !toplevel_modules
else if !serial
then Miscellanea.crono ~label:"Oebuild_dep.find" (fun () -> Oebuild_dep.find ~pp:!pp ~ignore_stderr:false !toplevel_modules) ()
else []
in
(build
~compilation
~package:!package
~includes:!includes
~libs:!libs
~other_mods:!mods
~outkind:!outkind
~compile_only:!compile_only
~thread:!thread
~vmthread:!vmthread
~annot:!annot
~bin_annot:!bin_annot
~pp:!pp
?inline:!inline
~cflags:!cflags
~lflags:!lflags
~outname
~deps
~dontlinkdep:!dontlinkdep
~dontaddopt:!dontaddopt
~toplevel_modules:!toplevel_modules
~prof:!prof
~jobs:!jobs
~serial:!serial
~verbose:!verbose
()), deps
end
with
| Build_failed code, _ -> exit code (*(compilation, None)*)
| Built_successfully, deps ->
begin
match !install_flag with
| Some _ when not ! serial - > failwith " -install is accepted only with -serial "
| Some path ->
serial := true;
install ~compilation ~outname ~outkind:!outkind ~deps ~path
~ccomp_type:(Ocaml_config.can_compile_native ());
| _ -> ()
end;
last_outname := Some outname;
(compilation, Some outname)
end compilation;
in
if !outkind = Executable then begin
try
begin
match !run_code with
| Some Native ->
(match List.assoc Native outnames with None -> ()
| Some outname -> run_output ~outname ~args:!run_args)
| Some Bytecode ->
(match List.assoc Bytecode outnames with None -> ()
| Some outname -> run_output ~outname ~args:!run_args)
| Some Unspecified ->
(match !last_outname with None -> ()
| Some outname -> run_output ~outname ~args:!run_args)
| None -> ()
end
with Not_found -> (invalid_arg "-run-opt or -run-byt")
end;
end
in
if !verbose >= 3 then Oebuild_util.crono ~label:"Build time" main' () else main' ()
let _ = main ()
| null |
https://raw.githubusercontent.com/ftovagliari/ocamleditor/53284253cf7603b96051e7425e85a731f09abcd1/src/oebuild/oebuild_tool.ml
|
ocaml
|
* main
("-cs", Set compile_separately, " Compile separately without recompiling unmodified modules.");
Compilation mode
print_output_name
Clean
Build, install and run
(compilation, None)
|
OCamlEditor
Copyright ( C ) 2010 - 2014
This file is part of OCamlEditor .
OCamlEditor 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 .
OCamlEditor 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 < / > .
OCamlEditor
Copyright (C) 2010-2014 Francesco Tovagliari
This file is part of OCamlEditor.
OCamlEditor 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.
OCamlEditor 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 </>.
*)
open Printf
open Arg
open Oebuild
let main () =
let enabled = ref true in
let nodep = ref false in
let dontlinkdep = ref false in
let dontaddopt = ref false in
let toplevel_modules = ref [] in
let outkind = ref Executable in
let is_clean = ref false in
let is_distclean = ref false in
let compilation = ref [] in
let prof = ref false in
let package = ref "" in
let includes = ref "" in
let cflags = ref "" in
let lflags = ref "" in
let libs = ref "" in
let mods = ref "" in
let install_flag = ref None in
let compile_only = ref false in
let annot = ref false in
let bin_annot = ref false in
let pp = ref "" in
let inline : int option ref = ref None in
let output_name = ref "" in
let run_code = ref None in
let run_args = ref [] in
let ms_paths = ref false in
let print_output_name = ref false in
let thread = ref false in
let vmthread = ref false in
let no_build = ref false in
let jobs = ref 0 in
let serial = ref false in
let verbose = ref 2 in
let add_target x = toplevel_modules := x :: !toplevel_modules in
let add_compilation x () = compilation := x :: !compilation in
let set_run_args x = run_args := x :: !run_args in
let set_run_code x () = run_code := Some x in
let set_install x = install_flag := Some x in
let dep () =
try
let deps =
Oebuild_dep.ocamldep_toplevels ~pp:!pp ~ignore_stderr:false !toplevel_modules
|> Oebuild_dep.sort_dependencies
in
printf "%s\n%!" (String.concat " " deps);
exit 0;
with Oebuild_dep.Loop_found msg -> begin
printf "%s\n%!" msg;
exit 0;
end
in
let check_restrictions restr =
let restr = Str.split (Str.regexp " *& *") restr in
enabled := check_restrictions restr
in
let speclist = Arg.align [
("-byt", Unit (add_compilation Bytecode), " Bytecode compilation (default).");
("-opt", Unit (add_compilation Native), " Native-code compilation.");
("-c", Set compile_only, " Compile only.");
("-a", Unit (fun _ -> outkind := Library), " Build a library. ");
("-shared", Unit (fun _ -> outkind := Plugin), " Build a plugin. ");
("-pack", Unit (fun _ -> outkind := Pack), " Pack object files.");
("-package", Set_string package, "\"<package-name-list>\" Option passed to ocamlfind.");
("-I", Set_string includes, "\"<paths>\" Search paths, separated by spaces.");
("-l", Set_string libs, "\"<libs>\" Libraries, separated by spaces (e.g. -l \"unix str\").
When the library name ends with \".o\" is interpreted
as compiled object file, not as library.");
("-m", Set_string mods, "\"<objects>\" Other required object files.");
("-cflags", Set_string cflags, "\"<flags>\" Flags passed to the compiler.");
("-lflags", Set_string lflags, "\"<flags>\" Flags passed to the linker.");
("-thread", Set thread, " Add -thread option to both cflags and lflags.");
("-vmthread", Set vmthread, " Add -vmthread option to both cflags and lflags.");
("-annot", Set annot, " Add -annot option to cflags.");
("-bin-annot", Set bin_annot, " Add -bin-annot option to cflags.");
("-pp", Set_string pp, "\"<command>\" Add -pp option to the compiler.");
("-inline", Int (fun x -> inline := Some x), "<n> Add -inline option to the compiler.");
("-o", Set_string output_name, "\"<filename>\" Output file name. Extension {.cm[x]a | [.opt][.exe]}
is automatically added to the resulting filename according
to the -a and -opt options and the type of O.S.");
("-dont-add-opt", Set dontaddopt, " Do not add \".opt\" to the native executable file name.");
("-run", Unit (set_run_code Unspecified), " Run the resulting executable (native-code takes precedence) giving
each argument after \"--\" on the command line
(\"-run --\" for no arguments).");
("-run-byt", Unit (set_run_code Bytecode), " Run the resulting bytecode executable.");
("-run-opt", Unit (set_run_code Native), " Run the resulting native-code executable.");
("--", Rest set_run_args, "<run-args> Command line arguments for the -run, -run-byt or -run-opt options.");
("-clean", Set is_clean, " Remove output files for the selected target and exit.");
("-dep", Unit dep, " Print dependencies and exit.");
("-no-dep", Set nodep, " Do not detect module dependencies.");
("-dont-link-dep", Set dontlinkdep, " Do not link module dependencies.");
("-when", String check_restrictions, "\"<c1&c2&...>\" Exit immediately if any condition specified here is not true.
Recognized conditions are:
FINDLIB(packages,...) : Findlib packages are installed
IS_UNIX : O.S. type is Unix
IS_WIN32 : O.S. type is Win32
IS_CYGWIN : O.S. type is Cygwin
ENV(name[{=|<>}value]) : Check environment variable
OCAML(name[{=|<>}value]) : Check OCaml configuration property
NATIVE : Native compilation is supported\n");
("-output-name", Set print_output_name, " (undocumented)");
("-msvc", Set ms_paths, " (undocumented)");
("-no-build", Set no_build, " (undocumented)");
("-install", String set_install, " (undocumented)");
("-prof", Set prof, " (undocumented)");
("-distclean", Set is_distclean, " (undocumented)");
("-jobs", Set_int jobs, " (undocumented)");
("-serial", Set serial, " (undocumented)");
("-verbose", Set_int verbose, " (undocumented)");
( " -install " , Set_string install , " " Copy the output to the specified directory . When building libraries the path is relative to " ^
( win32 " % OCAMLLIB% " " $ OCAMLLIB " ) ^ " . Create all non - existing directories . " ) ;
(win32 "%OCAMLLIB%" "$OCAMLLIB") ^ ". Create all non-existing directories.");*)
] in
let command_name = Filename.basename Sys.argv.(0) in
let help_message = sprintf "\nUsage:\n %s target.ml... [options]\n\nOptions:" command_name in
Arg.parse speclist add_target help_message;
let main' () =
toplevel_modules := List.rev !toplevel_modules;
if List.length !toplevel_modules = 0 then begin
Arg.usage speclist help_message;
exit 0;
end;
if not !enabled then (exit 0);
let compilation = if !compilation = [] then [Bytecode] else !compilation in
let compilation = List.sort Stdlib.compare compilation in
if !print_output_name then begin
List.iter begin fun compilation ->
let outname = get_output_name ~compilation ~outkind:!outkind ~outname:!output_name ~dontaddopt:!dontaddopt () in
printf "%s\n%!" outname
end compilation;
exit 0;
end;
if !is_clean || !is_distclean then begin
let = Oebuild_util.crono ~label:"Oebuild_dep.find " ( ~ignore_stderr : false ) ! toplevel_modules in
let deps =
Oebuild_dep.ocamldep_toplevels ~verbose:false ~pp:!pp ~ignore_stderr:false !toplevel_modules
|> Oebuild_dep.sort_dependencies
in
if !is_clean then (clean ~deps ());
if !is_distclean then (distclean ());
end else begin
let last_outname = ref None in
let outnames =
List.map begin fun compilation ->
let outname = get_output_name ~compilation ~outkind:!outkind ~outname:!output_name ~dontaddopt:!dontaddopt () in
match
if !no_build then Built_successfully, []
else begin
let deps =
if !nodep then !toplevel_modules
else if !serial
then Miscellanea.crono ~label:"Oebuild_dep.find" (fun () -> Oebuild_dep.find ~pp:!pp ~ignore_stderr:false !toplevel_modules) ()
else []
in
(build
~compilation
~package:!package
~includes:!includes
~libs:!libs
~other_mods:!mods
~outkind:!outkind
~compile_only:!compile_only
~thread:!thread
~vmthread:!vmthread
~annot:!annot
~bin_annot:!bin_annot
~pp:!pp
?inline:!inline
~cflags:!cflags
~lflags:!lflags
~outname
~deps
~dontlinkdep:!dontlinkdep
~dontaddopt:!dontaddopt
~toplevel_modules:!toplevel_modules
~prof:!prof
~jobs:!jobs
~serial:!serial
~verbose:!verbose
()), deps
end
with
| Built_successfully, deps ->
begin
match !install_flag with
| Some _ when not ! serial - > failwith " -install is accepted only with -serial "
| Some path ->
serial := true;
install ~compilation ~outname ~outkind:!outkind ~deps ~path
~ccomp_type:(Ocaml_config.can_compile_native ());
| _ -> ()
end;
last_outname := Some outname;
(compilation, Some outname)
end compilation;
in
if !outkind = Executable then begin
try
begin
match !run_code with
| Some Native ->
(match List.assoc Native outnames with None -> ()
| Some outname -> run_output ~outname ~args:!run_args)
| Some Bytecode ->
(match List.assoc Bytecode outnames with None -> ()
| Some outname -> run_output ~outname ~args:!run_args)
| Some Unspecified ->
(match !last_outname with None -> ()
| Some outname -> run_output ~outname ~args:!run_args)
| None -> ()
end
with Not_found -> (invalid_arg "-run-opt or -run-byt")
end;
end
in
if !verbose >= 3 then Oebuild_util.crono ~label:"Build time" main' () else main' ()
let _ = main ()
|
3b249bb92064115fa8a871fb5aabd817fc3056369d33734f3437b5c60f554864
|
ghcjs/jsaddle
|
WKWebView.hs
|
module Language.Javascript.JSaddle.WKWebView
( run
) where
run :: IO () -> IO ()
run = id
# INLINE run #
| null |
https://raw.githubusercontent.com/ghcjs/jsaddle/97273656e28790ab6e35c827f8086cf47bfbedca/jsaddle-wkwebview/src-ghcjs/Language/Javascript/JSaddle/WKWebView.hs
|
haskell
|
module Language.Javascript.JSaddle.WKWebView
( run
) where
run :: IO () -> IO ()
run = id
# INLINE run #
|
|
5a4efc938a2365c7fac3e4688b75accf9e157ea592e6a1a253e13bdd100aa991
|
racket/drdr
|
replay.rkt
|
#lang racket/base
(require racket/match
racket/contract/base
(prefix-in racket: racket/base)
"formats.rkt"
"status.rkt")
(define replay-event
(match-lambda
[(struct stdout (bs)) (printf "~a\n" bs)]
[(struct stderr (bs)) (eprintf "~a\n" bs)]))
(define (replay-status s)
(for-each replay-event (status-output-log s))
#;(when (timeout? s)
(eprintf "[replay-log] TIMEOUT!\n"))
#;(when (exit? s)
(eprintf "[replay-log] Exit code: ~a\n" (exit-code s)))
#;(printf "[replay-log] Took ~a\n"
(format-duration-ms (status-duration s)))
(replay-exit-code s))
(define (replay-exit-code s)
(when (exit? s)
(racket:exit (exit-code s))))
(provide/contract
[replay-exit-code (status? . -> . void)]
[replay-status (status? . -> . void)])
| null |
https://raw.githubusercontent.com/racket/drdr/a3e5e778a1c19e7312b98bab25ed95075783f896/replay.rkt
|
racket
|
(when (timeout? s)
(when (exit? s)
(printf "[replay-log] Took ~a\n"
|
#lang racket/base
(require racket/match
racket/contract/base
(prefix-in racket: racket/base)
"formats.rkt"
"status.rkt")
(define replay-event
(match-lambda
[(struct stdout (bs)) (printf "~a\n" bs)]
[(struct stderr (bs)) (eprintf "~a\n" bs)]))
(define (replay-status s)
(for-each replay-event (status-output-log s))
(eprintf "[replay-log] TIMEOUT!\n"))
(eprintf "[replay-log] Exit code: ~a\n" (exit-code s)))
(format-duration-ms (status-duration s)))
(replay-exit-code s))
(define (replay-exit-code s)
(when (exit? s)
(racket:exit (exit-code s))))
(provide/contract
[replay-exit-code (status? . -> . void)]
[replay-status (status? . -> . void)])
|
fdd3e52b750611bcc461b8bee59ed0008e21d71ef087ef7415f9c78d0453f031
|
GaloisInc/daedalus
|
Compat.hs
|
# Language CPP , TemplateHaskell #
# OPTIONS_GHC -Wno - orphans #
module Daedalus.Compat where
| null |
https://raw.githubusercontent.com/GaloisInc/daedalus/d02dda2e149ffa0e7bcca59cddc4991b875006e4/daedalus-utils/src/Daedalus/Compat.hs
|
haskell
|
# Language CPP , TemplateHaskell #
# OPTIONS_GHC -Wno - orphans #
module Daedalus.Compat where
|
|
d4f76fa7b6c4e3ca3e323509e46eeef149ebebc1e475b4b9e235f15de71faf11
|
GillianPlatform/Gillian
|
wislConstants.ml
|
let internal_imports = [ "wisl_pointer_arith.gil"; "wisl_core.gil" ]
let internal_prefix = "i__"
module Prefix = struct
let gvar = "gvar"
let sgvar = "#wisl__"
let loopinv_lab = "loopinv"
let loop_lab = "loop"
let ctn_lab = "continue"
let fail_lab = "fail"
let lbody_lab = "lbody"
let end_lab = "end"
let endif_lab = "endif"
let then_lab = "then"
let else_lab = "else"
end
module InternalProcs = struct
let proc_prefix = ""
let i x = internal_prefix ^ proc_prefix ^ x
let internal_add = i "add"
let internal_minus = i "minus"
let internal_gt = i "gt"
let internal_lt = i "lt"
let internal_leq = i "leq"
let internal_geq = i "geq"
end
module InternalPreds = struct
let pred_prefix = "pred_"
let i x = internal_prefix ^ pred_prefix ^ x
let internal_pred_cell = i "cell"
let internal_pred_add = i "add"
let internal_pred_minus = i "minus"
let internal_pred_gt = i "gt"
let internal_pred_lt = i "lt"
let internal_pred_geq = i "geq"
let internal_pred_leq = i "leq"
end
| null |
https://raw.githubusercontent.com/GillianPlatform/Gillian/3c6d690d82c1b9f63f5dbf2e9357dbde69e5071c/wisl/lib/ParserAndCompiler/wislConstants.ml
|
ocaml
|
let internal_imports = [ "wisl_pointer_arith.gil"; "wisl_core.gil" ]
let internal_prefix = "i__"
module Prefix = struct
let gvar = "gvar"
let sgvar = "#wisl__"
let loopinv_lab = "loopinv"
let loop_lab = "loop"
let ctn_lab = "continue"
let fail_lab = "fail"
let lbody_lab = "lbody"
let end_lab = "end"
let endif_lab = "endif"
let then_lab = "then"
let else_lab = "else"
end
module InternalProcs = struct
let proc_prefix = ""
let i x = internal_prefix ^ proc_prefix ^ x
let internal_add = i "add"
let internal_minus = i "minus"
let internal_gt = i "gt"
let internal_lt = i "lt"
let internal_leq = i "leq"
let internal_geq = i "geq"
end
module InternalPreds = struct
let pred_prefix = "pred_"
let i x = internal_prefix ^ pred_prefix ^ x
let internal_pred_cell = i "cell"
let internal_pred_add = i "add"
let internal_pred_minus = i "minus"
let internal_pred_gt = i "gt"
let internal_pred_lt = i "lt"
let internal_pred_geq = i "geq"
let internal_pred_leq = i "leq"
end
|
|
5e1a9148d2cc7004e67fe5e61a31ba68c5d7a2bd19dcb7b019a743c84b95625e
|
racket/drracket
|
number-snip.rkt
|
#lang racket/base
(require mred
racket/class
framework)
(provide snip-class)
(define snip-class (make-object number-snip:snip-class%))
(send snip-class set-classname (format "~s" `(lib "number-snip.ss" "drracket" "private")))
(send (get-the-snip-class-list) add snip-class)
| null |
https://raw.githubusercontent.com/racket/drracket/2d7c2cded99e630a69f05fb135d1bf7543096a23/drracket/drracket/private/number-snip.rkt
|
racket
|
#lang racket/base
(require mred
racket/class
framework)
(provide snip-class)
(define snip-class (make-object number-snip:snip-class%))
(send snip-class set-classname (format "~s" `(lib "number-snip.ss" "drracket" "private")))
(send (get-the-snip-class-list) add snip-class)
|
|
2419c9fb2053e7007df170987b4cab97f4a096b33d17a76d37e27073c9a213d7
|
alaricsp/chicken-scheme
|
port-tests.scm
|
(require-extension srfi-1)
(define *text* #<<EOF
this is a test
33 > ( let ( ( in ( open - input - string " " ) ) ) ( close - input - port in )
(read-char in)) [09:40]
<foof> Error: (read-char) port already closed: #<input port "(string)">
33 > ( let ( ( in ( open - input - string " " ) ) ) ( close - input - port in )
(read-line in))
<foof> Error: call of non-procedure: #t
<foof> ... that's a little odd
<Bunny351> yuck. [09:44]
<Bunny351> double yuck. [10:00]
<sjamaan> yuck squared! [10:01]
<Bunny351> yuck powered by yuck
<Bunny351> (to the power of yuck, of course) [10:02]
<pbusser3> My yuck is bigger than yours!!!
<foof> yuck!
<foof> (that's a factorial)
<sjamaan> heh
<sjamaan> I think you outyucked us all [10:03]
<foof> well, for large enough values of yuck, yuck! ~= yuck^yuck [10:04]
ERC>
EOF
)
(define p (open-input-string *text*))
(assert (string=? "this is a test" (read-line p)))
(assert
(string=?
"<foof> #;33> (let ((in (open-input-string \"\"))) (close-input-port in)"
(read-line p)))
(assert (= 20 (length (read-lines (open-input-string *text*)))))
| null |
https://raw.githubusercontent.com/alaricsp/chicken-scheme/1eb14684c26b7c2250ca9b944c6b671cb62cafbc/tests/port-tests.scm
|
scheme
|
(require-extension srfi-1)
(define *text* #<<EOF
this is a test
33 > ( let ( ( in ( open - input - string " " ) ) ) ( close - input - port in )
(read-char in)) [09:40]
<foof> Error: (read-char) port already closed: #<input port "(string)">
33 > ( let ( ( in ( open - input - string " " ) ) ) ( close - input - port in )
(read-line in))
<foof> Error: call of non-procedure: #t
<foof> ... that's a little odd
<Bunny351> yuck. [09:44]
<Bunny351> double yuck. [10:00]
<sjamaan> yuck squared! [10:01]
<Bunny351> yuck powered by yuck
<Bunny351> (to the power of yuck, of course) [10:02]
<pbusser3> My yuck is bigger than yours!!!
<foof> yuck!
<foof> (that's a factorial)
<sjamaan> heh
<sjamaan> I think you outyucked us all [10:03]
<foof> well, for large enough values of yuck, yuck! ~= yuck^yuck [10:04]
ERC>
EOF
)
(define p (open-input-string *text*))
(assert (string=? "this is a test" (read-line p)))
(assert
(string=?
"<foof> #;33> (let ((in (open-input-string \"\"))) (close-input-port in)"
(read-line p)))
(assert (= 20 (length (read-lines (open-input-string *text*)))))
|
|
d2e70c94dc77212b752bbccbfbc477d7234f82a243eef2facaf3c4d4e2457989
|
racket/db
|
connect-util.rkt
|
#lang racket/base
(require racket/class
db/private/generic/interfaces
db/private/generic/common)
(provide kill-safe-connection
virtual-connection
connection-pool
connection-pool?
connection-pool-lease)
manager% implements kill - safe manager thread w/ request channel
(define manager%
(class object%
;; other-evt : (-> evt)
generates other evt to sync on besides req - channel , eg timeouts
(init-field (other-evt (lambda () never-evt)))
(super-new)
(define req-channel (make-channel))
(define mthread
(thread/suspend-to-kill
(lambda ()
(let loop ()
(sync (wrap-evt req-channel (lambda (p) (p)))
(other-evt))
(loop)))))
(define/public (call proc)
(call* proc req-channel #f))
(define/public (call-evt proc)
(call* proc req-channel #t))
(define/private (call* proc chan as-evt?)
(thread-resume mthread (current-thread))
(let* ([result #f]
[sema (make-semaphore 0)]
[proc (lambda ()
(set! result
(with-handlers ([(lambda (e) #t)
(lambda (e) (cons 'exn e))])
(cons 'values (call-with-values proc list))))
(semaphore-post sema))]
[handler
(lambda (_evt)
(semaphore-wait sema)
(case (car result)
((values) (apply values (cdr result)))
((exn) (raise (cdr result)))))])
(if as-evt?
(wrap-evt (channel-put-evt chan proc) handler)
(begin (channel-put chan proc)
(handler #f)))))))
;; ----
;; Kill-safe wrapper
;; Note: wrapper protects against kill-thread, but not from
;; custodian-shutdown of ports, etc.
(define kill-safe-connection%
(class* object% (connection<%>)
(init-private connection)
(define mgr (new manager%))
(define last-connected? #t)
(define-syntax-rule (define-forward (method arg ...) ...)
(begin
(define/public (method arg ...)
(send mgr call (lambda ()
(dynamic-wind
void
(lambda () (send connection method arg ...))
(lambda () (set! last-connected? (send connection connected?)))))))
...))
(define/public (connected?)
;; If mgr is busy, then just return last-connected?, otherwise, do check.
(sync/timeout
(lambda () last-connected?)
(send mgr call-evt
(lambda ()
(set! last-connected? (send connection connected?))
last-connected?))))
(define-forward
(disconnect)
(get-dbsystem)
(query fsym stmt cursor?)
(prepare fsym stmt close-on-exec?)
(fetch/cursor fsym cursor fetch-size)
(get-base)
(free-statement stmt need-lock?)
(transaction-status fsym)
(start-transaction fsym isolation option cwt?)
(end-transaction fsym mode cwt?)
(list-tables fsym schema))
(super-new)))
;; ----
(define (kill-safe-connection connection)
(new kill-safe-connection%
(connection connection)))
;; ========================================
;; Virtual connection
(define virtual-connection%
(class* object% (connection<%>)
(init-private connector ;; called from client thread
get-key) ;; called from client thread
(super-new)
(define custodian (current-custodian))
;; == methods called in manager thread ==
;; key=>conn : hasheq[key => connection]
(define key=>conn (make-hasheq))
(define/private (get key) ;; also called by client thread for connected?
(hash-ref key=>conn key #f))
(define/private (put! key c)
(hash-set! key=>conn key c))
(define/private (remove! key)
(let ([c (get key)])
(when c
(hash-remove! key=>conn key)
(send c disconnect))))
(define mgr
(new manager%
(other-evt
(lambda ()
(choice-evt
(let ([keys (hash-map key=>conn (lambda (k v) k))])
(handle-evt (apply choice-evt keys)
;; Assignment to key has expired
(lambda (key)
(log-db-debug "virtual-connection: key expiration: ~e" key)
(remove! key)))))))))
;; == methods called in client thread ==
(define/private (get-connection create?)
(let* ([key (get-key)]
[c (send mgr call (lambda () (get key)))])
(cond [(and c (send c connected?)) c]
[create?
(log-db-debug
(if c
"virtual-connection: refreshing connection (old is disconnected)"
"virtual-connection: creating new connection"))
(let ([c* (parameterize ((current-custodian custodian))
(connector))])
(send mgr call
(lambda ()
(when c (remove! key))
(put! key c*)))
c*)]
[else
(when c ;; got a disconnected connection
(send mgr call (lambda () (remove! key))))
#f])))
;; ----
(define-syntax-rule (define-forward (req-con? no-con (method arg ...)) ...)
(begin (define/public (method arg ...)
(let ([c (get-connection req-con?)])
(if c
(send c method arg ...)
no-con)))
...))
(define-forward
(#t '_ (get-dbsystem))
(#t '_ (query fsym stmt cursor?))
(#t '_ (fetch/cursor fsym stmt fetch-size))
(#t '_ (start-transaction fsym isolation option cwt?))
(#f (void) (end-transaction fsym mode cwt?))
(#f #f (transaction-status fsym))
(#t '_ (list-tables fsym schema)))
(define/public (get-base)
(get-connection #t))
(define/public (connected?)
(let ([c (get (get-key))])
(and c (send c connected?))))
(define/public (disconnect)
(let ([c (get-connection #f)]
[key (get-key)])
(when c
(send c disconnect)
(send mgr call (lambda () (remove! key)))))
(void))
(define/public (prepare fsym stmt close-on-exec?)
;; FIXME: hacky way of supporting virtual-statement
(unless (or close-on-exec? (eq? fsym 'virtual-statement))
(error fsym "cannot prepare statement with virtual connection"))
(send (get-connection #t) prepare fsym stmt close-on-exec?))
(define/public (free-statement stmt need-lock?)
(error/internal 'free-statement "virtual connection does not own statements"))))
;; ----
(define (virtual-connection connector)
(let ([connector
(cond [(connection-pool? connector)
(lambda () (connection-pool-lease connector))]
[else connector])]
[get-key (lambda () (thread-dead-evt (current-thread)))])
(new virtual-connection%
(connector connector)
(get-key get-key))))
;; ========================================
;; Connection pool
(define connection-pool%
(class* object% ()
(init-private connector ;; called from manager thread
max-connections
max-idle-connections)
(super-new)
(define proxy-counter 1) ;; for debugging
(define actual-counter 1) ;; for debugging
(define actual=>number (make-weak-hasheq))
;; == methods called in manager thread ==
assigned - connections :
(define assigned-connections 0)
;; proxy=>evt : hasheq[proxy-connection => evt]
(define proxy=>evt (make-hasheq))
;; idle-list : (listof raw-connection)
(define idle-list null)
;; lease* : Evt -> (U Connection 'limit)
(define/private (lease* key)
(cond [(< assigned-connections max-connections)
(cond [(try-take-idle)
=> (lambda (raw-c) (lease** key raw-c #t))]
[else (lease** key (new-connection) #f)])]
[else 'limit]))
(define/private (lease** key raw-c reused?)
(define proxy-number proxy-counter)
(set! proxy-counter (add1 proxy-counter))
(define c
(new proxy-connection%
(pool this) (connection raw-c) (number proxy-number)))
(log-db-debug "connection-pool: leasing connection #~a (~a @~a)"
proxy-number
(if reused? "idle" "new")
(hash-ref actual=>number raw-c "???"))
(hash-set! proxy=>evt c (wrap-evt key (lambda (_e) c)))
(set! assigned-connections (add1 assigned-connections))
c)
(define/private (try-take-idle)
(and (pair? idle-list)
(let ([c (car idle-list)])
(set! idle-list (cdr idle-list))
(if (send c connected?)
c
(try-take-idle)))))
(define/private (release* proxy raw-c why)
(log-db-debug "connection-pool: releasing connection #~a (~a, ~a)"
(send proxy get-number)
(cond [(not raw-c) "no-op"]
[(< (length idle-list) max-idle-connections) "idle"]
[else "disconnect"])
why)
(hash-remove! proxy=>evt proxy)
(when raw-c
(with-handlers ([exn:fail? void])
If in tx , just disconnect ( for simplicity ; else must loop for nested )
(when (send raw-c transaction-status 'connection-pool)
(send raw-c disconnect)))
(cond [(and (< (length idle-list) max-idle-connections)
(send raw-c connected?))
(set! idle-list (cons raw-c idle-list))]
[else (send raw-c disconnect)])
(set! assigned-connections (sub1 assigned-connections))))
(define/private (new-connection)
(define c (connector))
(define actual-number actual-counter)
(set! actual-counter (add1 actual-counter))
(when (or (hash-ref proxy=>evt c #f) (memq c idle-list))
(error 'connection-pool "connect function did not produce a fresh connection"))
(hash-set! actual=>number c actual-number)
c)
(define/private (clear-idle*)
(for ([c (in-list idle-list)])
(send c disconnect))
(set! idle-list null))
(define mgr
(new manager%
(other-evt
(lambda ()
(let ([evts (hash-values proxy=>evt)])
(handle-evt (apply choice-evt evts)
(lambda (proxy)
(release* proxy
(send proxy release-connection)
"release-evt"))))))))
;; == methods called in client thread ==
(define/public (lease-evt key)
(send mgr call-evt (lambda () (lease* key))))
(define/public (release proxy)
(let ([raw-c (send proxy release-connection)])
(send mgr call (lambda () (release* proxy raw-c "proxy disconnect"))))
(void))
(define/public (clear-idle)
(send mgr call (lambda () (clear-idle*))))
))
;; --
(define proxy-connection%
(class* locking% (connection<%>)
(init-private connection
pool
number)
(inherit call-with-lock)
(super-new)
(define-syntax-rule (define-forward defmethod (method arg ...) ...)
(begin
(defmethod (method arg ...)
(call-with-lock 'method
(lambda ()
(let ([c connection])
(unless c (error/not-connected 'method))
(send c method arg ...)))))
...))
(define-forward define/public
(get-dbsystem)
(query fsym stmt cursor?)
(prepare fsym stmt close-on-exec?)
(fetch/cursor fsym stmt fetch-size)
(get-base)
(free-statement stmt need-lock?)
(transaction-status fsym)
(start-transaction fsym isolation option cwt?)
(end-transaction fsym mode cwt?)
(list-tables fsym schema))
(define/override (connected?) (and connection (send connection connected?)))
(define/public (disconnect)
(send pool release this))
(define/public (get-number) number)
(define/public (release-connection)
(begin0 connection
(set! connection #f)))))
;; ----
(define (connection-pool connector
#:max-connections [max-connections +inf.0]
#:max-idle-connections [max-idle-connections 10])
(new connection-pool%
(connector connector)
(max-connections max-connections)
(max-idle-connections max-idle-connections)))
(define (connection-pool? x)
(is-a? x connection-pool%))
(define (connection-pool-lease pool [key (current-thread)]
#:timeout [timeout +inf.0])
(let ([key
(cond [(thread? key) (thread-dead-evt key)]
[(custodian? key) (make-custodian-box key #t)]
[else key])])
(cond [(sync/timeout timeout (send pool lease-evt key))
=> (lambda (result)
(when (eq? result 'limit)
(error 'connection-pool-lease "connection pool limit reached"))
result)]
[else #f])))
| null |
https://raw.githubusercontent.com/racket/db/0336d2522a613e76ebf60705cea3be4c237c447e/db-lib/db/private/generic/connect-util.rkt
|
racket
|
other-evt : (-> evt)
----
Kill-safe wrapper
Note: wrapper protects against kill-thread, but not from
custodian-shutdown of ports, etc.
If mgr is busy, then just return last-connected?, otherwise, do check.
----
========================================
Virtual connection
called from client thread
called from client thread
== methods called in manager thread ==
key=>conn : hasheq[key => connection]
also called by client thread for connected?
Assignment to key has expired
== methods called in client thread ==
got a disconnected connection
----
FIXME: hacky way of supporting virtual-statement
----
========================================
Connection pool
called from manager thread
for debugging
for debugging
== methods called in manager thread ==
proxy=>evt : hasheq[proxy-connection => evt]
idle-list : (listof raw-connection)
lease* : Evt -> (U Connection 'limit)
else must loop for nested )
== methods called in client thread ==
--
----
|
#lang racket/base
(require racket/class
db/private/generic/interfaces
db/private/generic/common)
(provide kill-safe-connection
virtual-connection
connection-pool
connection-pool?
connection-pool-lease)
manager% implements kill - safe manager thread w/ request channel
(define manager%
(class object%
generates other evt to sync on besides req - channel , eg timeouts
(init-field (other-evt (lambda () never-evt)))
(super-new)
(define req-channel (make-channel))
(define mthread
(thread/suspend-to-kill
(lambda ()
(let loop ()
(sync (wrap-evt req-channel (lambda (p) (p)))
(other-evt))
(loop)))))
(define/public (call proc)
(call* proc req-channel #f))
(define/public (call-evt proc)
(call* proc req-channel #t))
(define/private (call* proc chan as-evt?)
(thread-resume mthread (current-thread))
(let* ([result #f]
[sema (make-semaphore 0)]
[proc (lambda ()
(set! result
(with-handlers ([(lambda (e) #t)
(lambda (e) (cons 'exn e))])
(cons 'values (call-with-values proc list))))
(semaphore-post sema))]
[handler
(lambda (_evt)
(semaphore-wait sema)
(case (car result)
((values) (apply values (cdr result)))
((exn) (raise (cdr result)))))])
(if as-evt?
(wrap-evt (channel-put-evt chan proc) handler)
(begin (channel-put chan proc)
(handler #f)))))))
(define kill-safe-connection%
(class* object% (connection<%>)
(init-private connection)
(define mgr (new manager%))
(define last-connected? #t)
(define-syntax-rule (define-forward (method arg ...) ...)
(begin
(define/public (method arg ...)
(send mgr call (lambda ()
(dynamic-wind
void
(lambda () (send connection method arg ...))
(lambda () (set! last-connected? (send connection connected?)))))))
...))
(define/public (connected?)
(sync/timeout
(lambda () last-connected?)
(send mgr call-evt
(lambda ()
(set! last-connected? (send connection connected?))
last-connected?))))
(define-forward
(disconnect)
(get-dbsystem)
(query fsym stmt cursor?)
(prepare fsym stmt close-on-exec?)
(fetch/cursor fsym cursor fetch-size)
(get-base)
(free-statement stmt need-lock?)
(transaction-status fsym)
(start-transaction fsym isolation option cwt?)
(end-transaction fsym mode cwt?)
(list-tables fsym schema))
(super-new)))
(define (kill-safe-connection connection)
(new kill-safe-connection%
(connection connection)))
(define virtual-connection%
(class* object% (connection<%>)
(super-new)
(define custodian (current-custodian))
(define key=>conn (make-hasheq))
(hash-ref key=>conn key #f))
(define/private (put! key c)
(hash-set! key=>conn key c))
(define/private (remove! key)
(let ([c (get key)])
(when c
(hash-remove! key=>conn key)
(send c disconnect))))
(define mgr
(new manager%
(other-evt
(lambda ()
(choice-evt
(let ([keys (hash-map key=>conn (lambda (k v) k))])
(handle-evt (apply choice-evt keys)
(lambda (key)
(log-db-debug "virtual-connection: key expiration: ~e" key)
(remove! key)))))))))
(define/private (get-connection create?)
(let* ([key (get-key)]
[c (send mgr call (lambda () (get key)))])
(cond [(and c (send c connected?)) c]
[create?
(log-db-debug
(if c
"virtual-connection: refreshing connection (old is disconnected)"
"virtual-connection: creating new connection"))
(let ([c* (parameterize ((current-custodian custodian))
(connector))])
(send mgr call
(lambda ()
(when c (remove! key))
(put! key c*)))
c*)]
[else
(send mgr call (lambda () (remove! key))))
#f])))
(define-syntax-rule (define-forward (req-con? no-con (method arg ...)) ...)
(begin (define/public (method arg ...)
(let ([c (get-connection req-con?)])
(if c
(send c method arg ...)
no-con)))
...))
(define-forward
(#t '_ (get-dbsystem))
(#t '_ (query fsym stmt cursor?))
(#t '_ (fetch/cursor fsym stmt fetch-size))
(#t '_ (start-transaction fsym isolation option cwt?))
(#f (void) (end-transaction fsym mode cwt?))
(#f #f (transaction-status fsym))
(#t '_ (list-tables fsym schema)))
(define/public (get-base)
(get-connection #t))
(define/public (connected?)
(let ([c (get (get-key))])
(and c (send c connected?))))
(define/public (disconnect)
(let ([c (get-connection #f)]
[key (get-key)])
(when c
(send c disconnect)
(send mgr call (lambda () (remove! key)))))
(void))
(define/public (prepare fsym stmt close-on-exec?)
(unless (or close-on-exec? (eq? fsym 'virtual-statement))
(error fsym "cannot prepare statement with virtual connection"))
(send (get-connection #t) prepare fsym stmt close-on-exec?))
(define/public (free-statement stmt need-lock?)
(error/internal 'free-statement "virtual connection does not own statements"))))
(define (virtual-connection connector)
(let ([connector
(cond [(connection-pool? connector)
(lambda () (connection-pool-lease connector))]
[else connector])]
[get-key (lambda () (thread-dead-evt (current-thread)))])
(new virtual-connection%
(connector connector)
(get-key get-key))))
(define connection-pool%
(class* object% ()
max-connections
max-idle-connections)
(super-new)
(define actual=>number (make-weak-hasheq))
assigned - connections :
(define assigned-connections 0)
(define proxy=>evt (make-hasheq))
(define idle-list null)
(define/private (lease* key)
(cond [(< assigned-connections max-connections)
(cond [(try-take-idle)
=> (lambda (raw-c) (lease** key raw-c #t))]
[else (lease** key (new-connection) #f)])]
[else 'limit]))
(define/private (lease** key raw-c reused?)
(define proxy-number proxy-counter)
(set! proxy-counter (add1 proxy-counter))
(define c
(new proxy-connection%
(pool this) (connection raw-c) (number proxy-number)))
(log-db-debug "connection-pool: leasing connection #~a (~a @~a)"
proxy-number
(if reused? "idle" "new")
(hash-ref actual=>number raw-c "???"))
(hash-set! proxy=>evt c (wrap-evt key (lambda (_e) c)))
(set! assigned-connections (add1 assigned-connections))
c)
(define/private (try-take-idle)
(and (pair? idle-list)
(let ([c (car idle-list)])
(set! idle-list (cdr idle-list))
(if (send c connected?)
c
(try-take-idle)))))
(define/private (release* proxy raw-c why)
(log-db-debug "connection-pool: releasing connection #~a (~a, ~a)"
(send proxy get-number)
(cond [(not raw-c) "no-op"]
[(< (length idle-list) max-idle-connections) "idle"]
[else "disconnect"])
why)
(hash-remove! proxy=>evt proxy)
(when raw-c
(with-handlers ([exn:fail? void])
(when (send raw-c transaction-status 'connection-pool)
(send raw-c disconnect)))
(cond [(and (< (length idle-list) max-idle-connections)
(send raw-c connected?))
(set! idle-list (cons raw-c idle-list))]
[else (send raw-c disconnect)])
(set! assigned-connections (sub1 assigned-connections))))
(define/private (new-connection)
(define c (connector))
(define actual-number actual-counter)
(set! actual-counter (add1 actual-counter))
(when (or (hash-ref proxy=>evt c #f) (memq c idle-list))
(error 'connection-pool "connect function did not produce a fresh connection"))
(hash-set! actual=>number c actual-number)
c)
(define/private (clear-idle*)
(for ([c (in-list idle-list)])
(send c disconnect))
(set! idle-list null))
(define mgr
(new manager%
(other-evt
(lambda ()
(let ([evts (hash-values proxy=>evt)])
(handle-evt (apply choice-evt evts)
(lambda (proxy)
(release* proxy
(send proxy release-connection)
"release-evt"))))))))
(define/public (lease-evt key)
(send mgr call-evt (lambda () (lease* key))))
(define/public (release proxy)
(let ([raw-c (send proxy release-connection)])
(send mgr call (lambda () (release* proxy raw-c "proxy disconnect"))))
(void))
(define/public (clear-idle)
(send mgr call (lambda () (clear-idle*))))
))
(define proxy-connection%
(class* locking% (connection<%>)
(init-private connection
pool
number)
(inherit call-with-lock)
(super-new)
(define-syntax-rule (define-forward defmethod (method arg ...) ...)
(begin
(defmethod (method arg ...)
(call-with-lock 'method
(lambda ()
(let ([c connection])
(unless c (error/not-connected 'method))
(send c method arg ...)))))
...))
(define-forward define/public
(get-dbsystem)
(query fsym stmt cursor?)
(prepare fsym stmt close-on-exec?)
(fetch/cursor fsym stmt fetch-size)
(get-base)
(free-statement stmt need-lock?)
(transaction-status fsym)
(start-transaction fsym isolation option cwt?)
(end-transaction fsym mode cwt?)
(list-tables fsym schema))
(define/override (connected?) (and connection (send connection connected?)))
(define/public (disconnect)
(send pool release this))
(define/public (get-number) number)
(define/public (release-connection)
(begin0 connection
(set! connection #f)))))
(define (connection-pool connector
#:max-connections [max-connections +inf.0]
#:max-idle-connections [max-idle-connections 10])
(new connection-pool%
(connector connector)
(max-connections max-connections)
(max-idle-connections max-idle-connections)))
(define (connection-pool? x)
(is-a? x connection-pool%))
(define (connection-pool-lease pool [key (current-thread)]
#:timeout [timeout +inf.0])
(let ([key
(cond [(thread? key) (thread-dead-evt key)]
[(custodian? key) (make-custodian-box key #t)]
[else key])])
(cond [(sync/timeout timeout (send pool lease-evt key))
=> (lambda (result)
(when (eq? result 'limit)
(error 'connection-pool-lease "connection pool limit reached"))
result)]
[else #f])))
|
c4ff6c7eab0ca5c7458903b2d2bdad98a0aaa0794138101e2ffc141f35912f7e
|
picty/parsifal
|
pcapContainers.ml
|
open Parsifal
open BasePTypes
open PTypes
open Pcap
(* TODO: All this should be rewritten from scratch *)
(* because of lots of shortcuts in the current implementation *)
type connection_key = {
source : ipv4 * int;
destination : ipv4 * int;
}
let string_of_connexion_key k =
Printf.sprintf "%s:%d -> %s:%d\n"
(string_of_ipv4 (fst k.source)) (snd k.source)
(string_of_ipv4 (fst k.destination)) (snd k.destination)
type segment = direction * int * int * string
type 'a oriented_tcp_container = (connection_key * (direction * 'a) list) list
let parse_oriented_tcp_container (init_fun : unit -> unit) (expected_dest_port : int) (_name : string)
(parse_fun : direction -> string_input -> 'a)
(input : string_input) : 'a oriented_tcp_container =
let connections : (connection_key, segment list) Hashtbl.t = Hashtbl.create 100 in
let update_connection = function
| { ip_payload = TCPLayer {
tcp_payload = "" } } -> ()
(* TODO: Handle SYN/SYN-ACK *)
| { source_ip = src_ip;
dest_ip = dst_ip;
ip_payload = TCPLayer {
source_port = src_port;
dest_port = dst_port;
seq = seq; ack = ack;
tcp_payload = payload } } ->
begin
let key, dir =
if dst_port = expected_dest_port
then Some {source = src_ip, src_port;
destination = dst_ip, dst_port},
ClientToServer
else if src_port = expected_dest_port
then Some {source = dst_ip, dst_port;
destination = src_ip, src_port},
ServerToClient
else None, ClientToServer
in match key with
| None -> ()
| Some k -> begin
try
let c = Hashtbl.find connections k in
Hashtbl.replace connections k (c@[dir, seq, ack, payload])
with Not_found ->
Hashtbl.replace connections k [dir, seq, ack, payload]
end
end
| _ -> ()
in
let handle_one_packet packet = match packet.data with
| EthernetContent { ether_payload = IPLayer ip_layer }
| IPContent ip_layer ->
update_connection ip_layer
| _ -> ()
in
let result = ref [] in
let handle_one_connection k c =
(* TODO: Improve this function (it does not take segment overlapping into account *)
let aggregate segs =
let extract_first_segment = function
TODO : Other strategies are possible ( by using SYN / SYN - ACK / ACK packets ) ...
| [] -> failwith "Internal error: segment list should not be empty"
| f::r -> f, r
in
let rec find_next_seg leftover accu ((cur_dir, next_seq, next_ack, cur_payload) as cur_seg) = function
(* TODO: What should we do with leftover here? *)
| [] -> List.rev ((cur_dir, cur_payload)::accu)
| ((dir, seq, ack, payload) as seg)::r ->
if dir = cur_dir && next_seq = seq && next_ack = ack
then find_next_seg [] accu
(dir, seq + String.length payload, ack, cur_payload^payload)
(List.rev_append leftover r)
else if dir <> cur_dir && next_ack = seq && next_seq = ack
then find_next_seg [] ((cur_dir, cur_payload)::accu)
(dir, seq + String.length payload, ack, payload)
(List.rev_append leftover r)
else find_next_seg (seg::leftover) accu cur_seg r
in
init_fun ();
let (dir, seq, ack, p), other_segs = extract_first_segment segs in
find_next_seg [] [] (dir, seq + String.length p, ack, p) other_segs
in
let cname = string_of_connexion_key k in
let segs = aggregate c in
let parse_aggregate (dir, payload) =
let new_input = get_in_container input cname payload in
let res = parse_rem_list "tcp_container" (parse_fun dir) new_input in
check_empty_input true new_input;
List.map (fun x -> dir, x) res
in
let conn_res = k, List.flatten (List.map parse_aggregate segs) in
result := conn_res::(!result)
in
let pcap = parse_pcap_file input in
List.iter handle_one_packet pcap.packets;
Hashtbl.iter handle_one_connection connections;
List.rev !result
let dump_oriented_tcp_container _dump_fun _o = not_implemented "dump_oriented_tcp_container"
let value_of_tcp_connexion value_of_fun (k, segs) =
let value_of_one_aggregate (d, p) = VRecord [
"@name", VString ("tcp_aggregate", false);
"direction", VString (string_of_direction d, false);
"payload", value_of_fun p
] in VRecord [
"@name", VString ("tcp_connexion", false);
"src", value_of_ipv4 (fst k.source);
"src_port", VInt (snd k.source);
"dst", value_of_ipv4 (fst k.destination);
"dst_port", VInt (snd k.destination);
"data", VList (List.map value_of_one_aggregate segs)
]
let value_of_oriented_tcp_container value_of_fun = value_of_list (value_of_tcp_connexion value_of_fun)
type 'a tcp_container = (connection_key * (direction * 'a) list) list
let parse_tcp_container expected_dest_port name parse_fun input =
parse_oriented_tcp_container (fun () -> ()) expected_dest_port name (fun _ -> parse_fun) input
let dump_tcp_container _dump_fun _o = not_implemented "dump_tcp_container"
let value_of_tcp_container value_of_fun = value_of_list (value_of_tcp_connexion value_of_fun)
type 'a udp_container = (connection_key * (direction * 'a) list) list
let parse_udp_container (expected_dest_port : int) (_name : string)
(parse_fun : string_input -> 'a)
(input : string_input) : 'a udp_container =
let connections : (connection_key, (direction * string) list) Hashtbl.t = Hashtbl.create 100 in
let update_connection = function
| { source_ip = src_ip;
dest_ip = dst_ip;
ip_payload = UDPLayer {
udp_source_port = src_port;
udp_dest_port = dst_port;
udp_payload = payload } } ->
begin
let key, dir =
if dst_port = expected_dest_port
then Some {source = src_ip, src_port;
destination = dst_ip, dst_port},
ClientToServer
else if src_port = expected_dest_port
then Some {source = dst_ip, dst_port;
destination = src_ip, src_port},
ServerToClient
else None, ClientToServer
in match key with
| None -> ()
| Some k -> begin
try
let c = Hashtbl.find connections k in
Hashtbl.replace connections k (c@[dir, exact_dump dump_udp_service payload])
with Not_found ->
Hashtbl.replace connections k [dir, exact_dump dump_udp_service payload]
end
end
| _ -> ()
in
let handle_one_packet packet = match packet.data with
| EthernetContent { ether_payload = IPLayer ip_layer }
| IPContent ip_layer ->
update_connection ip_layer
| _ -> ()
in
let result = ref [] in
let handle_one_connection k c =
let c2s = string_of_connexion_key k
and s2c = Printf.sprintf "%s:%d -> %s:%d\n"
(string_of_ipv4 (fst k.destination)) (snd k.destination)
(string_of_ipv4 (fst k.source)) (snd k.source)
in
let handle_one_datagram (dir, s) =
let cname = match dir with
| ClientToServer -> c2s
| ServerToClient -> s2c
in
let new_input = get_in_container input cname s in
let res = dir, exact_parse parse_fun new_input in
check_empty_input true new_input;
res
in
let conn_res = k, List.map handle_one_datagram c in
result := conn_res::(!result)
in
enrich_udp_service := false;
let pcap = parse_pcap_file input in
List.iter handle_one_packet pcap.packets;
Hashtbl.iter handle_one_connection connections;
List.rev !result
let dump_udp_container _dump_fun _o = not_implemented "NotImplemented: dump_tcp_container"
let value_of_udp_connexion value_of_fun (k, segs) =
let value_of_one_aggregate (d, p) = VRecord [
"@name", VString ("udp_datagram", false);
"direction", VString (string_of_direction d, false);
"payload", value_of_fun p
] in VRecord [
"@name", VString ("udp_connexion", false);
"src", value_of_ipv4 (fst k.source);
"src_port", VInt (snd k.source);
"dst", value_of_ipv4 (fst k.destination);
"dst_port", VInt (snd k.destination);
"data", VList (List.map value_of_one_aggregate segs)
]
let value_of_udp_container value_of_fun = value_of_list (value_of_udp_connexion value_of_fun)
| null |
https://raw.githubusercontent.com/picty/parsifal/767a1d558ea6da23ada46d8d96a057514b0aa2a8/net/pcapContainers.ml
|
ocaml
|
TODO: All this should be rewritten from scratch
because of lots of shortcuts in the current implementation
TODO: Handle SYN/SYN-ACK
TODO: Improve this function (it does not take segment overlapping into account
TODO: What should we do with leftover here?
|
open Parsifal
open BasePTypes
open PTypes
open Pcap
type connection_key = {
source : ipv4 * int;
destination : ipv4 * int;
}
let string_of_connexion_key k =
Printf.sprintf "%s:%d -> %s:%d\n"
(string_of_ipv4 (fst k.source)) (snd k.source)
(string_of_ipv4 (fst k.destination)) (snd k.destination)
type segment = direction * int * int * string
type 'a oriented_tcp_container = (connection_key * (direction * 'a) list) list
let parse_oriented_tcp_container (init_fun : unit -> unit) (expected_dest_port : int) (_name : string)
(parse_fun : direction -> string_input -> 'a)
(input : string_input) : 'a oriented_tcp_container =
let connections : (connection_key, segment list) Hashtbl.t = Hashtbl.create 100 in
let update_connection = function
| { ip_payload = TCPLayer {
tcp_payload = "" } } -> ()
| { source_ip = src_ip;
dest_ip = dst_ip;
ip_payload = TCPLayer {
source_port = src_port;
dest_port = dst_port;
seq = seq; ack = ack;
tcp_payload = payload } } ->
begin
let key, dir =
if dst_port = expected_dest_port
then Some {source = src_ip, src_port;
destination = dst_ip, dst_port},
ClientToServer
else if src_port = expected_dest_port
then Some {source = dst_ip, dst_port;
destination = src_ip, src_port},
ServerToClient
else None, ClientToServer
in match key with
| None -> ()
| Some k -> begin
try
let c = Hashtbl.find connections k in
Hashtbl.replace connections k (c@[dir, seq, ack, payload])
with Not_found ->
Hashtbl.replace connections k [dir, seq, ack, payload]
end
end
| _ -> ()
in
let handle_one_packet packet = match packet.data with
| EthernetContent { ether_payload = IPLayer ip_layer }
| IPContent ip_layer ->
update_connection ip_layer
| _ -> ()
in
let result = ref [] in
let handle_one_connection k c =
let aggregate segs =
let extract_first_segment = function
TODO : Other strategies are possible ( by using SYN / SYN - ACK / ACK packets ) ...
| [] -> failwith "Internal error: segment list should not be empty"
| f::r -> f, r
in
let rec find_next_seg leftover accu ((cur_dir, next_seq, next_ack, cur_payload) as cur_seg) = function
| [] -> List.rev ((cur_dir, cur_payload)::accu)
| ((dir, seq, ack, payload) as seg)::r ->
if dir = cur_dir && next_seq = seq && next_ack = ack
then find_next_seg [] accu
(dir, seq + String.length payload, ack, cur_payload^payload)
(List.rev_append leftover r)
else if dir <> cur_dir && next_ack = seq && next_seq = ack
then find_next_seg [] ((cur_dir, cur_payload)::accu)
(dir, seq + String.length payload, ack, payload)
(List.rev_append leftover r)
else find_next_seg (seg::leftover) accu cur_seg r
in
init_fun ();
let (dir, seq, ack, p), other_segs = extract_first_segment segs in
find_next_seg [] [] (dir, seq + String.length p, ack, p) other_segs
in
let cname = string_of_connexion_key k in
let segs = aggregate c in
let parse_aggregate (dir, payload) =
let new_input = get_in_container input cname payload in
let res = parse_rem_list "tcp_container" (parse_fun dir) new_input in
check_empty_input true new_input;
List.map (fun x -> dir, x) res
in
let conn_res = k, List.flatten (List.map parse_aggregate segs) in
result := conn_res::(!result)
in
let pcap = parse_pcap_file input in
List.iter handle_one_packet pcap.packets;
Hashtbl.iter handle_one_connection connections;
List.rev !result
let dump_oriented_tcp_container _dump_fun _o = not_implemented "dump_oriented_tcp_container"
let value_of_tcp_connexion value_of_fun (k, segs) =
let value_of_one_aggregate (d, p) = VRecord [
"@name", VString ("tcp_aggregate", false);
"direction", VString (string_of_direction d, false);
"payload", value_of_fun p
] in VRecord [
"@name", VString ("tcp_connexion", false);
"src", value_of_ipv4 (fst k.source);
"src_port", VInt (snd k.source);
"dst", value_of_ipv4 (fst k.destination);
"dst_port", VInt (snd k.destination);
"data", VList (List.map value_of_one_aggregate segs)
]
let value_of_oriented_tcp_container value_of_fun = value_of_list (value_of_tcp_connexion value_of_fun)
type 'a tcp_container = (connection_key * (direction * 'a) list) list
let parse_tcp_container expected_dest_port name parse_fun input =
parse_oriented_tcp_container (fun () -> ()) expected_dest_port name (fun _ -> parse_fun) input
let dump_tcp_container _dump_fun _o = not_implemented "dump_tcp_container"
let value_of_tcp_container value_of_fun = value_of_list (value_of_tcp_connexion value_of_fun)
type 'a udp_container = (connection_key * (direction * 'a) list) list
let parse_udp_container (expected_dest_port : int) (_name : string)
(parse_fun : string_input -> 'a)
(input : string_input) : 'a udp_container =
let connections : (connection_key, (direction * string) list) Hashtbl.t = Hashtbl.create 100 in
let update_connection = function
| { source_ip = src_ip;
dest_ip = dst_ip;
ip_payload = UDPLayer {
udp_source_port = src_port;
udp_dest_port = dst_port;
udp_payload = payload } } ->
begin
let key, dir =
if dst_port = expected_dest_port
then Some {source = src_ip, src_port;
destination = dst_ip, dst_port},
ClientToServer
else if src_port = expected_dest_port
then Some {source = dst_ip, dst_port;
destination = src_ip, src_port},
ServerToClient
else None, ClientToServer
in match key with
| None -> ()
| Some k -> begin
try
let c = Hashtbl.find connections k in
Hashtbl.replace connections k (c@[dir, exact_dump dump_udp_service payload])
with Not_found ->
Hashtbl.replace connections k [dir, exact_dump dump_udp_service payload]
end
end
| _ -> ()
in
let handle_one_packet packet = match packet.data with
| EthernetContent { ether_payload = IPLayer ip_layer }
| IPContent ip_layer ->
update_connection ip_layer
| _ -> ()
in
let result = ref [] in
let handle_one_connection k c =
let c2s = string_of_connexion_key k
and s2c = Printf.sprintf "%s:%d -> %s:%d\n"
(string_of_ipv4 (fst k.destination)) (snd k.destination)
(string_of_ipv4 (fst k.source)) (snd k.source)
in
let handle_one_datagram (dir, s) =
let cname = match dir with
| ClientToServer -> c2s
| ServerToClient -> s2c
in
let new_input = get_in_container input cname s in
let res = dir, exact_parse parse_fun new_input in
check_empty_input true new_input;
res
in
let conn_res = k, List.map handle_one_datagram c in
result := conn_res::(!result)
in
enrich_udp_service := false;
let pcap = parse_pcap_file input in
List.iter handle_one_packet pcap.packets;
Hashtbl.iter handle_one_connection connections;
List.rev !result
let dump_udp_container _dump_fun _o = not_implemented "NotImplemented: dump_tcp_container"
let value_of_udp_connexion value_of_fun (k, segs) =
let value_of_one_aggregate (d, p) = VRecord [
"@name", VString ("udp_datagram", false);
"direction", VString (string_of_direction d, false);
"payload", value_of_fun p
] in VRecord [
"@name", VString ("udp_connexion", false);
"src", value_of_ipv4 (fst k.source);
"src_port", VInt (snd k.source);
"dst", value_of_ipv4 (fst k.destination);
"dst_port", VInt (snd k.destination);
"data", VList (List.map value_of_one_aggregate segs)
]
let value_of_udp_container value_of_fun = value_of_list (value_of_udp_connexion value_of_fun)
|
b9db540e984c6900931b02d3db36a64eb45481a5c386ea42c9bc622dad820263
|
brendanhay/statgrab
|
Internal.hs
|
{-# LANGUAGE DeriveGeneric #-}
# LANGUAGE GeneralizedNewtypeDeriving #
-- Module : System.Statgrab.Internal
Copyright : ( c ) 2013 - 2015 < >
License : This Source Code Form is subject to the terms of
the Mozilla Public License , v. 2.0 .
A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at /.
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
-- | Interface types for copying and unmarshalling libstatgrab structs into a
more programmer friendly format .
module System.Statgrab.Internal where
import Control.Applicative
import Data.ByteString (ByteString)
import Data.Time.Clock.POSIX
import Foreign
import Foreign.C.Types
import GHC.Generics (Generic)
type Entries = Ptr CSize
newtype Error = Error CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
newtype HostState = HostState CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
data Host = Host
{ hostOsName :: !ByteString
, hostOsRelease :: !ByteString
, hostOsVersion :: !ByteString
, hostPlatform :: !ByteString
, hostName :: !ByteString
, hostBitWidth :: !Integer
, hostState :: !HostState
, hostNCPU :: !Integer
, hostMaxCPU :: !Integer
, hostUptime :: !POSIXTime
, hostSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data CPU = CPU
{ cpuUser :: !Integer
, cpuKernel :: !Integer
, cpuIdle :: !Integer
, cpuIOWait :: !Integer
, cpuSwap :: !Integer
, cpuNice :: !Integer
, cpuTotal :: !Integer
, cpuCtxSwitches :: !Integer
, cpuVoluntaryCtxSwitches :: !Integer
, cpuInvoluntaryCtxSwitches :: !Integer
, cpuSyscalls :: !Integer
, cpuInterrupts :: !Integer
, cpuSoftInterrupts :: !Integer
, cpuSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
newtype CPUPercentSource = CPUPercentSource CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
data CPUPercent = CPUPercent
{ cpuPctUser :: !Double
, cpuPctKernel :: !Double
, cpuPctIdle :: !Double
, cpuPctIOWait :: !Double
, cpuPctSwap :: !Double
, cpuPctNice :: !Double
, cpuPctTimeTaken :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data Memory = Memory
{ memTotal :: !Integer
, memFree :: !Integer
, memUsed :: !Integer
, memCache :: !Integer
, memSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data Load = Load
{ load1 :: !Double
, load5 :: !Double
, load15 :: !Double
, loadSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data User = User
{ userLoginName :: !ByteString
, userRecordId :: !ByteString
, userRecordIdSize :: !Integer
, userDevice :: !ByteString
, userHostName :: !ByteString
, userPid :: !Integer
, userLoginTime :: !POSIXTime
, userSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data Swap = Swap
{ swapTotal :: !Integer
, swapUsed :: !Integer
, swapFree :: !Integer
, swapSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
newtype DeviceType = DeviceType CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
data FileSystem = FileSystem
{ fsDeviceName :: !ByteString
, fsType :: !ByteString
, fsMountPoint :: !ByteString
, fsDeviceType :: !DeviceType
, fsSize :: !Integer
, fsUsed :: !Integer
, fsFree :: !Integer
, fsAvail :: !Integer
, fsTotalInodes :: !Integer
, fsUsedInodes :: !Integer
, fsFreeInodes :: !Integer
, fsAvailInodes :: !Integer
, fsIOSize :: !Integer
, fsBlockSize :: !Integer
, fsTotalBlocks :: !Integer
, fsFreeBlocks :: !Integer
, fsUsedBlocks :: !Integer
, fsAvailBlocks :: !Integer
, fsSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data DiskIO = DiskIO
{ diskName :: !ByteString
, diskRead :: !Integer
, diskWrite :: !Integer
, diskSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data NetworkIO = NetworkIO
{ ifaceIOName :: !ByteString
, ifaceTX :: !Integer
, ifaceRX :: !Integer
, ifaceIPackets :: !Integer
, ifaceOPackets :: !Integer
, ifaceIErrors :: !Integer
, ifaceOErrors :: !Integer
, ifaceCollisions :: !Integer
, ifaceSystem :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
newtype InterfaceMode = InterfaceMode CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
newtype InterfaceStatus = InterfaceStatus CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
data NetworkInterface = NetworkInterface
{ ifaceName :: !ByteString
, ifaceSpeed :: !Integer
, ifaceFactor :: !Integer
, ifaceDuplex :: !InterfaceMode
, ifaceUp :: !InterfaceStatus
, ifaceSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data Page = Page
{ pagesIn :: !Integer
, pagesOut :: !Integer
, pagesSysTime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
newtype ProcessState = ProcessState CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
data Process = Process
{ procName :: !ByteString
, procTitle :: !ByteString
, procPid :: !Integer
, procParent :: !Integer
, procPGid :: !Integer
, procSessId :: !Integer
, procUid :: !Integer
, procEUid :: !Integer
, procGid :: !Integer
, procEGid :: !Integer
, procSwitches :: !Integer
, procVoluntary :: !Integer
, procInvoluntary :: !Integer
, procSize :: !Integer
, procResident :: !Integer
, procStart :: !POSIXTime
, procSpent :: !POSIXTime
, procCPUPercent :: !Double
, procNice :: !Integer
, procState :: !ProcessState
, procSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
newtype ProcessSource = ProcessSource CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
data ProcessCount = ProcessCount
{ countTotal :: !Integer
, countRunning :: !Integer
, countSleeping :: !Integer
, countStopped :: !Integer
, countZombie :: !Integer
, countUnknown :: !Integer
, countSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
infixl 4 <%>, <#>, <@>, <!>
(<%>) :: (Integral a, Applicative f) => (Integer -> b) -> a -> f b
(<%>) a b = a <$> pure (toInteger b)
(<#>) :: (Integral a, Applicative f) => f (Integer -> b) -> a -> f b
(<#>) a b = a <*> pure (toInteger b)
(<@>) :: (Fractional a, Real c, Applicative f) => f (a -> b) -> c -> f b
(<@>) a b = a <*> pure (realToFrac b)
(<!>) :: Applicative f => f (a -> b) -> a -> f b
(<!>) a b = a <*> pure b
| null |
https://raw.githubusercontent.com/brendanhay/statgrab/26146944abc99a3ac312b2f557d5762b3a6aebb4/src/System/Statgrab/Internal.hs
|
haskell
|
# LANGUAGE DeriveGeneric #
Module : System.Statgrab.Internal
you can obtain it at /.
Stability : experimental
| Interface types for copying and unmarshalling libstatgrab structs into a
|
# LANGUAGE GeneralizedNewtypeDeriving #
Copyright : ( c ) 2013 - 2015 < >
License : This Source Code Form is subject to the terms of
the Mozilla Public License , v. 2.0 .
A copy of the MPL can be found in the LICENSE file or
Maintainer : < >
Portability : non - portable ( GHC extensions )
more programmer friendly format .
module System.Statgrab.Internal where
import Control.Applicative
import Data.ByteString (ByteString)
import Data.Time.Clock.POSIX
import Foreign
import Foreign.C.Types
import GHC.Generics (Generic)
type Entries = Ptr CSize
newtype Error = Error CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
newtype HostState = HostState CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
data Host = Host
{ hostOsName :: !ByteString
, hostOsRelease :: !ByteString
, hostOsVersion :: !ByteString
, hostPlatform :: !ByteString
, hostName :: !ByteString
, hostBitWidth :: !Integer
, hostState :: !HostState
, hostNCPU :: !Integer
, hostMaxCPU :: !Integer
, hostUptime :: !POSIXTime
, hostSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data CPU = CPU
{ cpuUser :: !Integer
, cpuKernel :: !Integer
, cpuIdle :: !Integer
, cpuIOWait :: !Integer
, cpuSwap :: !Integer
, cpuNice :: !Integer
, cpuTotal :: !Integer
, cpuCtxSwitches :: !Integer
, cpuVoluntaryCtxSwitches :: !Integer
, cpuInvoluntaryCtxSwitches :: !Integer
, cpuSyscalls :: !Integer
, cpuInterrupts :: !Integer
, cpuSoftInterrupts :: !Integer
, cpuSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
newtype CPUPercentSource = CPUPercentSource CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
data CPUPercent = CPUPercent
{ cpuPctUser :: !Double
, cpuPctKernel :: !Double
, cpuPctIdle :: !Double
, cpuPctIOWait :: !Double
, cpuPctSwap :: !Double
, cpuPctNice :: !Double
, cpuPctTimeTaken :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data Memory = Memory
{ memTotal :: !Integer
, memFree :: !Integer
, memUsed :: !Integer
, memCache :: !Integer
, memSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data Load = Load
{ load1 :: !Double
, load5 :: !Double
, load15 :: !Double
, loadSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data User = User
{ userLoginName :: !ByteString
, userRecordId :: !ByteString
, userRecordIdSize :: !Integer
, userDevice :: !ByteString
, userHostName :: !ByteString
, userPid :: !Integer
, userLoginTime :: !POSIXTime
, userSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data Swap = Swap
{ swapTotal :: !Integer
, swapUsed :: !Integer
, swapFree :: !Integer
, swapSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
newtype DeviceType = DeviceType CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
data FileSystem = FileSystem
{ fsDeviceName :: !ByteString
, fsType :: !ByteString
, fsMountPoint :: !ByteString
, fsDeviceType :: !DeviceType
, fsSize :: !Integer
, fsUsed :: !Integer
, fsFree :: !Integer
, fsAvail :: !Integer
, fsTotalInodes :: !Integer
, fsUsedInodes :: !Integer
, fsFreeInodes :: !Integer
, fsAvailInodes :: !Integer
, fsIOSize :: !Integer
, fsBlockSize :: !Integer
, fsTotalBlocks :: !Integer
, fsFreeBlocks :: !Integer
, fsUsedBlocks :: !Integer
, fsAvailBlocks :: !Integer
, fsSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data DiskIO = DiskIO
{ diskName :: !ByteString
, diskRead :: !Integer
, diskWrite :: !Integer
, diskSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data NetworkIO = NetworkIO
{ ifaceIOName :: !ByteString
, ifaceTX :: !Integer
, ifaceRX :: !Integer
, ifaceIPackets :: !Integer
, ifaceOPackets :: !Integer
, ifaceIErrors :: !Integer
, ifaceOErrors :: !Integer
, ifaceCollisions :: !Integer
, ifaceSystem :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
newtype InterfaceMode = InterfaceMode CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
newtype InterfaceStatus = InterfaceStatus CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
data NetworkInterface = NetworkInterface
{ ifaceName :: !ByteString
, ifaceSpeed :: !Integer
, ifaceFactor :: !Integer
, ifaceDuplex :: !InterfaceMode
, ifaceUp :: !InterfaceStatus
, ifaceSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
data Page = Page
{ pagesIn :: !Integer
, pagesOut :: !Integer
, pagesSysTime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
newtype ProcessState = ProcessState CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
data Process = Process
{ procName :: !ByteString
, procTitle :: !ByteString
, procPid :: !Integer
, procParent :: !Integer
, procPGid :: !Integer
, procSessId :: !Integer
, procUid :: !Integer
, procEUid :: !Integer
, procGid :: !Integer
, procEGid :: !Integer
, procSwitches :: !Integer
, procVoluntary :: !Integer
, procInvoluntary :: !Integer
, procSize :: !Integer
, procResident :: !Integer
, procStart :: !POSIXTime
, procSpent :: !POSIXTime
, procCPUPercent :: !Double
, procNice :: !Integer
, procState :: !ProcessState
, procSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
newtype ProcessSource = ProcessSource CInt
deriving
( Eq
, Ord
, Enum
, Bounded
, Integral
, Num
, Real
, Show
, Storable
, Generic
)
data ProcessCount = ProcessCount
{ countTotal :: !Integer
, countRunning :: !Integer
, countSleeping :: !Integer
, countStopped :: !Integer
, countZombie :: !Integer
, countUnknown :: !Integer
, countSystime :: !POSIXTime
} deriving (Eq, Ord, Show, Generic)
infixl 4 <%>, <#>, <@>, <!>
(<%>) :: (Integral a, Applicative f) => (Integer -> b) -> a -> f b
(<%>) a b = a <$> pure (toInteger b)
(<#>) :: (Integral a, Applicative f) => f (Integer -> b) -> a -> f b
(<#>) a b = a <*> pure (toInteger b)
(<@>) :: (Fractional a, Real c, Applicative f) => f (a -> b) -> c -> f b
(<@>) a b = a <*> pure (realToFrac b)
(<!>) :: Applicative f => f (a -> b) -> a -> f b
(<!>) a b = a <*> pure b
|
f9c02c25c0265b8d0a34e48e5cab71451a650f29f48a2686ec39a6ae1a2e197d
|
chenyukang/eopl
|
18.scm
|
(load-relative "../libs/init.scm")
(load-relative "./base/environments.scm")
based on exercises 16
;;; a little similar with let,
;;; but the vals should be a list-exp-val
;;;;;;;;;;;;;;;; grammatical specification ;;;;;;;;;;;;;;;;
(define the-lexical-spec
'((whitespace (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier
(letter (arbno (or letter digit "_" "-" "?")))
symbol)
(number (digit (arbno digit)) number)
(number ("-" digit (arbno digit)) number)
))
(define the-grammar
'((program (expression) a-program)
(expression (identifier) var-exp)
(expression (number) const-exp)
(expression ("-" "(" expression "," expression ")") diff-exp)
(expression ("+" "(" expression "," expression ")") add-exp)
(expression ("*" "(" expression "," expression ")") mult-exp)
(expression ("/" "(" expression "," expression ")") div-exp)
(expression ("zero?" "(" expression ")") zero?-exp)
(expression ("equal?" "(" expression "," expression ")") equal?-exp)
(expression ("less?" "(" expression "," expression ")") less?-exp)
(expression ("greater?" "(" expression "," expression ")") greater?-exp)
(expression ("minus" "(" expression ")") minus-exp)
(expression ("if" expression "then" expression "else" expression) if-exp)
(expression ("cons" "(" expression "," expression ")") cons-exp)
(expression ("car" "(" expression ")") car-exp)
(expression ("cdr" "(" expression ")") cdr-exp)
(expression ("emptylist") emptylist-exp)
(expression ("null?" "(" expression ")") null?-exp)
(expression ("list" "(" (separated-list expression ",") ")" ) list-exp)
(expression ("cond" (arbno expression "==>" expression) "end") cond-exp)
(expression ("print" "(" expression ")") print-exp)
(expression ("let" (arbno identifier "=" expression) "in" expression) let-exp)
(expression ("let*" (arbno identifier "=" expression) "in" expression) let*-exp)
;;new stuff
(expression ("unpack" (arbno identifier) "=" expression "in" expression) unpack-exp)
))
;;;;;;;;;;;;;;;; sllgen boilerplate ;;;;;;;;;;;;;;;;
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define scan&parse
(sllgen:make-string-parser the-lexical-spec the-grammar))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-datatype expression expression?
(var-exp
(id symbol?))
(const-exp
(num number?))
(zero?-exp
(expr expression?))
(equal?-exp
(exp1 expression?)
(exp2 expression?))
(less?-exp
(exp1 expression?)
(exp2 expression?))
(greater?-exp
(exp1 expression?)
(exp2 expression?))
(if-exp
(predicate-exp expression?)
(true-exp expression?)
(false-exp expression?))
(minus-exp
(body-exp expression?))
(diff-exp
(exp1 expression?)
(exp2 expression?))
(add-exp
(exp1 expression?)
(exp2 expression?))
(mult-exp
(exp1 expression?)
(exp2 expression?))
(div-exp
(exp1 expression?)
(exp2 expression?))
(let-exp
(vars (list-of symbols?))
(vals (list-of expression?))
(body expression?))
(let*-exp
(vars (list-of symbols?))
(vals (list-of expression?))
(body expression?))
(emptylist-exp)
(cons-exp
(exp1 expression?)
(exp2 expression?))
(car-exp
(body expression?))
(cdr-exp
(body expression?))
(null?-exp
(body expression?))
(list-exp
(args (list-of expression?)))
(cond-exp
(conds (list-of expression?))
(acts (list-of expression?)))
(unpack-exp
(args (list-of identifier?))
(vals expression?)
(body expression?))
(print-exp
(arg expression?)))
;;; an expressed value is either a number, a boolean or a procval.
(define-datatype expval expval?
(num-val
(value number?))
(bool-val
(boolean boolean?))
(pair-val
(car expval?)
(cdr expval?))
(emptylist-val))
;;; extractors:
;; expval->num : ExpVal -> Int
Page : 70
(define expval->num
(lambda (v)
(cases expval v
(num-val (num) num)
(else (expval-extractor-error 'num v)))))
;; expval->bool : ExpVal -> Bool
Page : 70
(define expval->bool
(lambda (v)
(cases expval v
(bool-val (bool) bool)
(else (expval-extractor-error 'bool v)))))
(define expval->pair
(lambda (val)
(cases expval val
(emptylist-val () '())
(pair-val (car cdr) (cons car (expval->pair cdr)))
(else (error 'expval->pair "Invalid pair: ~s" val)))))
(define expval-car
(lambda (v)
(cases expval v
(pair-val (car cdr) car)
(else (expval-extractor-error 'car v)))))
(define expval-cdr
(lambda (v)
(cases expval v
(pair-val (car cdr) cdr)
(else (expval-extractor-error 'cdr v)))))
(define expval-null?
(lambda (v)
(cases expval v
(emptylist-val () (bool-val #t))
(else (bool-val #f)))))
(define list-val
(lambda (args)
(if (null? args)
(emptylist-val)
(pair-val (car args)
(list-val (cdr args))))))
;;new stuff
(define cond-val
(lambda (conds acts env)
(cond ((null? conds)
(error 'cond-val "No conditions got into #t"))
((expval->bool (value-of (car conds) env))
(value-of (car acts) env))
(else
(cond-val (cdr conds) (cdr acts) env)))))
(define expval-extractor-error
(lambda (variant value)
(error 'expval-extractors "Looking for a ~s, found ~s"
variant value)))
(define value-of-vals
(lambda (vals env)
(if (null? vals)
'()
(cons (value-of (car vals) env)
(value-of-vals (cdr vals) env)))))
(define extend-env-list
(lambda (vars vals env)
(if (null? vars)
env
(let ((var1 (car vars))
(val1 (car vals)))
(extend-env-list (cdr vars) (cdr vals) (extend-env var1 val1 env))))))
(define extend-env-list-exp
(lambda (vars vals env)
(if (null? vars)
env
(let ((var1 (car vars))
(val1 (expval-car vals)))
(extend-env-list-exp (cdr vars)
(expval-cdr vals)
(extend-env var1 val1 env))))))
(define extend-env-list-iter
(lambda(vars vals env)
(if (null? vars)
env
(let ((var1 (car vars))
(val1 (value-of (car vals) env)))
(extend-env-list-iter (cdr vars) (cdr vals)
(extend-env var1 val1 env))))))
;;;;;;;;;;;;;;;; the interpreter ;;;;;;;;;;;;;;;;
value - of - program : Program - > ExpVal
Page : 71
(define value-of-program
(lambda (pgm)
(cases program pgm
(a-program (exp1)
(value-of exp1 (init-env))))))
;; used as map for the list
(define apply-elm
(lambda (env)
(lambda (elem)
(value-of elem env))))
value - of : Exp * Env - > ExpVal
Page : 71
(define value-of
(lambda (exp env)
(cases expression exp
(const-exp (num) (num-val num))
(var-exp (var) (apply-env env var))
(diff-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(num-val
(- num1 num2)))))
(add-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(num-val
(+ num1 num2)))))
(mult-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(num-val
(* num1 num2)))))
(div-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(num-val
(/ num1 num2)))))
(zero?-exp (exp1)
(let ((val1 (value-of exp1 env)))
(let ((num1 (expval->num val1)))
(if (zero? num1)
(bool-val #t)
(bool-val #f)))))
(equal?-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(bool-val
(= num1 num2)))))
(less?-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(bool-val
(< num1 num2)))))
(greater?-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(bool-val
(> num1 num2)))))
(if-exp (exp1 exp2 exp3)
(let ((val1 (value-of exp1 env)))
(if (expval->bool val1)
(value-of exp2 env)
(value-of exp3 env))))
(minus-exp (body-exp)
(let ((val1 (value-of body-exp env)))
(let ((num (expval->num val1)))
(num-val (- 0 num)))))
(let-exp (vars vals body)
(let ((_vals (value-of-vals vals env)))
(value-of body (extend-env-list vars _vals env))))
(let*-exp (vars vals body)
(value-of body (extend-env-list-iter vars vals env)))
(emptylist-exp ()
(emptylist-val))
(cons-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(pair-val val1 val2)))
(car-exp (body)
(expval-car (value-of body env)))
(cdr-exp (body)
(expval-cdr (value-of body env)))
(null?-exp (exp)
(expval-null? (value-of exp env)))
(list-exp (args)
(list-val (map (apply-elm env) args)))
(cond-exp (conds acts)
(cond-val conds acts env))
(print-exp (arg)
(let ((val (value-of arg env)))
(print val)
(num-val 1)))
(unpack-exp (vars vals body)
(let ((_vals (value-of vals env)))
(value-of body (extend-env-list-exp vars _vals env))))
)))
;;
(define run
(lambda (string)
(value-of-program (scan&parse string))))
(run "x")
(run "v")
(run "i")
(run "10")
(run "-(1, 2)")
(run "-(1, x)")
;; (run "foo") -> error
(run "if zero?(-(11, 11)) then 3 else 4")
(run "minus(4)")
(run "if zero?(-(11, 11)) then minus(3) else minus(4)")
(run "+(1, 2)")
(run "+(+(1,2), 3)")
(run "/(1, 2)")
(run "*(*(1,2), *(10, 2))")
(run "if less?(1, 2) then 1 else 2")
(run "if greater?(2, 1) then minus(1) else minus(2)")
(run "cons(1, 2)")
(run "car (cons (1, 2))")
(run "cdr (cons (1, 2))")
(run "null? (emptylist)")
(run "null? (cons (1, 2))")
(run "let x = 4
in cons(x,
cons(cons(-(x,1),
emptylist),
emptylist))")
(run "list(1, 2, 3)")
(run "cdr(list(1, 2, 3))")
(run "let x = 4
in list(x, -(x,1), -(x,3))")
(run "1")
(run "less?(1, 2)")
(run "cond less?(1, 2) ==> 2 end")
(run "cond less?(2, 1) ==> 1 greater?(2, 2) ==> 2 greater?(3, 2) ==> 3 end")
( run " cond less?(2 , 1 ) = = > 1 end " ) = = > error )
( run " print ( less ? ( 1 , 2 ) ) " )
(run "let x = 10
in let x = 20
in +(x, 10)")
(run "let x = 30
in let x = -(x,1)
y = -(x,2)
in -(x, y)")
(run "let x = 30
in let* x = -(x,1)
y = -(x,2)
in -(x, y)")
(run "cons(1, emptylist)")
(run "cons(7,cons(3,emptylist))")
;; new testcase
(run "let u = 7
in unpack x y = cons(u, cons(3,emptylist))
in -(x,y)")
- > ( 4 )
| null |
https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/ch3/18.scm
|
scheme
|
a little similar with let,
but the vals should be a list-exp-val
grammatical specification ;;;;;;;;;;;;;;;;
new stuff
sllgen boilerplate ;;;;;;;;;;;;;;;;
an expressed value is either a number, a boolean or a procval.
extractors:
expval->num : ExpVal -> Int
expval->bool : ExpVal -> Bool
new stuff
the interpreter ;;;;;;;;;;;;;;;;
used as map for the list
(run "foo") -> error
new testcase
|
(load-relative "../libs/init.scm")
(load-relative "./base/environments.scm")
based on exercises 16
(define the-lexical-spec
'((whitespace (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier
(letter (arbno (or letter digit "_" "-" "?")))
symbol)
(number (digit (arbno digit)) number)
(number ("-" digit (arbno digit)) number)
))
(define the-grammar
'((program (expression) a-program)
(expression (identifier) var-exp)
(expression (number) const-exp)
(expression ("-" "(" expression "," expression ")") diff-exp)
(expression ("+" "(" expression "," expression ")") add-exp)
(expression ("*" "(" expression "," expression ")") mult-exp)
(expression ("/" "(" expression "," expression ")") div-exp)
(expression ("zero?" "(" expression ")") zero?-exp)
(expression ("equal?" "(" expression "," expression ")") equal?-exp)
(expression ("less?" "(" expression "," expression ")") less?-exp)
(expression ("greater?" "(" expression "," expression ")") greater?-exp)
(expression ("minus" "(" expression ")") minus-exp)
(expression ("if" expression "then" expression "else" expression) if-exp)
(expression ("cons" "(" expression "," expression ")") cons-exp)
(expression ("car" "(" expression ")") car-exp)
(expression ("cdr" "(" expression ")") cdr-exp)
(expression ("emptylist") emptylist-exp)
(expression ("null?" "(" expression ")") null?-exp)
(expression ("list" "(" (separated-list expression ",") ")" ) list-exp)
(expression ("cond" (arbno expression "==>" expression) "end") cond-exp)
(expression ("print" "(" expression ")") print-exp)
(expression ("let" (arbno identifier "=" expression) "in" expression) let-exp)
(expression ("let*" (arbno identifier "=" expression) "in" expression) let*-exp)
(expression ("unpack" (arbno identifier) "=" expression "in" expression) unpack-exp)
))
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define scan&parse
(sllgen:make-string-parser the-lexical-spec the-grammar))
(define-datatype expression expression?
(var-exp
(id symbol?))
(const-exp
(num number?))
(zero?-exp
(expr expression?))
(equal?-exp
(exp1 expression?)
(exp2 expression?))
(less?-exp
(exp1 expression?)
(exp2 expression?))
(greater?-exp
(exp1 expression?)
(exp2 expression?))
(if-exp
(predicate-exp expression?)
(true-exp expression?)
(false-exp expression?))
(minus-exp
(body-exp expression?))
(diff-exp
(exp1 expression?)
(exp2 expression?))
(add-exp
(exp1 expression?)
(exp2 expression?))
(mult-exp
(exp1 expression?)
(exp2 expression?))
(div-exp
(exp1 expression?)
(exp2 expression?))
(let-exp
(vars (list-of symbols?))
(vals (list-of expression?))
(body expression?))
(let*-exp
(vars (list-of symbols?))
(vals (list-of expression?))
(body expression?))
(emptylist-exp)
(cons-exp
(exp1 expression?)
(exp2 expression?))
(car-exp
(body expression?))
(cdr-exp
(body expression?))
(null?-exp
(body expression?))
(list-exp
(args (list-of expression?)))
(cond-exp
(conds (list-of expression?))
(acts (list-of expression?)))
(unpack-exp
(args (list-of identifier?))
(vals expression?)
(body expression?))
(print-exp
(arg expression?)))
(define-datatype expval expval?
(num-val
(value number?))
(bool-val
(boolean boolean?))
(pair-val
(car expval?)
(cdr expval?))
(emptylist-val))
Page : 70
(define expval->num
(lambda (v)
(cases expval v
(num-val (num) num)
(else (expval-extractor-error 'num v)))))
Page : 70
(define expval->bool
(lambda (v)
(cases expval v
(bool-val (bool) bool)
(else (expval-extractor-error 'bool v)))))
(define expval->pair
(lambda (val)
(cases expval val
(emptylist-val () '())
(pair-val (car cdr) (cons car (expval->pair cdr)))
(else (error 'expval->pair "Invalid pair: ~s" val)))))
(define expval-car
(lambda (v)
(cases expval v
(pair-val (car cdr) car)
(else (expval-extractor-error 'car v)))))
(define expval-cdr
(lambda (v)
(cases expval v
(pair-val (car cdr) cdr)
(else (expval-extractor-error 'cdr v)))))
(define expval-null?
(lambda (v)
(cases expval v
(emptylist-val () (bool-val #t))
(else (bool-val #f)))))
(define list-val
(lambda (args)
(if (null? args)
(emptylist-val)
(pair-val (car args)
(list-val (cdr args))))))
(define cond-val
(lambda (conds acts env)
(cond ((null? conds)
(error 'cond-val "No conditions got into #t"))
((expval->bool (value-of (car conds) env))
(value-of (car acts) env))
(else
(cond-val (cdr conds) (cdr acts) env)))))
(define expval-extractor-error
(lambda (variant value)
(error 'expval-extractors "Looking for a ~s, found ~s"
variant value)))
(define value-of-vals
(lambda (vals env)
(if (null? vals)
'()
(cons (value-of (car vals) env)
(value-of-vals (cdr vals) env)))))
(define extend-env-list
(lambda (vars vals env)
(if (null? vars)
env
(let ((var1 (car vars))
(val1 (car vals)))
(extend-env-list (cdr vars) (cdr vals) (extend-env var1 val1 env))))))
(define extend-env-list-exp
(lambda (vars vals env)
(if (null? vars)
env
(let ((var1 (car vars))
(val1 (expval-car vals)))
(extend-env-list-exp (cdr vars)
(expval-cdr vals)
(extend-env var1 val1 env))))))
(define extend-env-list-iter
(lambda(vars vals env)
(if (null? vars)
env
(let ((var1 (car vars))
(val1 (value-of (car vals) env)))
(extend-env-list-iter (cdr vars) (cdr vals)
(extend-env var1 val1 env))))))
value - of - program : Program - > ExpVal
Page : 71
(define value-of-program
(lambda (pgm)
(cases program pgm
(a-program (exp1)
(value-of exp1 (init-env))))))
(define apply-elm
(lambda (env)
(lambda (elem)
(value-of elem env))))
value - of : Exp * Env - > ExpVal
Page : 71
(define value-of
(lambda (exp env)
(cases expression exp
(const-exp (num) (num-val num))
(var-exp (var) (apply-env env var))
(diff-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(num-val
(- num1 num2)))))
(add-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(num-val
(+ num1 num2)))))
(mult-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(num-val
(* num1 num2)))))
(div-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(num-val
(/ num1 num2)))))
(zero?-exp (exp1)
(let ((val1 (value-of exp1 env)))
(let ((num1 (expval->num val1)))
(if (zero? num1)
(bool-val #t)
(bool-val #f)))))
(equal?-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(bool-val
(= num1 num2)))))
(less?-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(bool-val
(< num1 num2)))))
(greater?-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(let ((num1 (expval->num val1))
(num2 (expval->num val2)))
(bool-val
(> num1 num2)))))
(if-exp (exp1 exp2 exp3)
(let ((val1 (value-of exp1 env)))
(if (expval->bool val1)
(value-of exp2 env)
(value-of exp3 env))))
(minus-exp (body-exp)
(let ((val1 (value-of body-exp env)))
(let ((num (expval->num val1)))
(num-val (- 0 num)))))
(let-exp (vars vals body)
(let ((_vals (value-of-vals vals env)))
(value-of body (extend-env-list vars _vals env))))
(let*-exp (vars vals body)
(value-of body (extend-env-list-iter vars vals env)))
(emptylist-exp ()
(emptylist-val))
(cons-exp (exp1 exp2)
(let ((val1 (value-of exp1 env))
(val2 (value-of exp2 env)))
(pair-val val1 val2)))
(car-exp (body)
(expval-car (value-of body env)))
(cdr-exp (body)
(expval-cdr (value-of body env)))
(null?-exp (exp)
(expval-null? (value-of exp env)))
(list-exp (args)
(list-val (map (apply-elm env) args)))
(cond-exp (conds acts)
(cond-val conds acts env))
(print-exp (arg)
(let ((val (value-of arg env)))
(print val)
(num-val 1)))
(unpack-exp (vars vals body)
(let ((_vals (value-of vals env)))
(value-of body (extend-env-list-exp vars _vals env))))
)))
(define run
(lambda (string)
(value-of-program (scan&parse string))))
(run "x")
(run "v")
(run "i")
(run "10")
(run "-(1, 2)")
(run "-(1, x)")
(run "if zero?(-(11, 11)) then 3 else 4")
(run "minus(4)")
(run "if zero?(-(11, 11)) then minus(3) else minus(4)")
(run "+(1, 2)")
(run "+(+(1,2), 3)")
(run "/(1, 2)")
(run "*(*(1,2), *(10, 2))")
(run "if less?(1, 2) then 1 else 2")
(run "if greater?(2, 1) then minus(1) else minus(2)")
(run "cons(1, 2)")
(run "car (cons (1, 2))")
(run "cdr (cons (1, 2))")
(run "null? (emptylist)")
(run "null? (cons (1, 2))")
(run "let x = 4
in cons(x,
cons(cons(-(x,1),
emptylist),
emptylist))")
(run "list(1, 2, 3)")
(run "cdr(list(1, 2, 3))")
(run "let x = 4
in list(x, -(x,1), -(x,3))")
(run "1")
(run "less?(1, 2)")
(run "cond less?(1, 2) ==> 2 end")
(run "cond less?(2, 1) ==> 1 greater?(2, 2) ==> 2 greater?(3, 2) ==> 3 end")
( run " cond less?(2 , 1 ) = = > 1 end " ) = = > error )
( run " print ( less ? ( 1 , 2 ) ) " )
(run "let x = 10
in let x = 20
in +(x, 10)")
(run "let x = 30
in let x = -(x,1)
y = -(x,2)
in -(x, y)")
(run "let x = 30
in let* x = -(x,1)
y = -(x,2)
in -(x, y)")
(run "cons(1, emptylist)")
(run "cons(7,cons(3,emptylist))")
(run "let u = 7
in unpack x y = cons(u, cons(3,emptylist))
in -(x,y)")
- > ( 4 )
|
8da5b6d7bbf363e8ecd93e79ebb68906807cea969a7aafa5f7607f750deb6ebe
|
kmi/irs
|
irs.lisp
|
Copyright © 2007 - 2010 The Open University
(in-package #:cl-user)
#+:lispworks
(setf system:*stack-overflow-behaviour* :warn)
Lispworks does n't seem to guess UTF-8 files properly , which is a
shame since most files in the IRS are UTF-8 , and the rest are
;;; heading that way. We override its encoding detection for files,
and tell the editor to use UTF-8 .
#+:lispworks
(lw:set-default-character-element-type 'lw:simple-char)
We use UTF-8 encoding for files in the IRS . So , if the pathname
starts with the path in * irs - home * , use UTF-8 . Punt the rest to
;; the next guesser function.
#+:lispworks
(defun irs-file-encoding (pathname ef-spec buffer length)
(let ((home (pathname-directory (pathname *irs-home*))))
(if (= (length home)
(mismatch home (pathname-directory pathname)
:test 'string=))
(list :utf-8 :eol-style :lf)
ef-spec)))
#+:lispworks
(pushnew 'irs-file-encoding sys:*file-encoding-detection-algorithm*)
#+:lispworks
(setf (editor:variable-value "output format default") '(:utf-8)
(editor:variable-value "input format default") '(:utf-8))
(defvar *irs-home*
(let ((pathname (format nil "~A" *load-truename*)))
(subseq pathname 0
(- (length pathname) (length "/scripts/irs.lisp")))))
(defun from-irs-home (partial-path)
(format nil "~A/~A" *irs-home* partial-path))
(setf (logical-pathname-translations "irs")
`(("irs:**;*.*.*" ,(from-irs-home "**/*.*"))))
{ { { QuickLisp
(let ((quicklisp (concatenate 'string *irs-home* "/quicklisp.lisp")))
(when (probe-file quicklisp)
(load quicklisp)
(push :quicklisp *features*)))
#+:quicklisp
(let ((quicklisp-setup (quicklisp-quickstart::qmerge "setup.lisp")))
(if (probe-file quicklisp-setup)
(load quicklisp-setup)
(quicklisp-quickstart:install)))
;;; }}}
;;;; ASDF system definition setup.
(unless (find-package '#:asdf)
(load (translate-logical-pathname
(logical-pathname "irs:external;cl-asdf;asdf.lisp"))))
(defun register-asdf-package (path &key (where :start) (force nil))
"Add a package to the ASDF registry. PATH is a logical pathname.
WHERE can be :start or :end. If FORCE is true, add the PATH even if
it is already in the list. "
(when (or force
(not (member path asdf:*central-registry* :test 'equal)))
(ecase where
(:start (push path asdf:*central-registry*))
(:end (setf asdf:*central-registry*
(append asdf:*central-registry* (list path)))))
asdf:*central-registry*))
Extend Lispworks ' REQUIRE function to look for ASDFs first , and
fall back to looking for Lispworks modules .
#+:lispworks
(sys::without-warning-on-redefinition
(let ((system-require (symbol-function 'require)))
(defun require (module &optional pathname)
(if (or pathname (not (asdf:find-system module nil)))
(funcall system-require module pathname)
(asdf:operate 'asdf:load-op module)))))
(register-asdf-package (translate-logical-pathname
(logical-pathname "irs:src;")))
(register-asdf-package (translate-logical-pathname
(logical-pathname "irs:publisher;")))
(register-asdf-package (translate-logical-pathname
(logical-pathname "irs:tests;")))
(defun directory-contents (logical-dirname)
(directory (logical-pathname
#-:clisp logical-dirname
#+:clisp (format nil "~A;" logical-dirname))))
Check in irs / apps for entries , and register them .
(dolist (app (directory-contents "irs:apps;*"))
(register-asdf-package app))
Prepare to load OCML from external / ocml
(register-asdf-package (translate-logical-pathname
(logical-pathname "irs:external;ocml;")))
(defvar *lisp-suffix* "lisp")
(defun set-irs-home (irs-home)
(let (ocml-home)
(if (eq irs-home :image)
If : image is specified as IRS - HOME , use the directory the
;; image is in.
(let* ((image-path (format nil "~A" (pathname-location (lisp-image-name))))
(pwd
#+:cocoa (subseq image-path 0
(position #\/ image-path :start 0 :end (search "/Contents/MacOS/" image-path)
:from-end t))
#-:cocoa (subseq image-path 0 (- (length image-path) 1))))
(setf irs-home pwd)
(setf ocml-home (format nil "~A/external/ocml" irs-home)))
(setf ocml-home
(let ((path (format nil "~A" (asdf:component-pathname (asdf:find-system :ocml)))))
(subseq path 0 (- (length path) 1)))))
(setf *irs-home* irs-home)
(setf (logical-pathname-translations "irs")
`(("irs:**;*.*.*" ,(from-irs-home "**/*.*"))))
(setf (logical-pathname-translations "ocml")
`(("ocml:library;basic;*.*.*"
,(format nil
#+(or :macosx :unix) "~A/library/basic/*.*"
#+:win32 "~A\\library\\basic\\*.*"
ocml-home))
("ocml:library;**;*.*.*" ,(from-irs-home "ontologies/**/*.*"))))))
We could n't use SET - IRS - HOME to set * irs - home * earlier because the
;;; definition relies on ASDF already being loaded, which can't be
done until * irs - home * is set ...
(set-irs-home *irs-home*)
;;; {{{ Image and deliverable build support
#+:cocoa
(compile-file-if-needed (sys:example-file "configuration/macos-application-bundle") :load t)
(defun executable-name (filename &optional (interface :gui))
#+:cocoa (ecase interface
(:gui (write-macos-application-bundle
(from-irs-home (format nil "~A.app" filename)) :document-types nil))
(:console filename))
#-:cocoa (format nil "~A~A" filename #+:win32 ".exe" #-:win32 ""))
;;; }}}
(eval-when (:load-toplevel :execute)
(push :webonto *features*)
New version of OCML does n't like some of the things IRS makes it
;; do, so persuade it.
(push :irs-ocml-hacks *features*))
Certain components , like Lispweb , WebOnto , CAPI , and a few other
bits , depend heavily on Lispworks . Porting the required
;;; functionality is not realistic, at least not in the short term, so
we selectively disable it based on the : irs - legacy feature .
#+:lispworks (push :irs-lispworks *features*)
The interface provided by is deprecated and not built by
;;; default. Uncomment the next line to enable it.
# + : lispworks(push : irs - use - lispweb * features * )
| null |
https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/scripts/irs.lisp
|
lisp
|
heading that way. We override its encoding detection for files,
the next guesser function.
}}}
ASDF system definition setup.
image is in.
definition relies on ASDF already being loaded, which can't be
{{{ Image and deliverable build support
}}}
do, so persuade it.
functionality is not realistic, at least not in the short term, so
default. Uncomment the next line to enable it.
|
Copyright © 2007 - 2010 The Open University
(in-package #:cl-user)
#+:lispworks
(setf system:*stack-overflow-behaviour* :warn)
Lispworks does n't seem to guess UTF-8 files properly , which is a
shame since most files in the IRS are UTF-8 , and the rest are
and tell the editor to use UTF-8 .
#+:lispworks
(lw:set-default-character-element-type 'lw:simple-char)
We use UTF-8 encoding for files in the IRS . So , if the pathname
starts with the path in * irs - home * , use UTF-8 . Punt the rest to
#+:lispworks
(defun irs-file-encoding (pathname ef-spec buffer length)
(let ((home (pathname-directory (pathname *irs-home*))))
(if (= (length home)
(mismatch home (pathname-directory pathname)
:test 'string=))
(list :utf-8 :eol-style :lf)
ef-spec)))
#+:lispworks
(pushnew 'irs-file-encoding sys:*file-encoding-detection-algorithm*)
#+:lispworks
(setf (editor:variable-value "output format default") '(:utf-8)
(editor:variable-value "input format default") '(:utf-8))
(defvar *irs-home*
(let ((pathname (format nil "~A" *load-truename*)))
(subseq pathname 0
(- (length pathname) (length "/scripts/irs.lisp")))))
(defun from-irs-home (partial-path)
(format nil "~A/~A" *irs-home* partial-path))
(setf (logical-pathname-translations "irs")
`(("irs:**;*.*.*" ,(from-irs-home "**/*.*"))))
{ { { QuickLisp
(let ((quicklisp (concatenate 'string *irs-home* "/quicklisp.lisp")))
(when (probe-file quicklisp)
(load quicklisp)
(push :quicklisp *features*)))
#+:quicklisp
(let ((quicklisp-setup (quicklisp-quickstart::qmerge "setup.lisp")))
(if (probe-file quicklisp-setup)
(load quicklisp-setup)
(quicklisp-quickstart:install)))
(unless (find-package '#:asdf)
(load (translate-logical-pathname
(logical-pathname "irs:external;cl-asdf;asdf.lisp"))))
(defun register-asdf-package (path &key (where :start) (force nil))
"Add a package to the ASDF registry. PATH is a logical pathname.
WHERE can be :start or :end. If FORCE is true, add the PATH even if
it is already in the list. "
(when (or force
(not (member path asdf:*central-registry* :test 'equal)))
(ecase where
(:start (push path asdf:*central-registry*))
(:end (setf asdf:*central-registry*
(append asdf:*central-registry* (list path)))))
asdf:*central-registry*))
Extend Lispworks ' REQUIRE function to look for ASDFs first , and
fall back to looking for Lispworks modules .
#+:lispworks
(sys::without-warning-on-redefinition
(let ((system-require (symbol-function 'require)))
(defun require (module &optional pathname)
(if (or pathname (not (asdf:find-system module nil)))
(funcall system-require module pathname)
(asdf:operate 'asdf:load-op module)))))
(register-asdf-package (translate-logical-pathname
(logical-pathname "irs:src;")))
(register-asdf-package (translate-logical-pathname
(logical-pathname "irs:publisher;")))
(register-asdf-package (translate-logical-pathname
(logical-pathname "irs:tests;")))
(defun directory-contents (logical-dirname)
(directory (logical-pathname
#-:clisp logical-dirname
#+:clisp (format nil "~A;" logical-dirname))))
Check in irs / apps for entries , and register them .
(dolist (app (directory-contents "irs:apps;*"))
(register-asdf-package app))
Prepare to load OCML from external / ocml
(register-asdf-package (translate-logical-pathname
(logical-pathname "irs:external;ocml;")))
(defvar *lisp-suffix* "lisp")
(defun set-irs-home (irs-home)
(let (ocml-home)
(if (eq irs-home :image)
If : image is specified as IRS - HOME , use the directory the
(let* ((image-path (format nil "~A" (pathname-location (lisp-image-name))))
(pwd
#+:cocoa (subseq image-path 0
(position #\/ image-path :start 0 :end (search "/Contents/MacOS/" image-path)
:from-end t))
#-:cocoa (subseq image-path 0 (- (length image-path) 1))))
(setf irs-home pwd)
(setf ocml-home (format nil "~A/external/ocml" irs-home)))
(setf ocml-home
(let ((path (format nil "~A" (asdf:component-pathname (asdf:find-system :ocml)))))
(subseq path 0 (- (length path) 1)))))
(setf *irs-home* irs-home)
(setf (logical-pathname-translations "irs")
`(("irs:**;*.*.*" ,(from-irs-home "**/*.*"))))
(setf (logical-pathname-translations "ocml")
`(("ocml:library;basic;*.*.*"
,(format nil
#+(or :macosx :unix) "~A/library/basic/*.*"
#+:win32 "~A\\library\\basic\\*.*"
ocml-home))
("ocml:library;**;*.*.*" ,(from-irs-home "ontologies/**/*.*"))))))
We could n't use SET - IRS - HOME to set * irs - home * earlier because the
done until * irs - home * is set ...
(set-irs-home *irs-home*)
#+:cocoa
(compile-file-if-needed (sys:example-file "configuration/macos-application-bundle") :load t)
(defun executable-name (filename &optional (interface :gui))
#+:cocoa (ecase interface
(:gui (write-macos-application-bundle
(from-irs-home (format nil "~A.app" filename)) :document-types nil))
(:console filename))
#-:cocoa (format nil "~A~A" filename #+:win32 ".exe" #-:win32 ""))
(eval-when (:load-toplevel :execute)
(push :webonto *features*)
New version of OCML does n't like some of the things IRS makes it
(push :irs-ocml-hacks *features*))
Certain components , like Lispweb , WebOnto , CAPI , and a few other
bits , depend heavily on Lispworks . Porting the required
we selectively disable it based on the : irs - legacy feature .
#+:lispworks (push :irs-lispworks *features*)
The interface provided by is deprecated and not built by
# + : lispworks(push : irs - use - lispweb * features * )
|
33d48d3bb8c6c60d7947fba6ed8154f660119ba3fff4c2c2530e5a6c1664236b
|
pallet/thread-expr
|
thread_expr_test.clj
|
(ns pallet.thread-expr-test
(:use
pallet.thread-expr
clojure.test))
(deftest for->-test
(is (= 7 (-> 1 (for-> [x [1 2 3]] (+ x)))))
(is (= 13 (-> 1 (for-> [x [1 2 3]] (+ x) (+ x)))))
(is (= 1 (-> 1 (for-> [x []] (+ x)))))
(is (= 55 (-> 1 (for-> [x [1 2 3]
y [2 3 4]
:let [z (dec x)]] (+ x y z))))))
(deftest for->>-test
(is (= 7 (->> 1 (for->> [x [1 2 3]] (+ x)))))
(is (= 13 (->> 1 (for->> [x [1 2 3]] (+ x) (+ x)))))
(is (= 1 (->> 1 (for->> [x []] (+ x)))))
(is (= 55 (->> 1 (for->> [x [1 2 3]
y [2 3 4]
:let [z (dec x)]] (+ x y z))))))
(deftest when->test
(is (= 2 (-> 1 (when-> true (+ 1)))))
(is (= 1 (-> 1 (when-> false (+ 1))))))
(deftest when->>test
(is (= 2 (->> 1 (when->> true (+ 1)))))
(is (= 1 (->> 1 (when->> false (+ 1))))))
(deftest when-not->test
(is (= 1 (-> 1 (when-not-> true (+ 1)))))
(is (= 2 (-> 1 (when-not-> false (+ 1))))))
(deftest when-not->>test
(is (= 1 (->> 1 (when-not->> true (+ 1)))))
(is (= 2 (->> 1 (when-not->> false (+ 1))))))
(deftest when-let->test
(is (= 2) (-> 1 (when-let-> [a 1] (+ a))))
(is (= 1) (-> 1 (when-let-> [a nil] (+ a)))))
(deftest when-let->>test
(is (= 2) (->> 1 (when-let->> [a 1] (+ a))))
(is (= 1) (->> 1 (when-let->> [a nil] (+ a)))))
(deftest let->test
(is (= 2) (-> 1 (let-> [a 1] (+ a)))))
(deftest let->>test
(is (= 2) (->> 1 (let->> [a 1] (+ a)))))
(def ^{:dynamic true} *a* 0)
(deftest binding->test
(is (= 2) (-> 1 (binding-> [*a* 1] (+ *a*)))))
(deftest binding->>test
(is (= 2) (->> 1 (binding->> [*a* 1] (+ *a*)))))
(deftest if->test
(is (= 2 (-> 1 (if-> true (+ 1) (+ 2)))))
(is (= 3 (-> 1 (if-> false (+ 1) (+ 2)))))
(is (= 1 (-> 1 (if-> false (+ 1))))))
(deftest if->>test
(is (= 2 (->> 1 (if->> true (+ 1) (+ 2)))))
(is (= 3 (->> 1 (if->> false (+ 1) (+ 2)))))
(is (= 1 (->> 1 (if->> false (+ 1))))))
(deftest if-not->test
(is (= 3 (-> 1 (if-not-> true (+ 1) (+ 2)))))
(is (= 2 (-> 1 (if-not-> false (+ 1) (+ 2))))))
(deftest if-not->>test
(is (= 3 (->> 1 (if-not->> true (+ 1) (+ 2)))))
(is (= 2 (->> 1 (if-not->> false (+ 1) (+ 2))))))
(deftest arg->test
(is (= 6 (-> 2 (arg-> [x] (* (inc x)))))))
(deftest arg->>test
(is (= 6 (->> 2 (arg->> [x] (* (inc x)))))))
(deftest let-with-arg->test
(is (= 3 (-> 1 (let-with-arg-> arg [a 1] (+ a arg))))))
(deftest let-with-arg->>test
(is (= 3 (->> 1 (let-with-arg->> arg [a 1] (+ a arg))))))
(deftest apply->test
(is (= 7 (-> 1 (apply-> + [1 2 3])))))
(deftest apply->>test
(is (= 7 (->> 1 (apply->> + [1 2 3])))))
(deftest apply-map->test
(is (= {:a 1 :b 2} (-> :a (apply-map-> hash-map 1 {:b 2})))))
(deftest apply-map->>test
(is (= {:a 1 :b 2} (->> :a (apply-map->> hash-map 1 {:b 2})))))
(deftest -->test
(is (= 12 (--> 5
(let [y 1]
(for [x (range 3)]
(+ x y)))
(+ 1)))
(= 11 (--> 5
(expose-request-as [x] (+ x))
(+ 1)))))
(deftest -->>test
(is (= 12 (-->> 5
(let [y 1]
(for [x (range 3)]
(+ x y)))
(+ 1)))
(= 11 (-->> 5
(expose-request-as [x] (+ x))
(+ 1)))))
| null |
https://raw.githubusercontent.com/pallet/thread-expr/8db8f9cbf0d1ebf6945e2312c8d46d8191a68c5c/test/pallet/thread_expr_test.clj
|
clojure
|
(ns pallet.thread-expr-test
(:use
pallet.thread-expr
clojure.test))
(deftest for->-test
(is (= 7 (-> 1 (for-> [x [1 2 3]] (+ x)))))
(is (= 13 (-> 1 (for-> [x [1 2 3]] (+ x) (+ x)))))
(is (= 1 (-> 1 (for-> [x []] (+ x)))))
(is (= 55 (-> 1 (for-> [x [1 2 3]
y [2 3 4]
:let [z (dec x)]] (+ x y z))))))
(deftest for->>-test
(is (= 7 (->> 1 (for->> [x [1 2 3]] (+ x)))))
(is (= 13 (->> 1 (for->> [x [1 2 3]] (+ x) (+ x)))))
(is (= 1 (->> 1 (for->> [x []] (+ x)))))
(is (= 55 (->> 1 (for->> [x [1 2 3]
y [2 3 4]
:let [z (dec x)]] (+ x y z))))))
(deftest when->test
(is (= 2 (-> 1 (when-> true (+ 1)))))
(is (= 1 (-> 1 (when-> false (+ 1))))))
(deftest when->>test
(is (= 2 (->> 1 (when->> true (+ 1)))))
(is (= 1 (->> 1 (when->> false (+ 1))))))
(deftest when-not->test
(is (= 1 (-> 1 (when-not-> true (+ 1)))))
(is (= 2 (-> 1 (when-not-> false (+ 1))))))
(deftest when-not->>test
(is (= 1 (->> 1 (when-not->> true (+ 1)))))
(is (= 2 (->> 1 (when-not->> false (+ 1))))))
(deftest when-let->test
(is (= 2) (-> 1 (when-let-> [a 1] (+ a))))
(is (= 1) (-> 1 (when-let-> [a nil] (+ a)))))
(deftest when-let->>test
(is (= 2) (->> 1 (when-let->> [a 1] (+ a))))
(is (= 1) (->> 1 (when-let->> [a nil] (+ a)))))
(deftest let->test
(is (= 2) (-> 1 (let-> [a 1] (+ a)))))
(deftest let->>test
(is (= 2) (->> 1 (let->> [a 1] (+ a)))))
(def ^{:dynamic true} *a* 0)
(deftest binding->test
(is (= 2) (-> 1 (binding-> [*a* 1] (+ *a*)))))
(deftest binding->>test
(is (= 2) (->> 1 (binding->> [*a* 1] (+ *a*)))))
(deftest if->test
(is (= 2 (-> 1 (if-> true (+ 1) (+ 2)))))
(is (= 3 (-> 1 (if-> false (+ 1) (+ 2)))))
(is (= 1 (-> 1 (if-> false (+ 1))))))
(deftest if->>test
(is (= 2 (->> 1 (if->> true (+ 1) (+ 2)))))
(is (= 3 (->> 1 (if->> false (+ 1) (+ 2)))))
(is (= 1 (->> 1 (if->> false (+ 1))))))
(deftest if-not->test
(is (= 3 (-> 1 (if-not-> true (+ 1) (+ 2)))))
(is (= 2 (-> 1 (if-not-> false (+ 1) (+ 2))))))
(deftest if-not->>test
(is (= 3 (->> 1 (if-not->> true (+ 1) (+ 2)))))
(is (= 2 (->> 1 (if-not->> false (+ 1) (+ 2))))))
(deftest arg->test
(is (= 6 (-> 2 (arg-> [x] (* (inc x)))))))
(deftest arg->>test
(is (= 6 (->> 2 (arg->> [x] (* (inc x)))))))
(deftest let-with-arg->test
(is (= 3 (-> 1 (let-with-arg-> arg [a 1] (+ a arg))))))
(deftest let-with-arg->>test
(is (= 3 (->> 1 (let-with-arg->> arg [a 1] (+ a arg))))))
(deftest apply->test
(is (= 7 (-> 1 (apply-> + [1 2 3])))))
(deftest apply->>test
(is (= 7 (->> 1 (apply->> + [1 2 3])))))
(deftest apply-map->test
(is (= {:a 1 :b 2} (-> :a (apply-map-> hash-map 1 {:b 2})))))
(deftest apply-map->>test
(is (= {:a 1 :b 2} (->> :a (apply-map->> hash-map 1 {:b 2})))))
(deftest -->test
(is (= 12 (--> 5
(let [y 1]
(for [x (range 3)]
(+ x y)))
(+ 1)))
(= 11 (--> 5
(expose-request-as [x] (+ x))
(+ 1)))))
(deftest -->>test
(is (= 12 (-->> 5
(let [y 1]
(for [x (range 3)]
(+ x y)))
(+ 1)))
(= 11 (-->> 5
(expose-request-as [x] (+ x))
(+ 1)))))
|
|
9f8386f4502f55062be5ecc8fd80c56fcd1a31ee7f04526cf396b24036aebbc1
|
racket/racket7
|
letrec.rkt
|
#lang racket/base
(require "wrap.rkt"
"infer-known.rkt")
(provide letrec-splitable-values-binding?
letrec-split-values-binding)
;; Detect binding of lambdas that were probably generated from an
;; R[56]RS program
(define (letrec-splitable-values-binding? idss rhss)
(and (pair? idss)
(null? (cdr idss))
(wrap-pair? (car rhss))
(eq? 'values (wrap-car (car rhss)))
(= (length (wrap-cdr (car rhss)))
(length (car idss)))
(for/and ([rhs (in-list (wrap-cdr (car rhss)))])
(lambda? rhs #:simple? #t))))
(define (letrec-split-values-binding idss rhss bodys)
`(letrec-values ,(for/list ([id (in-list (car idss))]
[rhs (in-list (wrap-cdr (car rhss)))])
`[(,id) ,rhs])
. ,bodys))
| null |
https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/schemify/letrec.rkt
|
racket
|
Detect binding of lambdas that were probably generated from an
R[56]RS program
|
#lang racket/base
(require "wrap.rkt"
"infer-known.rkt")
(provide letrec-splitable-values-binding?
letrec-split-values-binding)
(define (letrec-splitable-values-binding? idss rhss)
(and (pair? idss)
(null? (cdr idss))
(wrap-pair? (car rhss))
(eq? 'values (wrap-car (car rhss)))
(= (length (wrap-cdr (car rhss)))
(length (car idss)))
(for/and ([rhs (in-list (wrap-cdr (car rhss)))])
(lambda? rhs #:simple? #t))))
(define (letrec-split-values-binding idss rhss bodys)
`(letrec-values ,(for/list ([id (in-list (car idss))]
[rhs (in-list (wrap-cdr (car rhss)))])
`[(,id) ,rhs])
. ,bodys))
|
d17038d8b981c4e0c551e21efa18a7347b2268afb87a65eab81246c630d5a134
|
rtoy/ansi-cl-tests
|
remf.lsp
|
;-*- Mode: Lisp -*-
Author :
Created : Sun Apr 20 07:38:18 2003
;;;; Contains: Tests of REMF
(in-package :cl-test)
(compile-and-load "cons-aux.lsp")
(deftest remf.1
(let ((x nil))
(values (remf x 'a) x))
nil ())
(deftest remf.2
(let ((x (list 'a 'b)))
(values (not (null (remf x 'a))) x))
t ())
(deftest remf.3
(let ((x (list 'a 'b 'a 'c)))
(values (not (null (remf x 'a))) x))
t (a c))
(deftest remf.4
(let ((x (list 'a 'b 'c 'd)))
(values
(and (remf x 'c) t)
(loop
for ptr on x by #'cddr count
(not (eqt (car ptr) 'a)))))
t 0)
;;; Test that explicit calls to macroexpand in subforms
;;; are done in the correct environment
(deftest remf.5
(macrolet
((%m (z) z))
(let ((x nil))
(values
(remf (expand-in-current-env (%m x)) 'a)
x)))
nil nil)
(deftest remf.6
(macrolet
((%m (z) z))
(let ((x (list 'a 'b)))
(values
(notnot (remf (expand-in-current-env (%m x)) 'a))
x)))
t nil)
(deftest remf.7
(macrolet
((%m (z) z))
(let ((x (list 'a 'b 'c 'd)))
(values
(notnot (remf x (expand-in-current-env (%m 'a))))
x)))
t (c d))
(deftest remf.order.1
(let ((i 0) x y
(p (make-array 1 :initial-element (copy-list '(a b c d e f)))))
(values
(notnot
(remf (aref p (progn (setf x (incf i)) 0))
(progn (setf y (incf i))
'c)))
(aref p 0)
i x y))
t (a b e f) 2 1 2)
(deftest remf.order.2
(let ((x (copy-seq #(nil :a :b)))
(pa (vector (list :a 1) (list :b 2) (list :c 3) (list :d 4)))
(i 0))
(values
(not (remf (aref pa (incf i)) (aref x (incf i))))
pa))
nil #((:a 1) nil (:c 3) (:d 4)))
(deftest remf.order.3
(let ((x (list 'a 'b 'c 'd)))
(progn
"See CLtS 5.1.3"
(values
(remf x (progn (setq x (list 'e 'f)) 'a))
x)))
nil (e f))
(def-macro-test remf.error.1 (remf x 'a))
| null |
https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/remf.lsp
|
lisp
|
-*- Mode: Lisp -*-
Contains: Tests of REMF
Test that explicit calls to macroexpand in subforms
are done in the correct environment
|
Author :
Created : Sun Apr 20 07:38:18 2003
(in-package :cl-test)
(compile-and-load "cons-aux.lsp")
(deftest remf.1
(let ((x nil))
(values (remf x 'a) x))
nil ())
(deftest remf.2
(let ((x (list 'a 'b)))
(values (not (null (remf x 'a))) x))
t ())
(deftest remf.3
(let ((x (list 'a 'b 'a 'c)))
(values (not (null (remf x 'a))) x))
t (a c))
(deftest remf.4
(let ((x (list 'a 'b 'c 'd)))
(values
(and (remf x 'c) t)
(loop
for ptr on x by #'cddr count
(not (eqt (car ptr) 'a)))))
t 0)
(deftest remf.5
(macrolet
((%m (z) z))
(let ((x nil))
(values
(remf (expand-in-current-env (%m x)) 'a)
x)))
nil nil)
(deftest remf.6
(macrolet
((%m (z) z))
(let ((x (list 'a 'b)))
(values
(notnot (remf (expand-in-current-env (%m x)) 'a))
x)))
t nil)
(deftest remf.7
(macrolet
((%m (z) z))
(let ((x (list 'a 'b 'c 'd)))
(values
(notnot (remf x (expand-in-current-env (%m 'a))))
x)))
t (c d))
(deftest remf.order.1
(let ((i 0) x y
(p (make-array 1 :initial-element (copy-list '(a b c d e f)))))
(values
(notnot
(remf (aref p (progn (setf x (incf i)) 0))
(progn (setf y (incf i))
'c)))
(aref p 0)
i x y))
t (a b e f) 2 1 2)
(deftest remf.order.2
(let ((x (copy-seq #(nil :a :b)))
(pa (vector (list :a 1) (list :b 2) (list :c 3) (list :d 4)))
(i 0))
(values
(not (remf (aref pa (incf i)) (aref x (incf i))))
pa))
nil #((:a 1) nil (:c 3) (:d 4)))
(deftest remf.order.3
(let ((x (list 'a 'b 'c 'd)))
(progn
"See CLtS 5.1.3"
(values
(remf x (progn (setq x (list 'e 'f)) 'a))
x)))
nil (e f))
(def-macro-test remf.error.1 (remf x 'a))
|
9cf34b91f0cd125ed26c3e2c02761e4a80a32c7dcfa60fe40b8fdab506f98619
|
avsm/mirage-duniverse
|
introduce.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.
*)
type address = {
domid: int;
mfn: nativeint;
remote_port: int;
}
let (stream: address Lwt_stream.t), introduce_fn = Lwt_stream.create ()
let introduce x = introduce_fn (Some x)
| null |
https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/xenstore/server/introduce.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.
*)
type address = {
domid: int;
mfn: nativeint;
remote_port: int;
}
let (stream: address Lwt_stream.t), introduce_fn = Lwt_stream.create ()
let introduce x = introduce_fn (Some x)
|
|
8e8bba2eced3787a6a28a9f07d06885614ac6d28fc03c9b8b57551dd991db185
|
matsen/pplacer
|
test_rerooting.ml
|
open Ppatteries
open OUnit
open Test_util
open Convex
let suite = List.map
(fun (before, reroot_at, after) ->
let before' = Newick_gtree.of_string before
and after' = Newick_gtree.of_string after in
Printf.sprintf "%s@%d" before reroot_at >:: fun () ->
before'
|> Gtree.get_stree
|> flip Stree.reroot reroot_at
|> Gtree.set_stree before'
|> (fun got ->
"failed to verify stree rerooting"
@? (Gtree.get_stree got = Gtree.get_stree after'));
let got = Gtree.reroot before' reroot_at in
"failed to verify gtree rerooting" @? (gtree_equal got after'))
[
"((A,B):2,(C,D):3,E):0", 2, "(((C{3},D{4}):3{5},E{6}):2{7},A{0},B{1}):0{2}";
"((A,B),(C,D):2,E)", 5, "(((A{0},B{1}){2},E{6}):2{7},C{3},D{4}){5}";
"((A,B),(C,D),E)", 7, "((A,B),(C,D),E)";
]
| null |
https://raw.githubusercontent.com/matsen/pplacer/f40a363e962cca7131f1f2d372262e0081ff1190/tests/pplacer/test_rerooting.ml
|
ocaml
|
open Ppatteries
open OUnit
open Test_util
open Convex
let suite = List.map
(fun (before, reroot_at, after) ->
let before' = Newick_gtree.of_string before
and after' = Newick_gtree.of_string after in
Printf.sprintf "%s@%d" before reroot_at >:: fun () ->
before'
|> Gtree.get_stree
|> flip Stree.reroot reroot_at
|> Gtree.set_stree before'
|> (fun got ->
"failed to verify stree rerooting"
@? (Gtree.get_stree got = Gtree.get_stree after'));
let got = Gtree.reroot before' reroot_at in
"failed to verify gtree rerooting" @? (gtree_equal got after'))
[
"((A,B):2,(C,D):3,E):0", 2, "(((C{3},D{4}):3{5},E{6}):2{7},A{0},B{1}):0{2}";
"((A,B),(C,D):2,E)", 5, "(((A{0},B{1}){2},E{6}):2{7},C{3},D{4}){5}";
"((A,B),(C,D),E)", 7, "((A,B),(C,D),E)";
]
|
|
9d3dea6434a5674fce5b1d04e0eb255445af067ba690e9332f6022647cb96042
|
Plisp/vico
|
interface.lisp
|
(in-package :vico-tickit)
(defconstant +tickit-window-popup+
(cffi:foreign-enum-value 'tkt:tickitwindowflags :tickit-window-popup))
;;; state class
(defclass tickit-instance ()
((%tickit :initarg :%tickit
:reader %tickit
:documentation "")
(windows :initarg :buffers
:type list
:documentation "")
(buffers :initarg :buffers
:type list
:documentation "")))
do not allow modification of the list through rplaca / d and such
(defmethod core:windows ((instance tickit-instance))
(copy-list (slot-value instance 'windows)))
(defmethod (setf core:windows) (new-value (instance tickit-instance))
(setf (slot-value instance 'windows) new-value))
(defmethod core:buffers ((instance tickit-instance))
(copy-list (slot-value instance 'buffers)))
(defmethod (setf core:buffers) (new-value (instance tickit-instance))
(setf (slot-value instance 'buffers) new-value))
;;; timers
(defstruct timer
callback)
( defmethod core : make - timer ( ( instance tickit - instance ) function )
( cffi : ) )
( defmethod core : schedule - timer ( ( timer tickit - timer ) delay & key repeat )
;; ())
( defmethod core : unschedule - timer ( ( timer tickit - timer ) )
;; (tkt:tickit-watch-cancel))
;;; window interface
(defclass tickit-window (core:window)
((%tickit-window :initarg :%tickit-window
:reader %tickit-window
:documentation "")
(buffer :initarg :buffer
:accessor buffer
:documentation "")))
TODO need way of querying floating status ?
(defmethod core:make-window ((instance tickit-instance) x y dx dy
&key buffer (floating nil))
(cffi:with-foreign-object (rect '(:struct tkt:tickitrect))
(setf (cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:top) y
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:left) x
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:lines) dy
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:cols) dx)
(let* ((flags (if floating +tickit-window-popup+ 0))
(new (tkt:tickit-window-new-ptr
(tkt:tickit-get-rootwin (%tickit-window instance)) rect flags)))
(push (make-instance 'tickit-window :%tickit-window new :buffer buffer)
(core:buffers instance)))))
(defmethod core:window-buffer ((window tickit-window))
(buffer window))
(defmethod core:window-x ((window tickit-window))
(let ((rect (tkt:tickit-window-get-geometry-ptr (%tickit-window window))))
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:left)
(cffi:foreign-free rect)))
(defmethod core:window-y ((window tickit-window))
(let ((rect (tkt:tickit-window-get-geometry-ptr (%tickit-window window))))
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:top)
(cffi:foreign-free rect)))
(defmethod core:window-width ((window tickit-window))
(let ((rect (tkt:tickit-window-get-geometry-ptr (%tickit-window window))))
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:cols)
(cffi:foreign-free rect)))
(defmethod core:window-height ((window tickit-window))
(let ((rect (tkt:tickit-window-get-geometry-ptr (%tickit-window window))))
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:lines)
(cffi:foreign-free rect)))
(defmethod core:window-string-width ((window tickit-window) string)
(loop :for c across string
NUL is ^@
((= (char-code c) 9) 8) ; TODO tab character
(t
(let ((width (vico-tickit.util:wide-character-width c)))
(if (= width -1)
2 ; control characters are displayed as ^*
width))))))
(defmethod core:window-line-height ((window tickit-window))
1)
(defmethod core:move-window ((window tickit-window) x y)
(tkt:tickit-window-reposition (%tickit-window window) x y))
(defmethod core:resize-window ((window tickit-window) width height)
(tkt:tickit-window-resize (%tickit-window window) height width))
(defmethod core:raise-window ((window tickit-window))
(tkt:tickit-window-raise (%tickit-window window)))
(defmethod core:lower-window ((window tickit-window))
(tkt:tickit-window-lower (%tickit-window window)))
;; TODO computation of changed region
(defmethod core:redisplay-window ((window tickit-window) &optional (force-p t))
(if force-p
(let ((rect (tkt:tickit-window-get-geometry-ptr (%tickit-window window))))
(tkt:tickit-window-expose (%tickit-window window) rect))
()))
| null |
https://raw.githubusercontent.com/Plisp/vico/40606aea583ef9db98941ee337feb47f10c9696c/ui/tickit/interface.lisp
|
lisp
|
state class
timers
())
(tkt:tickit-watch-cancel))
window interface
TODO tab character
control characters are displayed as ^*
TODO computation of changed region
|
(in-package :vico-tickit)
(defconstant +tickit-window-popup+
(cffi:foreign-enum-value 'tkt:tickitwindowflags :tickit-window-popup))
(defclass tickit-instance ()
((%tickit :initarg :%tickit
:reader %tickit
:documentation "")
(windows :initarg :buffers
:type list
:documentation "")
(buffers :initarg :buffers
:type list
:documentation "")))
do not allow modification of the list through rplaca / d and such
(defmethod core:windows ((instance tickit-instance))
(copy-list (slot-value instance 'windows)))
(defmethod (setf core:windows) (new-value (instance tickit-instance))
(setf (slot-value instance 'windows) new-value))
(defmethod core:buffers ((instance tickit-instance))
(copy-list (slot-value instance 'buffers)))
(defmethod (setf core:buffers) (new-value (instance tickit-instance))
(setf (slot-value instance 'buffers) new-value))
(defstruct timer
callback)
( defmethod core : make - timer ( ( instance tickit - instance ) function )
( cffi : ) )
( defmethod core : schedule - timer ( ( timer tickit - timer ) delay & key repeat )
( defmethod core : unschedule - timer ( ( timer tickit - timer ) )
(defclass tickit-window (core:window)
((%tickit-window :initarg :%tickit-window
:reader %tickit-window
:documentation "")
(buffer :initarg :buffer
:accessor buffer
:documentation "")))
TODO need way of querying floating status ?
(defmethod core:make-window ((instance tickit-instance) x y dx dy
&key buffer (floating nil))
(cffi:with-foreign-object (rect '(:struct tkt:tickitrect))
(setf (cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:top) y
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:left) x
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:lines) dy
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:cols) dx)
(let* ((flags (if floating +tickit-window-popup+ 0))
(new (tkt:tickit-window-new-ptr
(tkt:tickit-get-rootwin (%tickit-window instance)) rect flags)))
(push (make-instance 'tickit-window :%tickit-window new :buffer buffer)
(core:buffers instance)))))
(defmethod core:window-buffer ((window tickit-window))
(buffer window))
(defmethod core:window-x ((window tickit-window))
(let ((rect (tkt:tickit-window-get-geometry-ptr (%tickit-window window))))
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:left)
(cffi:foreign-free rect)))
(defmethod core:window-y ((window tickit-window))
(let ((rect (tkt:tickit-window-get-geometry-ptr (%tickit-window window))))
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:top)
(cffi:foreign-free rect)))
(defmethod core:window-width ((window tickit-window))
(let ((rect (tkt:tickit-window-get-geometry-ptr (%tickit-window window))))
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:cols)
(cffi:foreign-free rect)))
(defmethod core:window-height ((window tickit-window))
(let ((rect (tkt:tickit-window-get-geometry-ptr (%tickit-window window))))
(cffi:foreign-slot-value rect '(:struct tkt:tickitrect) 'tkt:lines)
(cffi:foreign-free rect)))
(defmethod core:window-string-width ((window tickit-window) string)
(loop :for c across string
NUL is ^@
(t
(let ((width (vico-tickit.util:wide-character-width c)))
(if (= width -1)
width))))))
(defmethod core:window-line-height ((window tickit-window))
1)
(defmethod core:move-window ((window tickit-window) x y)
(tkt:tickit-window-reposition (%tickit-window window) x y))
(defmethod core:resize-window ((window tickit-window) width height)
(tkt:tickit-window-resize (%tickit-window window) height width))
(defmethod core:raise-window ((window tickit-window))
(tkt:tickit-window-raise (%tickit-window window)))
(defmethod core:lower-window ((window tickit-window))
(tkt:tickit-window-lower (%tickit-window window)))
(defmethod core:redisplay-window ((window tickit-window) &optional (force-p t))
(if force-p
(let ((rect (tkt:tickit-window-get-geometry-ptr (%tickit-window window))))
(tkt:tickit-window-expose (%tickit-window window) rect))
()))
|
ba59b4700e614f221d0494c72bdfb824a390c323151f7663b75453f0c96e89bf
|
ocaml/ocamlbuild
|
d.ml
|
(***********************************************************************)
(* *)
(* ocamlbuild *)
(* *)
, , projet Gallium , INRIA Rocquencourt
(* *)
Copyright 2007 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
Format.printf "C.B.b = %d@." C.B.b
| null |
https://raw.githubusercontent.com/ocaml/ocamlbuild/792b7c8abdbc712c98ed7e69469ed354b87e125b/test/test5/d.ml
|
ocaml
|
*********************************************************************
ocamlbuild
the special exception on linking described in file ../LICENSE.
*********************************************************************
|
, , projet Gallium , INRIA Rocquencourt
Copyright 2007 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
Format.printf "C.B.b = %d@." C.B.b
|
0c1f60e62ec9e49e49a7b2c0957b804b3e512676a53b860c93ad0e7dffac91c9
|
forward/incanter-BLAS
|
internal.clj
|
;;; internal.clj -- Internal functions
by
April 19 , 2009
Copyright ( c ) , 2009 . All rights reserved . The use
and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.htincanter.at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
CHANGE LOG
April 19 , 2009 : First version
(ns incanter.internal
(:import [uk.co.forward.clojure.incanter DoubleFunction DoubleDoubleFunction DoubleFunctions])
(:import (incanter Matrix)))
(derive Matrix ::matrix)
(defn is-matrix
" Test if obj is 'derived' from ::matrix (e.g. class incanter.Matrix)."
([obj] (isa? (class obj) ::matrix)))
(defn make-matrix
([data]
(cond
(coll? (first data))
(Matrix. (into-array (map double-array data)))
(number? (first data))
(Matrix. (double-array data))))
([data ncol]
(cond
(or (coll? data) (.isArray (class data)))
(Matrix. (double-array data) ncol)
(number? data)
(Matrix. data ncol))) ; data is the number of rows in this case
([init-val rows cols]
(Matrix. rows cols init-val)))
(defmacro ^Matrix transform-with [A op fun]
`(cond
(is-matrix ~A)
(.assign (.copy ~A) (. DoubleFunctions ~fun))
(and (coll? ~A) (coll? (first ~A)))
(.assign ^Matrix (make-matrix ~A) (. DoubleFunctions ~fun))
(coll? ~A)
(map ~op ~A)
(number? ~A)
(~op ~A)))
(defmacro combine-with [A B op fun]
`(cond
(and (number? ~A) (number? ~B))
(~op ~A ~B)
(and (is-matrix ~A) (is-matrix ~B))
(.assign ^Matrix (.copy ^Matrix ~A)
^Matrix ~B
^DoubleDoubleFunction (. DoubleFunctions ~fun))
(and (is-matrix ~A) (number? ~B))
(.assign ^Matrix (.copy ^Matrix ~A)
(make-matrix ~B (.rows ~A) (.columns ~A))
^DoubleDoubleFunction (. DoubleFunctions ~fun))
(and (number? ~A) (is-matrix ~B))
(.assign ^Matrix (make-matrix ~A (.rows ~B) (.columns ~B))
^Matrix ~B
^DoubleDoubleFunction (. DoubleFunctions ~fun))
(and (coll? ~A) (is-matrix ~B))
(.assign ^Matrix (make-matrix ~A (.columns ~B))
^Matrix (make-matrix ~B)
^DoubleDoubleFunction (. DoubleFunctions ~fun))
(and (is-matrix ~A) (coll? ~B))
(.assign ^Matrix (.copy ~A)
^Matrix (make-matrix ~B)
^DoubleDoubleFunction (. DoubleFunctions ~fun))
(and (coll? ~A) (coll? ~B) (coll? (first ~A)))
(.assign (make-matrix ~A)
(make-matrix ~B)
(. DoubleFunctions ~fun))
(and (coll? ~A) (number? ~B) (coll? (first ~A)))
(.assign (make-matrix ~A)
(make-matrix ~B)
(. DoubleFunctions ~fun))
;;(. DoubleFunctions (~fun ~B)))
(and (number? ~A) (coll? ~B) (coll? (first ~B)))
(.assign (make-matrix ~A (.rows ~B) (.columns ~B))
(make-matrix ~B)
(. DoubleFunctions ~fun))
(and (coll? ~A) (coll? ~B))
(map ~op ~A ~B)
(and (number? ~A) (coll? ~B))
;(make-matrix (map ~op ~A ~B))
(map ~op (replicate (count ~B) ~A) ~B)
;(make-matrix (map ~op (replicate (count ~B) ~A) ~B))
(and (coll? ~A) (number? ~B))
(map ~op ~A (replicate (count ~A) ~B))
;(make-matrix (map ~op ~A (replicate (count ~A) ~B)))
))
;; PRINT METHOD FOR COLT MATRICES
(defmethod print-method Matrix [o, ^java.io.Writer w]
;(let [formatter (DoubleFormatter. "%1.4f")]
(do
( .setPrintShape formatter false )
(.write w "[")
(.write w (.toString o))
(.write w "]\n"))
;)
)
| null |
https://raw.githubusercontent.com/forward/incanter-BLAS/da48558cc9d8296b775d8e88de532a4897ee966e/src/main/clojure/incanter/internal.clj
|
clojure
|
internal.clj -- Internal functions
Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.htincanter.at the root of this
distribution. By using this software in any fashion, you are
agreeing to be bound by the terms of this license. You must not
remove this notice, or any other, from this software.
data is the number of rows in this case
(. DoubleFunctions (~fun ~B)))
(make-matrix (map ~op ~A ~B))
(make-matrix (map ~op (replicate (count ~B) ~A) ~B))
(make-matrix (map ~op ~A (replicate (count ~A) ~B)))
PRINT METHOD FOR COLT MATRICES
(let [formatter (DoubleFormatter. "%1.4f")]
)
|
by
April 19 , 2009
Copyright ( c ) , 2009 . All rights reserved . The use
and distribution terms for this software are covered by the Eclipse
CHANGE LOG
April 19 , 2009 : First version
(ns incanter.internal
(:import [uk.co.forward.clojure.incanter DoubleFunction DoubleDoubleFunction DoubleFunctions])
(:import (incanter Matrix)))
(derive Matrix ::matrix)
(defn is-matrix
" Test if obj is 'derived' from ::matrix (e.g. class incanter.Matrix)."
([obj] (isa? (class obj) ::matrix)))
(defn make-matrix
([data]
(cond
(coll? (first data))
(Matrix. (into-array (map double-array data)))
(number? (first data))
(Matrix. (double-array data))))
([data ncol]
(cond
(or (coll? data) (.isArray (class data)))
(Matrix. (double-array data) ncol)
(number? data)
([init-val rows cols]
(Matrix. rows cols init-val)))
(defmacro ^Matrix transform-with [A op fun]
`(cond
(is-matrix ~A)
(.assign (.copy ~A) (. DoubleFunctions ~fun))
(and (coll? ~A) (coll? (first ~A)))
(.assign ^Matrix (make-matrix ~A) (. DoubleFunctions ~fun))
(coll? ~A)
(map ~op ~A)
(number? ~A)
(~op ~A)))
(defmacro combine-with [A B op fun]
`(cond
(and (number? ~A) (number? ~B))
(~op ~A ~B)
(and (is-matrix ~A) (is-matrix ~B))
(.assign ^Matrix (.copy ^Matrix ~A)
^Matrix ~B
^DoubleDoubleFunction (. DoubleFunctions ~fun))
(and (is-matrix ~A) (number? ~B))
(.assign ^Matrix (.copy ^Matrix ~A)
(make-matrix ~B (.rows ~A) (.columns ~A))
^DoubleDoubleFunction (. DoubleFunctions ~fun))
(and (number? ~A) (is-matrix ~B))
(.assign ^Matrix (make-matrix ~A (.rows ~B) (.columns ~B))
^Matrix ~B
^DoubleDoubleFunction (. DoubleFunctions ~fun))
(and (coll? ~A) (is-matrix ~B))
(.assign ^Matrix (make-matrix ~A (.columns ~B))
^Matrix (make-matrix ~B)
^DoubleDoubleFunction (. DoubleFunctions ~fun))
(and (is-matrix ~A) (coll? ~B))
(.assign ^Matrix (.copy ~A)
^Matrix (make-matrix ~B)
^DoubleDoubleFunction (. DoubleFunctions ~fun))
(and (coll? ~A) (coll? ~B) (coll? (first ~A)))
(.assign (make-matrix ~A)
(make-matrix ~B)
(. DoubleFunctions ~fun))
(and (coll? ~A) (number? ~B) (coll? (first ~A)))
(.assign (make-matrix ~A)
(make-matrix ~B)
(. DoubleFunctions ~fun))
(and (number? ~A) (coll? ~B) (coll? (first ~B)))
(.assign (make-matrix ~A (.rows ~B) (.columns ~B))
(make-matrix ~B)
(. DoubleFunctions ~fun))
(and (coll? ~A) (coll? ~B))
(map ~op ~A ~B)
(and (number? ~A) (coll? ~B))
(map ~op (replicate (count ~B) ~A) ~B)
(and (coll? ~A) (number? ~B))
(map ~op ~A (replicate (count ~A) ~B))
))
(defmethod print-method Matrix [o, ^java.io.Writer w]
(do
( .setPrintShape formatter false )
(.write w "[")
(.write w (.toString o))
(.write w "]\n"))
)
|
5c07b796acbfe9366f3ca1008ad627d196ffc42639758c4c2555329b62deb62b
|
gator1/jepsen
|
client.clj
|
(ns jepsen.cockroach.client
"For talking to cockroachdb over the network"
(:require [clojure.tools.logging :refer :all]
[clojure.java.jdbc :as j]
[clojure.string :as str]
[clojure.pprint :refer [pprint]]
[jepsen [util :as util :refer [meh]]
[reconnect :as rc]]
[jepsen.cockroach [auto :as auto :refer [cockroach-user
cockroach
jdbc-mode
db-port
insecure
db-user
db-passwd
store-path
dbname
verlog
log-files
pcaplog]]]))
(def timeout-delay "Default timeout for operations in ms" 10000)
(def max-timeout "Longest timeout, in ms" 30000)
(def isolation-level "Default isolation level for txns" :serializable)
;; for secure mode
(def client-cert "certs/node.client.crt")
(def client-key "certs/node.client.pk8")
(def ca-cert "certs/ca.crt")
;; Postgres user and dbname for jdbc-mode = :pg-*
(def pg-user "kena") ; must already exist
(def pg-passwd "kena") ; must already exist
(def pg-dbname "mydb") ; must already exist
(def ssl-settings
(if insecure
""
(str "?ssl=true"
"&sslcert=" client-cert
"&sslkey=" client-key
"&sslrootcert=" ca-cert
"&sslfactory=org.postgresql.ssl.jdbc4.LibPQFactory")))
(defn db-conn-spec
"Assemble a JDBC connection specification for a given Jepsen node."
[node]
(merge {:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:loginTimeout (/ max-timeout 1000)
:connectTimeout (/ max-timeout 1000)
:socketTimeout (/ max-timeout 1000)}
(case jdbc-mode
:cdb-cluster
{:subname (str "//" (name node) ":" db-port "/" dbname
ssl-settings)
:user db-user
:password db-passwd}
:cdb-local
{:subname (str "//localhost:" db-port "/" dbname ssl-settings)
:user db-user
:password db-passwd}
:pg-local
{:subname (str "//localhost/" pg-dbname)
:user pg-user
:password pg-passwd})))
(defn close-conn
"Given a JDBC connection, closes it and returns the underlying spec."
[conn]
(when-let [c (j/db-find-connection conn)]
(.close c))
(dissoc conn :connection))
(defn client
"Constructs a network client for a node, and opens it"
[node]
(rc/open!
(rc/wrapper
{:name [:cockroach node]
:open (fn open []
(util/timeout max-timeout
(throw (RuntimeException.
(str "Connection to " node " timed out")))
(let [spec (db-conn-spec node)
conn (j/get-connection spec)
spec' (j/add-connection spec conn)]
(assert spec')
spec')))
:close close-conn
:log? true})))
(defmacro with-conn
"Like jepsen.reconnect/with-conn, but also asserts that the connection has
not been closed. If it has, throws an ex-info with :type :conn-not-ready.
Delays by 1 second to allow time for the DB to recover."
[[c client] & body]
`(rc/with-conn [~c ~client]
(when (.isClosed (j/db-find-connection ~c))
(Thread/sleep 1000)
(throw (ex-info "Connection not yet ready."
{:type :conn-not-ready})))
~@body))
(defn with-idempotent
"Takes a predicate on operation functions, and an op, presumably resulting
from a client call. If (idempotent? (:f op)) is truthy, remaps :info types to
:fail."
[idempotent? op]
(if (and (idempotent? (:f op)) (= :info (:type op)))
(assoc op :type :fail)
op))
(defmacro with-timeout
"Like util/timeout, but throws (RuntimeException. \"timeout\") for timeouts.
Throwing means that when we time out inside a with-conn, the connection state
gets reset, so we don't accidentally hand off the connection to a later
invocation with some incomplete transaction."
[& body]
`(util/timeout timeout-delay
(throw (RuntimeException. "timeout"))
~@body))
(defmacro with-txn-retry-as-fail
"Takes an op, runs body, catches PSQL 'restart transaction' errors, and
converts them to :fails"
[op & body]
`(try ~@body
(catch java.sql.SQLException e#
(if (re-find #"ERROR: restart transaction"
(str (exception->op e#)))
(assoc ~op
:type :fail
:error (str/replace
(.getMessage e#) #"ERROR: restart transaction: " ""))
(throw e#)))))
(defmacro with-txn-retry
"Catches PSQL 'restart transaction' errors and retries body a bunch of times,
with exponential backoffs."
[& body]
`(util/with-retry [attempts# 30
backoff# 20]
~@body
(catch java.sql.SQLException e#
(if (and (pos? attempts#)
(re-find #"ERROR: restart transaction"
(str (exception->op e#))))
(do (Thread/sleep backoff#)
(~'retry (dec attempts#)
(* backoff# (+ 4 (* 0.5 (- (rand) 0.5))))))
(throw e#)))))
(defmacro with-txn
"Wrap a evaluation within a SQL transaction."
[[c conn] & body]
`(j/with-db-transaction [~c ~conn {:isolation isolation-level}]
~@body))
(defmacro with-restart
"Wrap an evaluation within a CockroachDB retry block."
[c & body]
`(util/with-retry [attempts# 10
backoff# 20]
(j/execute! ~c ["savepoint cockroach_restart"])
~@body
(catch java.sql.SQLException e#
(if (and (pos? attempts#)
(re-find #"ERROR: restart transaction"
(str (exception->op e#))))
(do (j/execute! ~c ["rollback to savepoint cockroach_restart"])
(Thread/sleep backoff#)
(info "txn-restart" attempts#)
(~'retry (dec attempts#)
(* backoff# (+ 4 (* 0.5 (- (rand) 0.5))))))
(throw e#)))))
(defn exception->op
"Takes an exception and maps it to a partial op, like {:type :info, :error
...}. nil if unrecognized."
[e]
(when-let [m (.getMessage e)]
(condp instance? e
java.sql.SQLTransactionRollbackException
{:type :fail, :error [:rollback m]}
java.sql.BatchUpdateException
(if (re-find #"getNextExc" m)
; Wrap underlying exception error with [:batch ...]
(when-let [op (exception->op (.getNextException e))]
(update op :error (partial vector :batch)))
{:type :info, :error [:batch-update m]})
org.postgresql.util.PSQLException
(condp re-find (.getMessage e)
#"Connection .+? refused"
{:type :fail, :error :connection-refused}
#"context deadline exceeded"
{:type :fail, :error :context-deadline-exceeded}
#"rejecting command with timestamp in the future"
{:type :fail, :error :reject-command-future-timestamp}
#"encountered previous write with future timestamp"
{:type :fail, :error :previous-write-future-timestamp}
#"restart transaction"
{:type :fail, :error [:restart-transaction m]}
{:type :info, :error [:psql-exception m]})
clojure.lang.ExceptionInfo
(condp = (:type (ex-data e))
:conn-not-ready {:type :fail, :error :conn-not-ready}
nil)
(condp re-find m
#"^timeout$"
{:type :info, :error :timeout}
nil))))
(defmacro with-exception->op
"Takes an operation and a body. Evaluates body, catches exceptions, and maps
them to ops with :type :info and a descriptive :error."
[op & body]
`(try ~@body
(catch Exception e#
(if-let [ex-op# (exception->op e#)]
(merge ~op ex-op#)
(throw e#)))))
(defn wait-for-conn
"Spins until a client is ready. Somehow, I think exceptions escape from this."
[client]
(util/timeout 60000 (throw (RuntimeException. "Timed out waiting for conn"))
(while (try
(rc/with-conn [c client]
(j/query c ["select 1"])
false)
(catch RuntimeException e
true)))))
(defn query
"Like jdbc query, but includes a default timeout in ms."
([conn expr]
(query conn expr {}))
([conn [sql & params] opts]
(let [s (j/prepare-statement (j/db-find-connection conn)
sql
{:timeout (/ timeout-delay 1000)})]
(try
(j/query conn (into [s] params) opts)
(finally
(.close s))))))
(defn insert!
"Like jdbc insert!, but includes a default timeout."
[conn table values]
(j/insert! conn table values {:timeout timeout-delay}))
(defn insert-with-rowid!
"Like insert!, but includes the auto-generated :rowid."
[conn table record]
(let [keys (->> record
keys
(map name)
(str/join ", "))
placeholder (str/join ", " (repeat (count record) "?"))]
(merge record
(first (query conn
(into [(str "insert into " table " (" keys
") values (" placeholder
") returning rowid;")]
(vals record)))))))
(defn update!
"Like jdbc update!, but includes a default timeout."
[conn table values where]
(j/update! conn table values where {:timeout timeout-delay}))
(defn db-time
"Retrieve the current time (precise, monotonic) from the database."
[c]
(cond (= jdbc-mode :pg-local)
(->> (query c ["select extract(microseconds from now()) as ts"]
{:row-fn :ts})
(first)
(str))
true
(->> (query c ["select cluster_logical_timestamp()*10000000000::decimal as ts"]
{:row-fn :ts})
(first)
(.toBigInteger)
(str))))
(defn split!
"Split the given table at the given key."
[conn table k]
(query conn [(str "alter table " (name table) " split at values ("
(if (number? k)
k
(str "'" k "'"))
")")]))
| null |
https://raw.githubusercontent.com/gator1/jepsen/1932cbd72cbc1f6c2a27abe0fe347ea989f0cfbb/cockroachdb/src/jepsen/cockroach/client.clj
|
clojure
|
for secure mode
Postgres user and dbname for jdbc-mode = :pg-*
must already exist
must already exist
must already exist
Wrap underlying exception error with [:batch ...]
|
(ns jepsen.cockroach.client
"For talking to cockroachdb over the network"
(:require [clojure.tools.logging :refer :all]
[clojure.java.jdbc :as j]
[clojure.string :as str]
[clojure.pprint :refer [pprint]]
[jepsen [util :as util :refer [meh]]
[reconnect :as rc]]
[jepsen.cockroach [auto :as auto :refer [cockroach-user
cockroach
jdbc-mode
db-port
insecure
db-user
db-passwd
store-path
dbname
verlog
log-files
pcaplog]]]))
(def timeout-delay "Default timeout for operations in ms" 10000)
(def max-timeout "Longest timeout, in ms" 30000)
(def isolation-level "Default isolation level for txns" :serializable)
(def client-cert "certs/node.client.crt")
(def client-key "certs/node.client.pk8")
(def ca-cert "certs/ca.crt")
(def ssl-settings
(if insecure
""
(str "?ssl=true"
"&sslcert=" client-cert
"&sslkey=" client-key
"&sslrootcert=" ca-cert
"&sslfactory=org.postgresql.ssl.jdbc4.LibPQFactory")))
(defn db-conn-spec
"Assemble a JDBC connection specification for a given Jepsen node."
[node]
(merge {:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:loginTimeout (/ max-timeout 1000)
:connectTimeout (/ max-timeout 1000)
:socketTimeout (/ max-timeout 1000)}
(case jdbc-mode
:cdb-cluster
{:subname (str "//" (name node) ":" db-port "/" dbname
ssl-settings)
:user db-user
:password db-passwd}
:cdb-local
{:subname (str "//localhost:" db-port "/" dbname ssl-settings)
:user db-user
:password db-passwd}
:pg-local
{:subname (str "//localhost/" pg-dbname)
:user pg-user
:password pg-passwd})))
(defn close-conn
"Given a JDBC connection, closes it and returns the underlying spec."
[conn]
(when-let [c (j/db-find-connection conn)]
(.close c))
(dissoc conn :connection))
(defn client
"Constructs a network client for a node, and opens it"
[node]
(rc/open!
(rc/wrapper
{:name [:cockroach node]
:open (fn open []
(util/timeout max-timeout
(throw (RuntimeException.
(str "Connection to " node " timed out")))
(let [spec (db-conn-spec node)
conn (j/get-connection spec)
spec' (j/add-connection spec conn)]
(assert spec')
spec')))
:close close-conn
:log? true})))
(defmacro with-conn
"Like jepsen.reconnect/with-conn, but also asserts that the connection has
not been closed. If it has, throws an ex-info with :type :conn-not-ready.
Delays by 1 second to allow time for the DB to recover."
[[c client] & body]
`(rc/with-conn [~c ~client]
(when (.isClosed (j/db-find-connection ~c))
(Thread/sleep 1000)
(throw (ex-info "Connection not yet ready."
{:type :conn-not-ready})))
~@body))
(defn with-idempotent
"Takes a predicate on operation functions, and an op, presumably resulting
from a client call. If (idempotent? (:f op)) is truthy, remaps :info types to
:fail."
[idempotent? op]
(if (and (idempotent? (:f op)) (= :info (:type op)))
(assoc op :type :fail)
op))
(defmacro with-timeout
"Like util/timeout, but throws (RuntimeException. \"timeout\") for timeouts.
Throwing means that when we time out inside a with-conn, the connection state
gets reset, so we don't accidentally hand off the connection to a later
invocation with some incomplete transaction."
[& body]
`(util/timeout timeout-delay
(throw (RuntimeException. "timeout"))
~@body))
(defmacro with-txn-retry-as-fail
"Takes an op, runs body, catches PSQL 'restart transaction' errors, and
converts them to :fails"
[op & body]
`(try ~@body
(catch java.sql.SQLException e#
(if (re-find #"ERROR: restart transaction"
(str (exception->op e#)))
(assoc ~op
:type :fail
:error (str/replace
(.getMessage e#) #"ERROR: restart transaction: " ""))
(throw e#)))))
(defmacro with-txn-retry
"Catches PSQL 'restart transaction' errors and retries body a bunch of times,
with exponential backoffs."
[& body]
`(util/with-retry [attempts# 30
backoff# 20]
~@body
(catch java.sql.SQLException e#
(if (and (pos? attempts#)
(re-find #"ERROR: restart transaction"
(str (exception->op e#))))
(do (Thread/sleep backoff#)
(~'retry (dec attempts#)
(* backoff# (+ 4 (* 0.5 (- (rand) 0.5))))))
(throw e#)))))
(defmacro with-txn
"Wrap a evaluation within a SQL transaction."
[[c conn] & body]
`(j/with-db-transaction [~c ~conn {:isolation isolation-level}]
~@body))
(defmacro with-restart
"Wrap an evaluation within a CockroachDB retry block."
[c & body]
`(util/with-retry [attempts# 10
backoff# 20]
(j/execute! ~c ["savepoint cockroach_restart"])
~@body
(catch java.sql.SQLException e#
(if (and (pos? attempts#)
(re-find #"ERROR: restart transaction"
(str (exception->op e#))))
(do (j/execute! ~c ["rollback to savepoint cockroach_restart"])
(Thread/sleep backoff#)
(info "txn-restart" attempts#)
(~'retry (dec attempts#)
(* backoff# (+ 4 (* 0.5 (- (rand) 0.5))))))
(throw e#)))))
(defn exception->op
"Takes an exception and maps it to a partial op, like {:type :info, :error
...}. nil if unrecognized."
[e]
(when-let [m (.getMessage e)]
(condp instance? e
java.sql.SQLTransactionRollbackException
{:type :fail, :error [:rollback m]}
java.sql.BatchUpdateException
(if (re-find #"getNextExc" m)
(when-let [op (exception->op (.getNextException e))]
(update op :error (partial vector :batch)))
{:type :info, :error [:batch-update m]})
org.postgresql.util.PSQLException
(condp re-find (.getMessage e)
#"Connection .+? refused"
{:type :fail, :error :connection-refused}
#"context deadline exceeded"
{:type :fail, :error :context-deadline-exceeded}
#"rejecting command with timestamp in the future"
{:type :fail, :error :reject-command-future-timestamp}
#"encountered previous write with future timestamp"
{:type :fail, :error :previous-write-future-timestamp}
#"restart transaction"
{:type :fail, :error [:restart-transaction m]}
{:type :info, :error [:psql-exception m]})
clojure.lang.ExceptionInfo
(condp = (:type (ex-data e))
:conn-not-ready {:type :fail, :error :conn-not-ready}
nil)
(condp re-find m
#"^timeout$"
{:type :info, :error :timeout}
nil))))
(defmacro with-exception->op
"Takes an operation and a body. Evaluates body, catches exceptions, and maps
them to ops with :type :info and a descriptive :error."
[op & body]
`(try ~@body
(catch Exception e#
(if-let [ex-op# (exception->op e#)]
(merge ~op ex-op#)
(throw e#)))))
(defn wait-for-conn
"Spins until a client is ready. Somehow, I think exceptions escape from this."
[client]
(util/timeout 60000 (throw (RuntimeException. "Timed out waiting for conn"))
(while (try
(rc/with-conn [c client]
(j/query c ["select 1"])
false)
(catch RuntimeException e
true)))))
(defn query
"Like jdbc query, but includes a default timeout in ms."
([conn expr]
(query conn expr {}))
([conn [sql & params] opts]
(let [s (j/prepare-statement (j/db-find-connection conn)
sql
{:timeout (/ timeout-delay 1000)})]
(try
(j/query conn (into [s] params) opts)
(finally
(.close s))))))
(defn insert!
"Like jdbc insert!, but includes a default timeout."
[conn table values]
(j/insert! conn table values {:timeout timeout-delay}))
(defn insert-with-rowid!
"Like insert!, but includes the auto-generated :rowid."
[conn table record]
(let [keys (->> record
keys
(map name)
(str/join ", "))
placeholder (str/join ", " (repeat (count record) "?"))]
(merge record
(first (query conn
(into [(str "insert into " table " (" keys
") values (" placeholder
") returning rowid;")]
(vals record)))))))
(defn update!
"Like jdbc update!, but includes a default timeout."
[conn table values where]
(j/update! conn table values where {:timeout timeout-delay}))
(defn db-time
"Retrieve the current time (precise, monotonic) from the database."
[c]
(cond (= jdbc-mode :pg-local)
(->> (query c ["select extract(microseconds from now()) as ts"]
{:row-fn :ts})
(first)
(str))
true
(->> (query c ["select cluster_logical_timestamp()*10000000000::decimal as ts"]
{:row-fn :ts})
(first)
(.toBigInteger)
(str))))
(defn split!
"Split the given table at the given key."
[conn table k]
(query conn [(str "alter table " (name table) " split at values ("
(if (number? k)
k
(str "'" k "'"))
")")]))
|
c3bd005491b88a25558f14a28121270dbfdcf0095fb0d97f2ebbea280668ffba
|
herd/herdtools7
|
hardwareExtra.ml
|
(****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2022 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
(** Additional hardware features *)
module type S = sig
val user_handler_clobbers : string list
val vector_table : bool -> string -> string list
end
module No = struct
let user_handler_clobbers = []
let vector_table _ _ = []
end
| null |
https://raw.githubusercontent.com/herd/herdtools7/de608e9a67a4c91e442bb0f807c6641a4283b4be/litmus/hardwareExtra.ml
|
ocaml
|
**************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
* Additional hardware features
|
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2022 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
module type S = sig
val user_handler_clobbers : string list
val vector_table : bool -> string -> string list
end
module No = struct
let user_handler_clobbers = []
let vector_table _ _ = []
end
|
20e4ac73df4dc4a94d194b3a4beb19c611d3f179f52588f5d9d1ab3ddcd213b8
|
stritzinger/opcua
|
opcua_channel.erl
|
-module(opcua_channel).
%%% BEHAVIOUR opcua_channel DEFINITION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-callback channel_id(State) -> ChannelId
when State :: term(), ChannelId :: opcua:channel_id().
-callback lock(Chunk, Conn, State)
-> {ok, Chunk, Conn, State} | {error, Reason}
when Chunk :: opcua:chunk(),
Conn :: opcua:connection(),
State :: term(),
Reason :: term().
-callback unlock(Chunk, Conn, State)
-> {ok, Chunk, Conn, State} | {error, Reason}
when Chunk :: opcua:chunk(),
Conn :: opcua:connection(),
State :: term(),
Reason :: term().
| null |
https://raw.githubusercontent.com/stritzinger/opcua/a9802f829f80e6961871653f4d3c932f9496ba99/src/opcua_channel.erl
|
erlang
|
BEHAVIOUR opcua_channel DEFINITION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
-module(opcua_channel).
-callback channel_id(State) -> ChannelId
when State :: term(), ChannelId :: opcua:channel_id().
-callback lock(Chunk, Conn, State)
-> {ok, Chunk, Conn, State} | {error, Reason}
when Chunk :: opcua:chunk(),
Conn :: opcua:connection(),
State :: term(),
Reason :: term().
-callback unlock(Chunk, Conn, State)
-> {ok, Chunk, Conn, State} | {error, Reason}
when Chunk :: opcua:chunk(),
Conn :: opcua:connection(),
State :: term(),
Reason :: term().
|
766d42a12c7fc3eaf3446e7629c1c05c845723a2d72743e06af6fc69a1fa0e96
|
kupl/LearnML
|
patch.ml
|
let rec iter ((n : int), (f : int -> int)) (x : int) : int =
if n = 0 then x
else if n < 1 then raise Failure "ERROR"
else f (iter (n - 1, f) x)
| null |
https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/iter/sub25/patch.ml
|
ocaml
|
let rec iter ((n : int), (f : int -> int)) (x : int) : int =
if n = 0 then x
else if n < 1 then raise Failure "ERROR"
else f (iter (n - 1, f) x)
|
|
813b1ef972b44250cef61a1c4cdb8de8c0e96e50691c1febf150a0a008511e57
|
mon-key/unicly
|
unicly-bit-vectors.lisp
|
: FILE - CREATED < Timestamp : # { 2011 - 08 - 13T19:18:12 - 04:00Z}#{11326 } - by MON >
;;; :FILE unicly/unicly-bit-vectors.lisp
;;; ==============================
;;; ==============================
;; :NOTE Per RFC 4.1.3 bit 48 should always be 0.
The UUID as bit field :
WEIGHT INDEX OCTETS BIT - FIELD - PER - OCTET
4 | ( 0 31 ) | 255 255 255 255 | # * 11111111 # * 11111111 # * 11111111 # * 11111111 | % uuid_time - low | uuid - ub32
2 | ( 32 47 ) | 255 255 | # * 11111111 # * 11111111 | % uuid_time - mid | uuid - ub16
2 | ( 48 63 ) | 255 255 | # * 11111111 # * 11111111 | % uuid_time - high - and - version
1 | ( 64 71 ) | 255 | # * 11111111 | % uuid_clock - seq - and - reserved | uuid - ub8
1 | ( 72 79 ) | 255 | # * 11111111 | % uuid_clock - seq - low | uuid - ub8
6 | ( 80 127 ) | 255 255 255 255 255 255 | # * 11111111 # * 11111111 # * 11111111 # * 11111111 # * 11111111 # * 11111111 | % uuid_node | uuid - ub48
;;
;; The UUIDs bit-vector representation
;; (uuid-to-bit-vector (make-v5-uuid *uuid-namespace-dns* "bubba"))
0 7 15 23 31 39 47 55 63 71 79 87 95 103 111 119 127
;; ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
;; #*11101110101000010001000001011110001101101000000101010001000101111001100110110110011110110010101101011111111000011111001111000111
;;
;; The UUIDs binary integer representation:
;; #b11101110101000010001000001011110001101101000000101010001000101111001100110110110011110110010101101011111111000011111001111000111
= > 317192554773903544674993329975922389959
;;
The byte - array reresentation :
( uuid - integer-128 - to - byte - array 317192554773903544674993329975922389959 )
= > # ( 238 161 16 94 54 129 81 23 153 182 123 43 95 225 243 199 )
;;
;; (uuid-to-byte-array (make-v5-uuid *uuid-namespace-dns* "bubba"))
= > # ( 238 161 16 94 54 129 81 23 153 182 123 43 95 225 243 199 )
;;
;; (map 'list #'uuid-octet-to-bit-vector-8 (uuid-to-byte-array (make-v5-uuid *uuid-namespace-dns* "bubba")))
= > ( # * 11101110 # * 10100001 # * 00010000 # * 01011110 # * 00110110 # * 10000001 # * 01010001
# * 00010111 # * 10011001 # * 10110110 # * 01111011 # * 00101011 # * 01011111 # * 11100001
# * 11110011 # * 11000111 )
;;
;;
;; (uuid-byte-array-to-bit-vector (uuid-to-byte-array (make-v5-uuid *uuid-namespace-dns* "bubba")))
;; => #*11101110101000010001000001011110001101101000000101010001000101111001100110110110011110110010101101011111111000011111001111000111
;;
;; The upper bounds of a UUID in binary integer representation:
;; #b11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
= > 340282366920938463463374607431768211455
;;
;; The number of unsigned bits used to represent the upper bounds of a UUIDs
;; integer representation:
( integer - length 340282366920938463463374607431768211455 )
= > 128
;;
;; The octet count of the upper bounds of a UUIDs integer representation:
( truncate ( integer - length 340282366920938463463374607431768211455 ) 8)
= > 16
;;
The upper bounds of UUID in decimal ( longform ):
( format t " ~R " 340282366920938463463374607431768211455 )
= > three hundred forty undecillion two hundred eighty - two decillion three hundred
sixty - six nonillion nine hundred twenty octillion nine hundred thirty - eight
septillion four hundred sixty - three sextillion four hundred sixty - three
;; quintillion three hundred seventy-four quadrillion six hundred seven trillion
four hundred thirty - one billion seven hundred sixty - eight million two hundred
;; eleven thousand four hundred fifty-five
;;
;; The octet offsets into a uuid-bit-vector-128:
;; (loop
for x from 0 below 128 by 8
;; for q = 0 then x
as y = 7 then ( + x 7 )
;; collect (list q y))
= > ( ( 0 7 ) ( 8 15 ) ( 16 23 ) ( 24 31 ) ; ; % uuid_time - low
( 32 39 ) ( 40 47 ) ; ; % uuid_time - mid
( 48 55 ) ( 56 63 ) ; ; % uuid_time - high - and - version
( 64 71 ) ; ; % uuid_clock - seq - and - reserved
( 72 79 ) ; ; % uuid_clock - seq - low
( 80 87 ) ( 88 95 ) ( 96 103 )
( 104 111 ) ( 112 119 ) ( 120 127 ) ) ; ; % uuid_nodede
;;
;;; ==============================
(in-package #:unicly)
;; *package*
(declaim (inline uuid-bit-vector-128-zeroed
uuid-bit-vector-48-zeroed
uuid-bit-vector-32-zeroed
uuid-bit-vector-16-zeroed
uuid-bit-vector-8-zeroed))
;; uuid-bit-vector-<N>-zeroed
(def-uuid-bit-vector-zeroed 128)
(def-uuid-bit-vector-zeroed 48)
(def-uuid-bit-vector-zeroed 32)
(def-uuid-bit-vector-zeroed 16)
(def-uuid-bit-vector-zeroed 8)
;; (uuid-bit-vector-32-zeroed)
;; (uuid-version-bit-vector (uuid-bit-vector-32-zeroed))
;; (typep (uuid-bit-vector-128-zeroed) 'uuid-bit-vector-128)
;;; ==============================
: NOTE For 1mil comparisons of two uuid - bit - vectors following timing support
;; the current implementation using `sb-int:bit-vector-=':
comparison with ` cl : equal ' completes in 251,812,778 cycles , 0.083328 run - time
comparison with ` sb - int : bit - vector-= ' without declarations completes in in ~191,959,447 cycles , 0.063329 run - time
comparison with ` sb - int : bit - vector-= ' with declartions completes in ~170,661,197 , 0.05555199 run - time
The alternative definition is not altogether inferior but ca n't be made surpass SBCL 's internal transforms
;;
;; (let ((bv (uuid-bit-vector-128-zeroed)))
( setf ( sbit bv 127 ) 1 )
;; (null (uuid-bit-vector-eql (uuid-bit-vector-128-zeroed) bv)))
;;
;; following errors succesfully:
;; (uuid-bit-vector-eql (uuid-bit-vector-128-zeroed) "bubba")
(defun uuid-bit-vector-eql (uuid-bv-a uuid-bv-b)
(declare
: NOTE safety 2 required if we want to ensure Python sniffs around for bv length
;; So we added `uuid-bit-vector-128-check-type' -- should be no way for it to fail.
(inline uuid-bit-vector-128-check-type)
( optimize ( speed 3 ) ( safety 2 ) ) )
(optimize (speed 3)))
(uuid-bit-vector-128-check-type uuid-bv-a)
(uuid-bit-vector-128-check-type uuid-bv-b)
(locally
(declare (type uuid-bit-vector-128 uuid-bv-a uuid-bv-b)
(optimize (speed 3) (safety 0)))
#-:sbcl
(if (and (= (count 0 uuid-bv-a :test #'=) (count 0 uuid-bv-b :test #'=))
(= (count 1 uuid-bv-a :test #'=) (count 1 uuid-bv-b :test #'=)))
(loop
for low-idx from 0 below 64
for top-idx = (logxor low-idx 127)
always (and (= (sbit uuid-bv-a low-idx) (sbit uuid-bv-b low-idx))
(= (sbit uuid-bv-a top-idx) (sbit uuid-bv-b top-idx)))))
#+:sbcl (SB-INT:BIT-VECTOR-= uuid-bv-a uuid-bv-b)))
(defun %uuid-bit-vector-null-p (bit-vector-maybe-null)
(declare (uuid-bit-vector-128 bit-vector-maybe-null)
(inline uuid-bit-vector-128-zeroed)
(optimize (speed 3)))
;; uuid-bit-vector-eql should catch non uuid-bit-vector-128s
(the (values (member t nil) &optional)
(uuid-bit-vector-eql bit-vector-maybe-null (the uuid-bit-vector-128 (uuid-bit-vector-128-zeroed)))))
;; :NOTE The type unicly::uuid-bit-vector-null is a satisfies of %uuid-bit-vector-null-p
(declaim (inline uuid-bit-vector-null-p))
(defun uuid-bit-vector-null-p (bit-vector-maybe-null)
(declare (optimize (speed 3)))
(the boolean (typep bit-vector-maybe-null 'uuid-bit-vector-null)))
: COURTESY : DATE 2011 - 04 - 08
;; :SOURCE (URL `/+2LKZ/2')
(defun uuid-octet-to-bit-vector-8 (octet)
(declare (type uuid-ub8 octet)
(inline uuid-bit-vector-8-zeroed)
(optimize (speed 3)))
(let ((bv8 (the uuid-bit-vector-8 (uuid-bit-vector-8-zeroed))))
(declare (uuid-bit-vector-8 bv8))
(dotimes (i 8 bv8)
(setf (sbit bv8 i) (ldb (byte 1 7) octet))
(setf octet (logand #xFF (ash octet 1))))))
(declaim (inline uuid-deposit-octet-to-bit-vector))
(defun uuid-deposit-octet-to-bit-vector (octet offset uuid-bv)
(declare (uuid-ub8 octet)
(uuid-ub128-integer-length offset)
(uuid-bit-vector-128 uuid-bv)
(optimize (speed 3)))
(loop
for idx upfrom offset below (+ offset 8)
do (setf (sbit uuid-bv idx) (ldb (byte 1 7) octet))
(setf octet (logand #xFF (ash octet 1)))
finally (return uuid-bv)))
(defun uuid-byte-array-to-bit-vector (uuid-byte-array)
(declare (uuid-byte-array-16 uuid-byte-array)
(inline uuid-deposit-octet-to-bit-vector
%uuid-byte-array-null-p)
(optimize (speed 3)))
;; (uuid-byte-array-16-check-type uuid-byte-array))
(let ((uuid-bv128 (the uuid-bit-vector-128 (uuid-bit-vector-128-zeroed))))
(declare (uuid-bit-vector-128 uuid-bv128))
(when (%uuid-byte-array-null-p uuid-byte-array)
(return-from uuid-byte-array-to-bit-vector uuid-bv128))
(loop
for byte across uuid-byte-array
for offset upfrom 0 by 8 below 128
do (uuid-deposit-octet-to-bit-vector byte offset uuid-bv128)
finally (return (the uuid-bit-vector-128 uuid-bv128)))))
(defun uuid-bit-vector-to-byte-array (uuid-bv-128)
(declare (uuid-bit-vector-128 uuid-bv-128)
(optimize (speed 3)))
(uuid-bit-vector-128-check-type uuid-bv-128)
(when (uuid-bit-vector-null-p uuid-bv-128)
(return-from uuid-bit-vector-to-byte-array (the uuid-byte-array-16 (uuid-byte-array-16-zeroed))))
(labels ((displaced-8 (disp-off)
(declare (optimize (speed 3)))
(the (bit-vector 8)
(make-array 8
:element-type 'bit
:displaced-to uuid-bv-128
:displaced-index-offset disp-off)))
;; ,----
| If ` make - array ' is called with ADJUSTABLE , FILL - POINTER , and
;; | DISPLACED-TO each ‘nil’, then the result is a simple array. If
| ‘ make - array ’ is called with one or more of ADJUSTABLE , FILL - POINTER , or
;; | DISPLACED-TO being true, whether the resulting array is a simple array
;; | is implementation-dependent.
;; `----
On SBCL bv8 is of type :
;; (and (bit-vector 8) (not simple-array))
(bv8-to-ub8 (bv8)
(declare ((bit-vector 8) bv8)
(optimize (speed 3)))
(let ((j 0))
(declare (uuid-ub8 j))
(dotimes (i 8 (the uuid-ub8 j))
(setf j (logior (bit bv8 i) (ash j 1))))))
(get-bv-octets ()
(let ((rtn (uuid-byte-array-16-zeroed))
(offsets (loop
with offsets-array = (uuid-byte-array-16-zeroed)
for idx from 0 below 16
for bv-offset from 0 below 128 by 8
do (setf (aref offsets-array idx) bv-offset)
finally (return offsets-array))))
(declare (uuid-byte-array-16 rtn offsets))
(loop
for off across offsets
for idx from 0 below 16
for octet of-type uuid-ub8 = (bv8-to-ub8 (displaced-8 off))
do (setf (aref rtn idx) octet)
finally (return rtn)))))
(the uuid-byte-array-16 (get-bv-octets))))
;;; ==============================
: NOTE Return value has the integer representation : 267678999922476945140730988764022209929
;; (uuid-to-bit-vector (make-v5-uuid *uuid-namespace-dns* "ḻfḉḲíï<òbG¦>GḜîṉí@B3Áû?ḹ<mþḩú'ÁṒ¬&]Ḏ"))
;; (uuid-bit-vector-to-integer (uuid-to-bit-vector (make-v5-uuid *uuid-namespace-dns* "ḻfḉḲíï<òbG¦>GḜîṉí@B3Áû?ḹ<mþḩú'ÁṒ¬&]Ḏ")))
(defun uuid-to-bit-vector (uuid)
(declare (type unique-universal-identifier uuid)
(inline uuid-disassemble-ub32
uuid-disassemble-ub16
uuid-bit-vector-128-zeroed
%unique-universal-identifier-null-p)
(optimize (speed 3)))
(when (%unique-universal-identifier-null-p uuid)
(return-from uuid-to-bit-vector (uuid-bit-vector-128-zeroed)))
(let ((bv-lst
(with-slots (%uuid_time-low %uuid_time-mid %uuid_time-high-and-version
%uuid_clock-seq-and-reserved %uuid_clock-seq-low %uuid_node)
uuid
(declare (uuid-ub32 %uuid_time-low)
(uuid-ub16 %uuid_time-mid %uuid_time-high-and-version)
(uuid-ub8 %uuid_clock-seq-and-reserved %uuid_clock-seq-low)
(uuid-ub48 %uuid_node))
(multiple-value-call #'list
(uuid-disassemble-ub32 %uuid_time-low)
(uuid-disassemble-ub16 %uuid_time-mid)
(uuid-disassemble-ub16 %uuid_time-high-and-version)
%uuid_clock-seq-and-reserved
%uuid_clock-seq-low
(uuid-disassemble-ub48 %uuid_node))))
(uuid-bv128 (the uuid-bit-vector-128 (uuid-bit-vector-128-zeroed))))
(declare (list bv-lst) (uuid-bit-vector-128 uuid-bv128))
(loop
for byte in bv-lst
for offset upfrom 0 by 8 below 128
do (uuid-deposit-octet-to-bit-vector (the uuid-ub8 byte) offset uuid-bv128)
finally (return uuid-bv128))))
(declaim (inline %uuid-version-bit-vector-if))
(defun %uuid-version-bit-vector-if (uuid-bit-vector)
;; :TEST (signals succesfully)
;; (let ((bv-z (uuid-bit-vector-128-zeroed)))
( setf ( sbit bv - z 48 ) 1 )
;; (%uuid-version-bit-vector-if bv-z))
(declare (inline uuid-bit-vector-128-check-type)
(optimize (speed 3)))
(uuid-bit-vector-128-check-type uuid-bit-vector)
(locally (declare
(uuid-bit-vector-128 uuid-bit-vector)
(optimize (speed 3) (safety 0)))
(unless (zerop (sbit uuid-bit-vector 48))
(error 'uuid-bit-48-error :uuid-bit-48-error-datum uuid-bit-vector))))
;;
;; (%uuid-version-bit-vector-if (uuid-bit-vector-32-zeroed))
;; (uuid-version-bit-vector (uuid-bit-vector-32-zeroed))
;;; ==============================
48 49 50 51
| 0 0 0 1 | 1 The time - based version specified in this document .
| 0 0 1 0 | 2 DCE Security version , with embedded POSIX UIDs .
| 0 0 1 1 | 3 The name - based MD5
| 0 1 0 0 | 4 The randomly or pseudo - randomly generated version
| 0 1 0 1 | 5 The name - based SHA-1
(declaim (inline uuid-version-bit-vector))
(defun uuid-version-bit-vector (uuid-bit-vector)
(declare (uuid-bit-vector-128 uuid-bit-vector)
(inline %uuid-version-bit-vector-if
uuid-bit-vector-128-zeroed
uuid-bit-vector-null-p)
(optimize (speed 3)))
(%uuid-version-bit-vector-if uuid-bit-vector)
(ecase (the bit (sbit uuid-bit-vector 49))
(0 (ecase (the bit (sbit uuid-bit-vector 50))
(1 (ecase (the bit (sbit uuid-bit-vector 51))
(1 3)
(0 2)))
(0 (ecase (the bit (sbit uuid-bit-vector 51))
(1 1)
RFC4122 Setion 4.1.7 . " Nil UUID " specifically requires a null UUID
;; However, it doesn't say anything about the version 0 UUID...
;; Of course it wouldn't given how C centric nature of the entire RFC :)
;; So, as a way of flipping the bird to the curly brace inclined we
;; choose to return as if by `cl:values': 0, null-uuid
(0 (values (or (and (uuid-bit-vector-null-p uuid-bit-vector) 0)
(error "something wrong with UUID-BIT-VECTOR bit field~% got: ~S" uuid-bit-vector))
'null-uuid))))))
(1 (ecase (the bit (sbit uuid-bit-vector 51))
(0 4)
(1 5)))))
(declaim (inline uuid-bit-vector-v3-p))
(defun uuid-bit-vector-v3-p (uuid-bit-vector)
;; (uuid-bit-vector-v3-p (uuid-to-bit-vector (make-v3-uuid (make-v4-uuid) "bubba")))
(declare (uuid-bit-vector-128 uuid-bit-vector)
(inline uuid-version-bit-vector)
(optimize (speed 3)))
(let ((v3-if (uuid-version-bit-vector uuid-bit-vector)))
(declare (uuid-version-int v3-if))
(the boolean
(and (logbitp 1 v3-if) (logbitp 0 v3-if) t))))
(declaim (inline uuid-bit-vector-v4-p))
(defun uuid-bit-vector-v4-p (uuid-bit-vector)
;; (uuid-bit-vector-v4-p (uuid-to-bit-vector (make-v4-uuid)))
(declare (uuid-bit-vector-128 uuid-bit-vector)
(inline uuid-version-bit-vector)
(optimize (speed 3)))
(let ((v4-if (uuid-version-bit-vector uuid-bit-vector)))
(declare (uuid-version-int v4-if))
(the boolean
(zerop (logior (logxor v4-if 4) 0)))))
(declaim (inline uuid-bit-vector-v5-p))
(defun uuid-bit-vector-v5-p (uuid-bit-vector)
;; (uuid-bit-vector-v5-p (uuid-to-bit-vector (make-v5-uuid (make-v4-uuid) "bubba")))
(declare (uuid-bit-vector-128 uuid-bit-vector)
(inline uuid-version-bit-vector)
(optimize (speed 3)))
(let ((v5-if (uuid-version-bit-vector uuid-bit-vector)))
(declare (uuid-version-int v5-if))
(the boolean
(and (logbitp 2 v5-if) (logbitp 0 v5-if) t))))
;;; ==============================
;; (defun number-to-bit-vector (unsigned-integer)
;; (declare ((integer 0 *) unsigned-integer)
( optimize ( speed 3 ) ) )
;; (flet ((number-to-bit-vector-fixnum (fixnum-int)
;; (declare (fixnum-0-or-over fixnum-int))
;; (let* ((mk-len (the fixnum-bit-width (integer-length fixnum-int)))
;; (bv-29 (make-array (the fixnum-bit-width mk-len)
;; :element-type 'bit
;; :initial-element 0
;; :adjustable nil)))
;; (declare (fixnum-bit-width mk-len)
;; (simple-bit-vector bv-29))
;; (loop
;; for i-lb from 0 below mk-len
;; do (and (logbitp i-lb fixnum-int)
;; (setf (sbit bv-29 i-lb) 1))
finally ( return ( nreverse bv-29 ) ) ) ) )
;; (number-to-bit-vector-bignum (bignum-int)
;; (declare (bignum-0-or-over bignum-int))
;; (let* ((mk-big-len (the bignum-bit-width (integer-length bignum-int)))
;; (bv-big (make-array (the bignum-bit-width mk-big-len)
;; :element-type 'bit
;; :initial-element 0
;; :adjustable nil)))
;; (declare (bignum-bit-width mk-big-len)
;; (simple-bit-vector bv-big))
;; (loop
;; for i-lb from 0 below mk-big-len
;; do (and (logbitp i-lb bignum-int)
( setf ( sbit bv - big i - lb ) 1 ) )
finally ( return ( nreverse bv - big ) ) ) ) ) )
;; (etypecase unsigned-integer
;; (fixnum-0-or-over (the simple-bit-vector
;; (number-to-bit-vector-fixnum
;; (the fixnum-0-or-over unsigned-integer))))
;; (bignum-0-or-over (the simple-bit-vector
;; (number-to-bit-vector-bignum
;; (the bignum-0-or-over unsigned-integer)))))))
;;
;; :TODO incorporate trivial-features so we can test for :big-endian :little-endian
(defun uuid-integer-128-to-bit-vector (uuid-integer-128)
(declare (uuid-ub128 uuid-integer-128)
(optimize (speed 3)))
(let ((mk-big-len (the uuid-ub128-integer-length (integer-length uuid-integer-128)))
(bv-big (the uuid-bit-vector-128 (uuid-bit-vector-128-zeroed))))
(declare (uuid-ub128-integer-length mk-big-len)
(uuid-bit-vector-128 bv-big))
(loop
for i-lb from 0 below mk-big-len
do (and (logbitp i-lb uuid-integer-128)
(setf (sbit bv-big i-lb) 1))
;; *features*
;; #+big-endian (return bv-big))
# + little - endian ( return ( nreverse bv - big ) )
finally (return (nreverse bv-big)))))
;;; ==============================
: NOTE Following modeled after Stas 's inclued at bottom of file :
(defun uuid-bit-vector-to-integer (bit-vector)
(declare (uuid-bit-vector bit-vector)
(optimize (speed 3)))
(let* ((bv-length (the uuid-ub128-integer-length (length bit-vector)))
(word-size (ash bv-length -1))
in this case always two ?
(result 0)
(index -1))
(labels ((build-word ()
(loop
repeat word-size
for j = 0 then (logior (sbit bit-vector (incf index))
(ash j 1))
finally (return j)))
(loop-repeats ()
(loop
repeat repeats ;; (floor bv-length word-size)
do (setf result (logior (build-word)
(ash result (1- word-size))))))
(loop-less-index ()
(loop
while (< index (1- bv-length))
do (setf result (logior (sbit bit-vector (incf index))
(ash result 1)))))
(loop-and-return ()
(loop-repeats)
(loop-less-index)
result)
(get-bv-128-int ()
(declare (uuid-bit-vector-128 bit-vector)
(uuid-bit-vector-128-length bv-length)
((uuid-bit-vector-length 64) word-size))
(the uuid-ub128 (loop-and-return)))
(get-bv-48-int ()
(declare (uuid-bit-vector-48 bit-vector)
(uuid-bit-vector-48-length bv-length)
((uuid-bit-vector-length 24) word-size))
(the uuid-ub48 (loop-and-return)))
(get-bv-32-int ()
(declare (uuid-bit-vector-32 bit-vector)
(uuid-bit-vector-32-length bv-length)
(uuid-bit-vector-16-length word-size))
(the uuid-ub32 (loop-and-return)))
(get-bv-16-int ()
(declare (uuid-bit-vector-16 bit-vector)
(uuid-bit-vector-16-length bv-length)
(uuid-bit-vector-8-length word-size))
(the uuid-ub16 (loop-and-return)))
(get-bv-8-int ()
(declare (uuid-bit-vector-8 bit-vector)
(uuid-bit-vector-8-length bv-length)
((uuid-bit-vector-length 4) word-size))
(the uuid-ub8 (loop-and-return))))
(etypecase bv-length
(uuid-bit-vector-128-length (get-bv-128-int))
;; `%uuid_node'
(uuid-bit-vector-48-length (get-bv-48-int))
;; `%uuid_time-low'
(uuid-bit-vector-32-length (get-bv-32-int))
;; `%uuid_time-mid', `%uuid_time-high-and-version'
(uuid-bit-vector-16-length (get-bv-16-int))
;; `%uuid_clock-seq-and-reserved', `%uuid_clock-seq-low'
(uuid-bit-vector-8-length (get-bv-8-int))))))
;; :NOTE before `def-uuid-request-integer-bit-vector' expansion.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun uuid-bit-vector-build-offsets (bit-offset bit-width)
(declare (uuid-bit-vector-valid-bit-offset bit-offset)
(uuid-bit-vector-valid-bit-width bit-width)
(optimize (speed 3) (safety 2)))
(loop
for x from bit-offset below (+ bit-offset bit-width) by 8
for q = bit-offset then x
as y = (cons q (+ x 7))
collect y))
)
;;; ==============================
;; :NOTE `def-uuid-request-integer-bit-vector' defines the following functions:
(declaim (inline %uuid_time-low-request-bit-vector
%uuid_time-mid-request-bit-vector
%uuid_time-high-and-version-request-bit-vector
%uuid_clock-seq-and-reserved-request-bit-vector
%uuid_clock-seq-low-request-bit-vector
%uuid_node-request-bit-vector))
;;
(def-uuid-request-integer-bit-vector "time-low" 0 32)
(def-uuid-request-integer-bit-vector "time-mid" 32 16)
(def-uuid-request-integer-bit-vector "time-high-and-version" 48 16)
(def-uuid-request-integer-bit-vector "clock-seq-and-reserved" 64 8)
(def-uuid-request-integer-bit-vector "clock-seq-low" 72 8)
(def-uuid-request-integer-bit-vector "node" 80 48)
;;
(defun uuid-from-bit-vector (bit-vector-128)
(declare (inline %uuid_time-low-request-bit-vector
%uuid_time-mid-request-bit-vector
%uuid_time-high-and-version-request-bit-vector
%uuid_clock-seq-and-reserved-request-bit-vector
%uuid_clock-seq-low-request-bit-vector
%uuid_node-request-bit-vector
uuid-bit-vector-null-p)
(uuid-bit-vector-128 bit-vector-128)
(optimize (speed 3)))
(uuid-bit-vector-128-check-type bit-vector-128)
(when (uuid-bit-vector-null-p bit-vector-128)
(return-from uuid-from-bit-vector (the unique-universal-identifier (make-null-uuid))))
(ecase (uuid-version-bit-vector bit-vector-128)
((1 2) (error "can not convert v1 or v2 bit-vectors to instance of class `unique-universal-identifier'"))
((3 4 5) t))
(let ((tl (the uuid-ub32 (%uuid_time-low-request-bit-vector bit-vector-128)))
(tm (the uuid-ub16 (%uuid_time-mid-request-bit-vector bit-vector-128)))
(thv (the uuid-ub16 (%uuid_time-high-and-version-request-bit-vector bit-vector-128)))
(csr (the uuid-ub8 (%uuid_clock-seq-and-reserved-request-bit-vector bit-vector-128)))
(csl (the uuid-ub8 (%uuid_clock-seq-low-request-bit-vector bit-vector-128)))
(nd (the uuid-ub48 (%uuid_node-request-bit-vector bit-vector-128))))
(declare (uuid-ub32 tl)
(uuid-ub16 tm thv)
(uuid-ub8 csr csl)
(uuid-ub48 nd))
(the unique-universal-identifier
(make-instance 'unique-universal-identifier
:%uuid_time-low tl
:%uuid_time-mid tm
:%uuid_time-high-and-version thv
:%uuid_clock-seq-and-reserved csr
:%uuid_clock-seq-low csl
:%uuid_node nd))))
;;; ==============================
;;; :DEPRECATED
;;; ==============================
;;
;;
;; (defmacro declared-uuid-array-zeroed-of-size (size array-type array-elt-type)
; ; ( macroexpand-1 ' ( declared - uuid - array - zeroed - of - size 16 uuid - byte - ) )
;; `(the ,array-type
;; (make-array ,size :element-type ',array-elt-type :initial-element 0)))
;;
;; (defmacro declared-uuid-bit-vector-of-size-zeroed (size bit-vector-type)
; ; ( macroexpand-1 ' ( declared - uuid - bit - vector - of - size - zeroed 16 uuid - bit - vector-16 ) )
;; ;; `(the ,bit-vector-type (make-array ,size :element-type 'bit :initial-element 0))
;; `(declared-uuid-array-zeroed-of-size ,size ,bit-vector-type bit))
;;
( - vector - zeroed ( zeroed - size )
;; ;; (macroexpand-1 (def-uuid-bit-vector-zeroed
;; (let ((interned-bv-zeroed-name (%def-uuid-format-and-intern-symbol "UUID-BIT-VECTOR-~D-ZEROED" zeroed-size)))
;; `(defun ,interned-bv-zeroed-name ()
;; (uuid-bit-vector-of-size-zeroed ,zeroed-size))))
;;
;; (defun uuid-bit-vector-of-size-zeroed (size)
;; (declare (uuid-bit-vector-valid-length size)
( optimize ( speed 3 ) ) )
;; (etypecase size
;; (uuid-bit-vector-128-length
;; (declared-uuid-bit-vector-of-size-zeroed size uuid-bit-vector-128))
( uuid - bit - vector-48 - length
;; (declared-uuid-bit-vector-of-size-zeroed size uuid-bit-vector-48))
;; (uuid-bit-vector-32-length
;; (declared-uuid-bit-vector-of-size-zeroed size uuid-bit-vector-32))
;; (uuid-bit-vector-16-length
;; (declared-uuid-bit-vector-of-size-zeroed size uuid-bit-vector-16))
;; (uuid-bit-vector-8-length
;; (declared-uuid-bit-vector-of-size-zeroed size uuid-bit-vector-8))))
;;
;; :NOTE For both `uuid-bit-vector-128-zeroed' and `uuid-bit-vector-8-zeroed' we
assume that the returned array is always of type : ( simple - bit - vector 128 )
;; :SEE `uuid-verify-bit-vector-simplicity' in :FILE uuid-types.lisp
;; (declaim (inline uuid-bit-vector-128-zeroed))
;; (defun uuid-bit-vector-128-zeroed ()
( declare ( optimize ( speed 3 ) ) )
; ; ( the uuid - bit - vector-128 ( make - array 128 : element - type ' bit : initial - element 0 ) )
( uuid - bit - vector - of - size - zeroed 128 ) )
;;
;; (declaim (inline uuid-bit-vector-32-zeroed))
;; (defun uuid-bit-vector-32-zeroed ()
( declare ( optimize ( speed 3 ) ) )
; ; ( the uuid - bit - vector-32 ( make - array 32 : element - type ' bit : initial - element 0 ) ) )
( uuid - bit - vector - of - size - zeroed 32 ) )
;;
;; (declaim (inline uuid-bit-vector-16-zeroed))
;; (defun uuid-bit-vector-16-zeroed ()
( declare ( optimize ( speed 3 ) ) )
; ; ( the uuid - bit - vector-16 ( make - array 16 : element - type ' bit : initial - element 0 ) )
( uuid - bit - vector - of - size - zeroed 16 ) )
;;
;; (declaim (inline uuid-bit-vector-8-zeroed))
;; (defun uuid-bit-vector-8-zeroed ()
( declare ( optimize ( speed 3 ) ) )
; ; ( the uuid - bit - vector-8 ( make - array 8 : element - type ' bit : initial - element 0 ) )
;; (uuid-bit-vector-of-size-zeroed 8))
;;; ==============================
;;; ==============================
;;; ==============================
;;; ==============================
;;; ==============================
;; :SOURCE (URL `#p6269')
;; (defun uuid-bit-vector-to-integer (bit-vector)
;; "Return BIT-VECTOR's representation as a positive integer."
;; ;; (= (bit-vector-to-integer (uuid- (make-v4-uuid)
; ; 122378404974049034400182615604361091930 )
;; (declare (bit-vector bit-vector)
( optimize ( speed 3 ) ) )
;; ;; :NOTE We ought to be able to optimize around the size of expected return
;; ;; value by taking the length of the bv which should not exceed the
;; ;; integer-length of final return value.
( flet ( ( bit - adder ( first - bit second - bit )
( + ( ash first - bit 1 ) second - bit ) ) )
;; (etypecase bit-vector
;; (simple-bit-vector
;; (locally (declare (simple-bit-vector bit-vector))
;; (reduce #'bit-adder bit-vector)))
;; (bit-vector
;; (reduce #'bit-adder bit-vector)))))
;;; ==============================
: PASTE - DATE 2011 - 08 - 10
: PASTE - TITLE " Annotation number 1 : another version "
: PASTED - BY
;; :PASTE-URL (URL `/+2NN1/1')
;; (defun uuid-bit-vector-to-integer (bit-vector)
;; "Return BIT-VECTOR's representation as a positive integer."
;; (let ((j 0))
;; (dotimes (i (length bit-vector) j)
;; (setf j (logior (bit bit-vector i)
;; (ash j 1))))))
;;; ==============================
: PASTE - DATE 2011 - 08 - 10
: PASTE - TITLE " Annotation number 2 : a faster version "
: PASTED - BY stassats
;; :PASTE-URL (URL `/+2NN1/2')
;; (defun uuid-bit-vector-to-integer (bit-vector) ;; (uuid-bit-vector <SIZE>)
;; (let* ((bv-length (length bit-vector)) ;; uuid-ub128-integer-length
( word - size 64 ) ; ; ( ash bv - length 1 ) ; ; uuid - ub128 - integer - length
;; (result 0)
;; (index -1))
;; (flet ((build-word ()
;; (loop
;; repeat word-size
;; for j = 0 then (logior (bit bit-vector (incf index))
;; (ash j 1))
;; finally (return j))))
;; (loop
;; repeat (floor bv-length word-size)
do ( setf result ( logior ( build - word )
;; (ash result (1- word-size)))))
;; (loop
;; while (< index (1- bv-length))
do ( setf result ( logior ( bit bit - vector ( incf index ) )
( ash result 1 ) ) ) ) )
;; result))
;;; ==============================
;;; ==============================
;;; ==============================
;;; ==============================
;; Local Variables:
;; indent-tabs-mode: nil
;; show-trailing-whitespace: t
;; mode: lisp-interaction
;; package: unicly
;; End:
;;; ==============================
EOF
| null |
https://raw.githubusercontent.com/mon-key/unicly/f9bd21446f35e28766d2f1ada2741399b14d93cb/unicly-bit-vectors.lisp
|
lisp
|
:FILE unicly/unicly-bit-vectors.lisp
==============================
==============================
:NOTE Per RFC 4.1.3 bit 48 should always be 0.
The UUIDs bit-vector representation
(uuid-to-bit-vector (make-v5-uuid *uuid-namespace-dns* "bubba"))
! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
#*11101110101000010001000001011110001101101000000101010001000101111001100110110110011110110010101101011111111000011111001111000111
The UUIDs binary integer representation:
#b11101110101000010001000001011110001101101000000101010001000101111001100110110110011110110010101101011111111000011111001111000111
(uuid-to-byte-array (make-v5-uuid *uuid-namespace-dns* "bubba"))
(map 'list #'uuid-octet-to-bit-vector-8 (uuid-to-byte-array (make-v5-uuid *uuid-namespace-dns* "bubba")))
(uuid-byte-array-to-bit-vector (uuid-to-byte-array (make-v5-uuid *uuid-namespace-dns* "bubba")))
=> #*11101110101000010001000001011110001101101000000101010001000101111001100110110110011110110010101101011111111000011111001111000111
The upper bounds of a UUID in binary integer representation:
#b11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
The number of unsigned bits used to represent the upper bounds of a UUIDs
integer representation:
The octet count of the upper bounds of a UUIDs integer representation:
quintillion three hundred seventy-four quadrillion six hundred seven trillion
eleven thousand four hundred fifty-five
The octet offsets into a uuid-bit-vector-128:
(loop
for q = 0 then x
collect (list q y))
; % uuid_time - low
; % uuid_time - mid
; % uuid_time - high - and - version
; % uuid_clock - seq - and - reserved
; % uuid_clock - seq - low
; % uuid_nodede
==============================
*package*
uuid-bit-vector-<N>-zeroed
(uuid-bit-vector-32-zeroed)
(uuid-version-bit-vector (uuid-bit-vector-32-zeroed))
(typep (uuid-bit-vector-128-zeroed) 'uuid-bit-vector-128)
==============================
the current implementation using `sb-int:bit-vector-=':
(let ((bv (uuid-bit-vector-128-zeroed)))
(null (uuid-bit-vector-eql (uuid-bit-vector-128-zeroed) bv)))
following errors succesfully:
(uuid-bit-vector-eql (uuid-bit-vector-128-zeroed) "bubba")
So we added `uuid-bit-vector-128-check-type' -- should be no way for it to fail.
uuid-bit-vector-eql should catch non uuid-bit-vector-128s
:NOTE The type unicly::uuid-bit-vector-null is a satisfies of %uuid-bit-vector-null-p
:SOURCE (URL `/+2LKZ/2')
(uuid-byte-array-16-check-type uuid-byte-array))
,----
| DISPLACED-TO each ‘nil’, then the result is a simple array. If
| DISPLACED-TO being true, whether the resulting array is a simple array
| is implementation-dependent.
`----
(and (bit-vector 8) (not simple-array))
==============================
(uuid-to-bit-vector (make-v5-uuid *uuid-namespace-dns* "ḻfḉḲíï<òbG¦>GḜîṉí@B3Áû?ḹ<mþḩú'ÁṒ¬&]Ḏ"))
(uuid-bit-vector-to-integer (uuid-to-bit-vector (make-v5-uuid *uuid-namespace-dns* "ḻfḉḲíï<òbG¦>GḜîṉí@B3Áû?ḹ<mþḩú'ÁṒ¬&]Ḏ")))
:TEST (signals succesfully)
(let ((bv-z (uuid-bit-vector-128-zeroed)))
(%uuid-version-bit-vector-if bv-z))
(%uuid-version-bit-vector-if (uuid-bit-vector-32-zeroed))
(uuid-version-bit-vector (uuid-bit-vector-32-zeroed))
==============================
However, it doesn't say anything about the version 0 UUID...
Of course it wouldn't given how C centric nature of the entire RFC :)
So, as a way of flipping the bird to the curly brace inclined we
choose to return as if by `cl:values': 0, null-uuid
(uuid-bit-vector-v3-p (uuid-to-bit-vector (make-v3-uuid (make-v4-uuid) "bubba")))
(uuid-bit-vector-v4-p (uuid-to-bit-vector (make-v4-uuid)))
(uuid-bit-vector-v5-p (uuid-to-bit-vector (make-v5-uuid (make-v4-uuid) "bubba")))
==============================
(defun number-to-bit-vector (unsigned-integer)
(declare ((integer 0 *) unsigned-integer)
(flet ((number-to-bit-vector-fixnum (fixnum-int)
(declare (fixnum-0-or-over fixnum-int))
(let* ((mk-len (the fixnum-bit-width (integer-length fixnum-int)))
(bv-29 (make-array (the fixnum-bit-width mk-len)
:element-type 'bit
:initial-element 0
:adjustable nil)))
(declare (fixnum-bit-width mk-len)
(simple-bit-vector bv-29))
(loop
for i-lb from 0 below mk-len
do (and (logbitp i-lb fixnum-int)
(setf (sbit bv-29 i-lb) 1))
(number-to-bit-vector-bignum (bignum-int)
(declare (bignum-0-or-over bignum-int))
(let* ((mk-big-len (the bignum-bit-width (integer-length bignum-int)))
(bv-big (make-array (the bignum-bit-width mk-big-len)
:element-type 'bit
:initial-element 0
:adjustable nil)))
(declare (bignum-bit-width mk-big-len)
(simple-bit-vector bv-big))
(loop
for i-lb from 0 below mk-big-len
do (and (logbitp i-lb bignum-int)
(etypecase unsigned-integer
(fixnum-0-or-over (the simple-bit-vector
(number-to-bit-vector-fixnum
(the fixnum-0-or-over unsigned-integer))))
(bignum-0-or-over (the simple-bit-vector
(number-to-bit-vector-bignum
(the bignum-0-or-over unsigned-integer)))))))
:TODO incorporate trivial-features so we can test for :big-endian :little-endian
*features*
#+big-endian (return bv-big))
==============================
(floor bv-length word-size)
`%uuid_node'
`%uuid_time-low'
`%uuid_time-mid', `%uuid_time-high-and-version'
`%uuid_clock-seq-and-reserved', `%uuid_clock-seq-low'
:NOTE before `def-uuid-request-integer-bit-vector' expansion.
==============================
:NOTE `def-uuid-request-integer-bit-vector' defines the following functions:
==============================
:DEPRECATED
==============================
(defmacro declared-uuid-array-zeroed-of-size (size array-type array-elt-type)
; ( macroexpand-1 ' ( declared - uuid - array - zeroed - of - size 16 uuid - byte - ) )
`(the ,array-type
(make-array ,size :element-type ',array-elt-type :initial-element 0)))
(defmacro declared-uuid-bit-vector-of-size-zeroed (size bit-vector-type)
; ( macroexpand-1 ' ( declared - uuid - bit - vector - of - size - zeroed 16 uuid - bit - vector-16 ) )
;; `(the ,bit-vector-type (make-array ,size :element-type 'bit :initial-element 0))
`(declared-uuid-array-zeroed-of-size ,size ,bit-vector-type bit))
;; (macroexpand-1 (def-uuid-bit-vector-zeroed
(let ((interned-bv-zeroed-name (%def-uuid-format-and-intern-symbol "UUID-BIT-VECTOR-~D-ZEROED" zeroed-size)))
`(defun ,interned-bv-zeroed-name ()
(uuid-bit-vector-of-size-zeroed ,zeroed-size))))
(defun uuid-bit-vector-of-size-zeroed (size)
(declare (uuid-bit-vector-valid-length size)
(etypecase size
(uuid-bit-vector-128-length
(declared-uuid-bit-vector-of-size-zeroed size uuid-bit-vector-128))
(declared-uuid-bit-vector-of-size-zeroed size uuid-bit-vector-48))
(uuid-bit-vector-32-length
(declared-uuid-bit-vector-of-size-zeroed size uuid-bit-vector-32))
(uuid-bit-vector-16-length
(declared-uuid-bit-vector-of-size-zeroed size uuid-bit-vector-16))
(uuid-bit-vector-8-length
(declared-uuid-bit-vector-of-size-zeroed size uuid-bit-vector-8))))
:NOTE For both `uuid-bit-vector-128-zeroed' and `uuid-bit-vector-8-zeroed' we
:SEE `uuid-verify-bit-vector-simplicity' in :FILE uuid-types.lisp
(declaim (inline uuid-bit-vector-128-zeroed))
(defun uuid-bit-vector-128-zeroed ()
; ( the uuid - bit - vector-128 ( make - array 128 : element - type ' bit : initial - element 0 ) )
(declaim (inline uuid-bit-vector-32-zeroed))
(defun uuid-bit-vector-32-zeroed ()
; ( the uuid - bit - vector-32 ( make - array 32 : element - type ' bit : initial - element 0 ) ) )
(declaim (inline uuid-bit-vector-16-zeroed))
(defun uuid-bit-vector-16-zeroed ()
; ( the uuid - bit - vector-16 ( make - array 16 : element - type ' bit : initial - element 0 ) )
(declaim (inline uuid-bit-vector-8-zeroed))
(defun uuid-bit-vector-8-zeroed ()
; ( the uuid - bit - vector-8 ( make - array 8 : element - type ' bit : initial - element 0 ) )
(uuid-bit-vector-of-size-zeroed 8))
==============================
==============================
==============================
==============================
==============================
:SOURCE (URL `#p6269')
(defun uuid-bit-vector-to-integer (bit-vector)
"Return BIT-VECTOR's representation as a positive integer."
;; (= (bit-vector-to-integer (uuid- (make-v4-uuid)
; 122378404974049034400182615604361091930 )
(declare (bit-vector bit-vector)
;; :NOTE We ought to be able to optimize around the size of expected return
;; value by taking the length of the bv which should not exceed the
;; integer-length of final return value.
(etypecase bit-vector
(simple-bit-vector
(locally (declare (simple-bit-vector bit-vector))
(reduce #'bit-adder bit-vector)))
(bit-vector
(reduce #'bit-adder bit-vector)))))
==============================
:PASTE-URL (URL `/+2NN1/1')
(defun uuid-bit-vector-to-integer (bit-vector)
"Return BIT-VECTOR's representation as a positive integer."
(let ((j 0))
(dotimes (i (length bit-vector) j)
(setf j (logior (bit bit-vector i)
(ash j 1))))))
==============================
:PASTE-URL (URL `/+2NN1/2')
(defun uuid-bit-vector-to-integer (bit-vector) ;; (uuid-bit-vector <SIZE>)
(let* ((bv-length (length bit-vector)) ;; uuid-ub128-integer-length
; ( ash bv - length 1 ) ; ; uuid - ub128 - integer - length
(result 0)
(index -1))
(flet ((build-word ()
(loop
repeat word-size
for j = 0 then (logior (bit bit-vector (incf index))
(ash j 1))
finally (return j))))
(loop
repeat (floor bv-length word-size)
(ash result (1- word-size)))))
(loop
while (< index (1- bv-length))
result))
==============================
==============================
==============================
==============================
Local Variables:
indent-tabs-mode: nil
show-trailing-whitespace: t
mode: lisp-interaction
package: unicly
End:
==============================
|
: FILE - CREATED < Timestamp : # { 2011 - 08 - 13T19:18:12 - 04:00Z}#{11326 } - by MON >
The UUID as bit field :
WEIGHT INDEX OCTETS BIT - FIELD - PER - OCTET
4 | ( 0 31 ) | 255 255 255 255 | # * 11111111 # * 11111111 # * 11111111 # * 11111111 | % uuid_time - low | uuid - ub32
2 | ( 32 47 ) | 255 255 | # * 11111111 # * 11111111 | % uuid_time - mid | uuid - ub16
2 | ( 48 63 ) | 255 255 | # * 11111111 # * 11111111 | % uuid_time - high - and - version
1 | ( 64 71 ) | 255 | # * 11111111 | % uuid_clock - seq - and - reserved | uuid - ub8
1 | ( 72 79 ) | 255 | # * 11111111 | % uuid_clock - seq - low | uuid - ub8
6 | ( 80 127 ) | 255 255 255 255 255 255 | # * 11111111 # * 11111111 # * 11111111 # * 11111111 # * 11111111 # * 11111111 | % uuid_node | uuid - ub48
0 7 15 23 31 39 47 55 63 71 79 87 95 103 111 119 127
= > 317192554773903544674993329975922389959
The byte - array reresentation :
( uuid - integer-128 - to - byte - array 317192554773903544674993329975922389959 )
= > # ( 238 161 16 94 54 129 81 23 153 182 123 43 95 225 243 199 )
= > # ( 238 161 16 94 54 129 81 23 153 182 123 43 95 225 243 199 )
= > ( # * 11101110 # * 10100001 # * 00010000 # * 01011110 # * 00110110 # * 10000001 # * 01010001
# * 00010111 # * 10011001 # * 10110110 # * 01111011 # * 00101011 # * 01011111 # * 11100001
# * 11110011 # * 11000111 )
= > 340282366920938463463374607431768211455
( integer - length 340282366920938463463374607431768211455 )
= > 128
( truncate ( integer - length 340282366920938463463374607431768211455 ) 8)
= > 16
The upper bounds of UUID in decimal ( longform ):
( format t " ~R " 340282366920938463463374607431768211455 )
= > three hundred forty undecillion two hundred eighty - two decillion three hundred
sixty - six nonillion nine hundred twenty octillion nine hundred thirty - eight
septillion four hundred sixty - three sextillion four hundred sixty - three
four hundred thirty - one billion seven hundred sixty - eight million two hundred
for x from 0 below 128 by 8
as y = 7 then ( + x 7 )
( 80 87 ) ( 88 95 ) ( 96 103 )
(in-package #:unicly)
(declaim (inline uuid-bit-vector-128-zeroed
uuid-bit-vector-48-zeroed
uuid-bit-vector-32-zeroed
uuid-bit-vector-16-zeroed
uuid-bit-vector-8-zeroed))
(def-uuid-bit-vector-zeroed 128)
(def-uuid-bit-vector-zeroed 48)
(def-uuid-bit-vector-zeroed 32)
(def-uuid-bit-vector-zeroed 16)
(def-uuid-bit-vector-zeroed 8)
: NOTE For 1mil comparisons of two uuid - bit - vectors following timing support
comparison with ` cl : equal ' completes in 251,812,778 cycles , 0.083328 run - time
comparison with ` sb - int : bit - vector-= ' without declarations completes in in ~191,959,447 cycles , 0.063329 run - time
comparison with ` sb - int : bit - vector-= ' with declartions completes in ~170,661,197 , 0.05555199 run - time
The alternative definition is not altogether inferior but ca n't be made surpass SBCL 's internal transforms
( setf ( sbit bv 127 ) 1 )
(defun uuid-bit-vector-eql (uuid-bv-a uuid-bv-b)
(declare
: NOTE safety 2 required if we want to ensure Python sniffs around for bv length
(inline uuid-bit-vector-128-check-type)
( optimize ( speed 3 ) ( safety 2 ) ) )
(optimize (speed 3)))
(uuid-bit-vector-128-check-type uuid-bv-a)
(uuid-bit-vector-128-check-type uuid-bv-b)
(locally
(declare (type uuid-bit-vector-128 uuid-bv-a uuid-bv-b)
(optimize (speed 3) (safety 0)))
#-:sbcl
(if (and (= (count 0 uuid-bv-a :test #'=) (count 0 uuid-bv-b :test #'=))
(= (count 1 uuid-bv-a :test #'=) (count 1 uuid-bv-b :test #'=)))
(loop
for low-idx from 0 below 64
for top-idx = (logxor low-idx 127)
always (and (= (sbit uuid-bv-a low-idx) (sbit uuid-bv-b low-idx))
(= (sbit uuid-bv-a top-idx) (sbit uuid-bv-b top-idx)))))
#+:sbcl (SB-INT:BIT-VECTOR-= uuid-bv-a uuid-bv-b)))
(defun %uuid-bit-vector-null-p (bit-vector-maybe-null)
(declare (uuid-bit-vector-128 bit-vector-maybe-null)
(inline uuid-bit-vector-128-zeroed)
(optimize (speed 3)))
(the (values (member t nil) &optional)
(uuid-bit-vector-eql bit-vector-maybe-null (the uuid-bit-vector-128 (uuid-bit-vector-128-zeroed)))))
(declaim (inline uuid-bit-vector-null-p))
(defun uuid-bit-vector-null-p (bit-vector-maybe-null)
(declare (optimize (speed 3)))
(the boolean (typep bit-vector-maybe-null 'uuid-bit-vector-null)))
: COURTESY : DATE 2011 - 04 - 08
(defun uuid-octet-to-bit-vector-8 (octet)
(declare (type uuid-ub8 octet)
(inline uuid-bit-vector-8-zeroed)
(optimize (speed 3)))
(let ((bv8 (the uuid-bit-vector-8 (uuid-bit-vector-8-zeroed))))
(declare (uuid-bit-vector-8 bv8))
(dotimes (i 8 bv8)
(setf (sbit bv8 i) (ldb (byte 1 7) octet))
(setf octet (logand #xFF (ash octet 1))))))
(declaim (inline uuid-deposit-octet-to-bit-vector))
(defun uuid-deposit-octet-to-bit-vector (octet offset uuid-bv)
(declare (uuid-ub8 octet)
(uuid-ub128-integer-length offset)
(uuid-bit-vector-128 uuid-bv)
(optimize (speed 3)))
(loop
for idx upfrom offset below (+ offset 8)
do (setf (sbit uuid-bv idx) (ldb (byte 1 7) octet))
(setf octet (logand #xFF (ash octet 1)))
finally (return uuid-bv)))
(defun uuid-byte-array-to-bit-vector (uuid-byte-array)
(declare (uuid-byte-array-16 uuid-byte-array)
(inline uuid-deposit-octet-to-bit-vector
%uuid-byte-array-null-p)
(optimize (speed 3)))
(let ((uuid-bv128 (the uuid-bit-vector-128 (uuid-bit-vector-128-zeroed))))
(declare (uuid-bit-vector-128 uuid-bv128))
(when (%uuid-byte-array-null-p uuid-byte-array)
(return-from uuid-byte-array-to-bit-vector uuid-bv128))
(loop
for byte across uuid-byte-array
for offset upfrom 0 by 8 below 128
do (uuid-deposit-octet-to-bit-vector byte offset uuid-bv128)
finally (return (the uuid-bit-vector-128 uuid-bv128)))))
(defun uuid-bit-vector-to-byte-array (uuid-bv-128)
(declare (uuid-bit-vector-128 uuid-bv-128)
(optimize (speed 3)))
(uuid-bit-vector-128-check-type uuid-bv-128)
(when (uuid-bit-vector-null-p uuid-bv-128)
(return-from uuid-bit-vector-to-byte-array (the uuid-byte-array-16 (uuid-byte-array-16-zeroed))))
(labels ((displaced-8 (disp-off)
(declare (optimize (speed 3)))
(the (bit-vector 8)
(make-array 8
:element-type 'bit
:displaced-to uuid-bv-128
:displaced-index-offset disp-off)))
| If ` make - array ' is called with ADJUSTABLE , FILL - POINTER , and
| ‘ make - array ’ is called with one or more of ADJUSTABLE , FILL - POINTER , or
On SBCL bv8 is of type :
(bv8-to-ub8 (bv8)
(declare ((bit-vector 8) bv8)
(optimize (speed 3)))
(let ((j 0))
(declare (uuid-ub8 j))
(dotimes (i 8 (the uuid-ub8 j))
(setf j (logior (bit bv8 i) (ash j 1))))))
(get-bv-octets ()
(let ((rtn (uuid-byte-array-16-zeroed))
(offsets (loop
with offsets-array = (uuid-byte-array-16-zeroed)
for idx from 0 below 16
for bv-offset from 0 below 128 by 8
do (setf (aref offsets-array idx) bv-offset)
finally (return offsets-array))))
(declare (uuid-byte-array-16 rtn offsets))
(loop
for off across offsets
for idx from 0 below 16
for octet of-type uuid-ub8 = (bv8-to-ub8 (displaced-8 off))
do (setf (aref rtn idx) octet)
finally (return rtn)))))
(the uuid-byte-array-16 (get-bv-octets))))
: NOTE Return value has the integer representation : 267678999922476945140730988764022209929
(defun uuid-to-bit-vector (uuid)
(declare (type unique-universal-identifier uuid)
(inline uuid-disassemble-ub32
uuid-disassemble-ub16
uuid-bit-vector-128-zeroed
%unique-universal-identifier-null-p)
(optimize (speed 3)))
(when (%unique-universal-identifier-null-p uuid)
(return-from uuid-to-bit-vector (uuid-bit-vector-128-zeroed)))
(let ((bv-lst
(with-slots (%uuid_time-low %uuid_time-mid %uuid_time-high-and-version
%uuid_clock-seq-and-reserved %uuid_clock-seq-low %uuid_node)
uuid
(declare (uuid-ub32 %uuid_time-low)
(uuid-ub16 %uuid_time-mid %uuid_time-high-and-version)
(uuid-ub8 %uuid_clock-seq-and-reserved %uuid_clock-seq-low)
(uuid-ub48 %uuid_node))
(multiple-value-call #'list
(uuid-disassemble-ub32 %uuid_time-low)
(uuid-disassemble-ub16 %uuid_time-mid)
(uuid-disassemble-ub16 %uuid_time-high-and-version)
%uuid_clock-seq-and-reserved
%uuid_clock-seq-low
(uuid-disassemble-ub48 %uuid_node))))
(uuid-bv128 (the uuid-bit-vector-128 (uuid-bit-vector-128-zeroed))))
(declare (list bv-lst) (uuid-bit-vector-128 uuid-bv128))
(loop
for byte in bv-lst
for offset upfrom 0 by 8 below 128
do (uuid-deposit-octet-to-bit-vector (the uuid-ub8 byte) offset uuid-bv128)
finally (return uuid-bv128))))
(declaim (inline %uuid-version-bit-vector-if))
(defun %uuid-version-bit-vector-if (uuid-bit-vector)
( setf ( sbit bv - z 48 ) 1 )
(declare (inline uuid-bit-vector-128-check-type)
(optimize (speed 3)))
(uuid-bit-vector-128-check-type uuid-bit-vector)
(locally (declare
(uuid-bit-vector-128 uuid-bit-vector)
(optimize (speed 3) (safety 0)))
(unless (zerop (sbit uuid-bit-vector 48))
(error 'uuid-bit-48-error :uuid-bit-48-error-datum uuid-bit-vector))))
48 49 50 51
| 0 0 0 1 | 1 The time - based version specified in this document .
| 0 0 1 0 | 2 DCE Security version , with embedded POSIX UIDs .
| 0 0 1 1 | 3 The name - based MD5
| 0 1 0 0 | 4 The randomly or pseudo - randomly generated version
| 0 1 0 1 | 5 The name - based SHA-1
(declaim (inline uuid-version-bit-vector))
(defun uuid-version-bit-vector (uuid-bit-vector)
(declare (uuid-bit-vector-128 uuid-bit-vector)
(inline %uuid-version-bit-vector-if
uuid-bit-vector-128-zeroed
uuid-bit-vector-null-p)
(optimize (speed 3)))
(%uuid-version-bit-vector-if uuid-bit-vector)
(ecase (the bit (sbit uuid-bit-vector 49))
(0 (ecase (the bit (sbit uuid-bit-vector 50))
(1 (ecase (the bit (sbit uuid-bit-vector 51))
(1 3)
(0 2)))
(0 (ecase (the bit (sbit uuid-bit-vector 51))
(1 1)
RFC4122 Setion 4.1.7 . " Nil UUID " specifically requires a null UUID
(0 (values (or (and (uuid-bit-vector-null-p uuid-bit-vector) 0)
(error "something wrong with UUID-BIT-VECTOR bit field~% got: ~S" uuid-bit-vector))
'null-uuid))))))
(1 (ecase (the bit (sbit uuid-bit-vector 51))
(0 4)
(1 5)))))
(declaim (inline uuid-bit-vector-v3-p))
(defun uuid-bit-vector-v3-p (uuid-bit-vector)
(declare (uuid-bit-vector-128 uuid-bit-vector)
(inline uuid-version-bit-vector)
(optimize (speed 3)))
(let ((v3-if (uuid-version-bit-vector uuid-bit-vector)))
(declare (uuid-version-int v3-if))
(the boolean
(and (logbitp 1 v3-if) (logbitp 0 v3-if) t))))
(declaim (inline uuid-bit-vector-v4-p))
(defun uuid-bit-vector-v4-p (uuid-bit-vector)
(declare (uuid-bit-vector-128 uuid-bit-vector)
(inline uuid-version-bit-vector)
(optimize (speed 3)))
(let ((v4-if (uuid-version-bit-vector uuid-bit-vector)))
(declare (uuid-version-int v4-if))
(the boolean
(zerop (logior (logxor v4-if 4) 0)))))
(declaim (inline uuid-bit-vector-v5-p))
(defun uuid-bit-vector-v5-p (uuid-bit-vector)
(declare (uuid-bit-vector-128 uuid-bit-vector)
(inline uuid-version-bit-vector)
(optimize (speed 3)))
(let ((v5-if (uuid-version-bit-vector uuid-bit-vector)))
(declare (uuid-version-int v5-if))
(the boolean
(and (logbitp 2 v5-if) (logbitp 0 v5-if) t))))
( optimize ( speed 3 ) ) )
finally ( return ( nreverse bv-29 ) ) ) ) )
( setf ( sbit bv - big i - lb ) 1 ) )
finally ( return ( nreverse bv - big ) ) ) ) ) )
(defun uuid-integer-128-to-bit-vector (uuid-integer-128)
(declare (uuid-ub128 uuid-integer-128)
(optimize (speed 3)))
(let ((mk-big-len (the uuid-ub128-integer-length (integer-length uuid-integer-128)))
(bv-big (the uuid-bit-vector-128 (uuid-bit-vector-128-zeroed))))
(declare (uuid-ub128-integer-length mk-big-len)
(uuid-bit-vector-128 bv-big))
(loop
for i-lb from 0 below mk-big-len
do (and (logbitp i-lb uuid-integer-128)
(setf (sbit bv-big i-lb) 1))
# + little - endian ( return ( nreverse bv - big ) )
finally (return (nreverse bv-big)))))
: NOTE Following modeled after Stas 's inclued at bottom of file :
(defun uuid-bit-vector-to-integer (bit-vector)
(declare (uuid-bit-vector bit-vector)
(optimize (speed 3)))
(let* ((bv-length (the uuid-ub128-integer-length (length bit-vector)))
(word-size (ash bv-length -1))
in this case always two ?
(result 0)
(index -1))
(labels ((build-word ()
(loop
repeat word-size
for j = 0 then (logior (sbit bit-vector (incf index))
(ash j 1))
finally (return j)))
(loop-repeats ()
(loop
do (setf result (logior (build-word)
(ash result (1- word-size))))))
(loop-less-index ()
(loop
while (< index (1- bv-length))
do (setf result (logior (sbit bit-vector (incf index))
(ash result 1)))))
(loop-and-return ()
(loop-repeats)
(loop-less-index)
result)
(get-bv-128-int ()
(declare (uuid-bit-vector-128 bit-vector)
(uuid-bit-vector-128-length bv-length)
((uuid-bit-vector-length 64) word-size))
(the uuid-ub128 (loop-and-return)))
(get-bv-48-int ()
(declare (uuid-bit-vector-48 bit-vector)
(uuid-bit-vector-48-length bv-length)
((uuid-bit-vector-length 24) word-size))
(the uuid-ub48 (loop-and-return)))
(get-bv-32-int ()
(declare (uuid-bit-vector-32 bit-vector)
(uuid-bit-vector-32-length bv-length)
(uuid-bit-vector-16-length word-size))
(the uuid-ub32 (loop-and-return)))
(get-bv-16-int ()
(declare (uuid-bit-vector-16 bit-vector)
(uuid-bit-vector-16-length bv-length)
(uuid-bit-vector-8-length word-size))
(the uuid-ub16 (loop-and-return)))
(get-bv-8-int ()
(declare (uuid-bit-vector-8 bit-vector)
(uuid-bit-vector-8-length bv-length)
((uuid-bit-vector-length 4) word-size))
(the uuid-ub8 (loop-and-return))))
(etypecase bv-length
(uuid-bit-vector-128-length (get-bv-128-int))
(uuid-bit-vector-48-length (get-bv-48-int))
(uuid-bit-vector-32-length (get-bv-32-int))
(uuid-bit-vector-16-length (get-bv-16-int))
(uuid-bit-vector-8-length (get-bv-8-int))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun uuid-bit-vector-build-offsets (bit-offset bit-width)
(declare (uuid-bit-vector-valid-bit-offset bit-offset)
(uuid-bit-vector-valid-bit-width bit-width)
(optimize (speed 3) (safety 2)))
(loop
for x from bit-offset below (+ bit-offset bit-width) by 8
for q = bit-offset then x
as y = (cons q (+ x 7))
collect y))
)
(declaim (inline %uuid_time-low-request-bit-vector
%uuid_time-mid-request-bit-vector
%uuid_time-high-and-version-request-bit-vector
%uuid_clock-seq-and-reserved-request-bit-vector
%uuid_clock-seq-low-request-bit-vector
%uuid_node-request-bit-vector))
(def-uuid-request-integer-bit-vector "time-low" 0 32)
(def-uuid-request-integer-bit-vector "time-mid" 32 16)
(def-uuid-request-integer-bit-vector "time-high-and-version" 48 16)
(def-uuid-request-integer-bit-vector "clock-seq-and-reserved" 64 8)
(def-uuid-request-integer-bit-vector "clock-seq-low" 72 8)
(def-uuid-request-integer-bit-vector "node" 80 48)
(defun uuid-from-bit-vector (bit-vector-128)
(declare (inline %uuid_time-low-request-bit-vector
%uuid_time-mid-request-bit-vector
%uuid_time-high-and-version-request-bit-vector
%uuid_clock-seq-and-reserved-request-bit-vector
%uuid_clock-seq-low-request-bit-vector
%uuid_node-request-bit-vector
uuid-bit-vector-null-p)
(uuid-bit-vector-128 bit-vector-128)
(optimize (speed 3)))
(uuid-bit-vector-128-check-type bit-vector-128)
(when (uuid-bit-vector-null-p bit-vector-128)
(return-from uuid-from-bit-vector (the unique-universal-identifier (make-null-uuid))))
(ecase (uuid-version-bit-vector bit-vector-128)
((1 2) (error "can not convert v1 or v2 bit-vectors to instance of class `unique-universal-identifier'"))
((3 4 5) t))
(let ((tl (the uuid-ub32 (%uuid_time-low-request-bit-vector bit-vector-128)))
(tm (the uuid-ub16 (%uuid_time-mid-request-bit-vector bit-vector-128)))
(thv (the uuid-ub16 (%uuid_time-high-and-version-request-bit-vector bit-vector-128)))
(csr (the uuid-ub8 (%uuid_clock-seq-and-reserved-request-bit-vector bit-vector-128)))
(csl (the uuid-ub8 (%uuid_clock-seq-low-request-bit-vector bit-vector-128)))
(nd (the uuid-ub48 (%uuid_node-request-bit-vector bit-vector-128))))
(declare (uuid-ub32 tl)
(uuid-ub16 tm thv)
(uuid-ub8 csr csl)
(uuid-ub48 nd))
(the unique-universal-identifier
(make-instance 'unique-universal-identifier
:%uuid_time-low tl
:%uuid_time-mid tm
:%uuid_time-high-and-version thv
:%uuid_clock-seq-and-reserved csr
:%uuid_clock-seq-low csl
:%uuid_node nd))))
( - vector - zeroed ( zeroed - size )
( optimize ( speed 3 ) ) )
( uuid - bit - vector-48 - length
assume that the returned array is always of type : ( simple - bit - vector 128 )
( declare ( optimize ( speed 3 ) ) )
( uuid - bit - vector - of - size - zeroed 128 ) )
( declare ( optimize ( speed 3 ) ) )
( uuid - bit - vector - of - size - zeroed 32 ) )
( declare ( optimize ( speed 3 ) ) )
( uuid - bit - vector - of - size - zeroed 16 ) )
( declare ( optimize ( speed 3 ) ) )
( optimize ( speed 3 ) ) )
( flet ( ( bit - adder ( first - bit second - bit )
( + ( ash first - bit 1 ) second - bit ) ) )
: PASTE - DATE 2011 - 08 - 10
: PASTE - TITLE " Annotation number 1 : another version "
: PASTED - BY
: PASTE - DATE 2011 - 08 - 10
: PASTE - TITLE " Annotation number 2 : a faster version "
: PASTED - BY stassats
do ( setf result ( logior ( build - word )
do ( setf result ( logior ( bit bit - vector ( incf index ) )
( ash result 1 ) ) ) ) )
EOF
|
d51e4ac53b3463f84ab8101555980f74894337faaa8f5ce8be8c72f446a8b6f4
|
ragkousism/Guix-on-Hurd
|
pki.scm
|
;;; GNU Guix --- Functional package management for GNU
Copyright © 2013 , 2014 , 2016 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU 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.
;;;
;;; GNU Guix 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 GNU . If not , see < / > .
(define-module (guix pki)
#:use-module (guix config)
#:use-module (guix pk-crypto)
#:use-module ((guix utils) #:select (with-atomic-file-output))
#:use-module ((guix build utils) #:select (mkdir-p))
#:use-module (ice-9 match)
#:use-module (ice-9 rdelim)
#:use-module (ice-9 binary-ports)
#:export (%public-key-file
%private-key-file
%acl-file
current-acl
public-keys->acl
acl->public-keys
authorized-key?
write-acl
signature-sexp
signature-subject
signature-signed-data
valid-signature?
signature-case))
;;; Commentary:
;;;
;;; Public key infrastructure for the authentication and authorization of
archive imports . This is essentially a subset of SPKI for our own
;;; purposes (see </~cme/spki.txt> and
;;; <>.)
;;;
;;; Code:
(define (public-keys->acl keys)
"Return an ACL that lists all of KEYS with a '(guix import)'
tag---meaning that all of KEYS are authorized for archive imports. Each
element in KEYS must be a canonical sexp with type 'public-key'."
Use SPKI - style ACL entry sexp for PUBLIC - KEY , authorizing imports
;; signed by the corresponding secret key (see the IETF draft at
< /~cme/spki.txt > for the ACL format . )
;;
;; Note: We always use PUBLIC-KEY to designate the subject. Someday we may
;; want to have name certificates and to use subject names instead of
;; complete keys.
`(acl ,@(map (lambda (key)
`(entry ,(canonical-sexp->sexp key)
(tag (guix import))))
keys)))
(define %acl-file
(string-append %config-directory "/acl"))
(define %public-key-file
(string-append %config-directory "/signing-key.pub"))
(define %private-key-file
(string-append %config-directory "/signing-key.sec"))
(define (ensure-acl)
"Make sure the ACL file exists, and create an initialized one if needed."
(unless (file-exists? %acl-file)
;; If there's no public key file, don't attempt to create the ACL.
(when (file-exists? %public-key-file)
(let ((public-key (call-with-input-file %public-key-file
(compose string->canonical-sexp
read-string))))
(mkdir-p (dirname %acl-file))
(with-atomic-file-output %acl-file
(lambda (port)
(write-acl (public-keys->acl (list public-key))
port)))))))
(define (write-acl acl port)
"Write ACL to PORT in canonical-sexp format."
(let ((sexp (sexp->canonical-sexp acl)))
(display (canonical-sexp->string sexp) port)))
(define (current-acl)
"Return the current ACL."
(ensure-acl)
(if (file-exists? %acl-file)
(call-with-input-file %acl-file
(compose canonical-sexp->sexp
string->canonical-sexp
read-string))
(public-keys->acl '()))) ; the empty ACL
(define (acl->public-keys acl)
"Return the public keys (as canonical sexps) listed in ACL with the '(guix
import)' tag."
(match acl
(('acl
('entry subject-keys
('tag ('guix 'import)))
...)
(map sexp->canonical-sexp subject-keys))
(_
(error "invalid access-control list" acl))))
(define* (authorized-key? key #:optional (acl (current-acl)))
"Return #t if KEY (a canonical sexp) is an authorized public key for archive
imports according to ACL."
;; Note: ACL is kept in native sexp form to make 'authorized-key?' faster,
;; by not having to convert it with 'canonical-sexp->sexp' on each call.
TODO : We could use a better data type for ACLs .
(let ((key (canonical-sexp->sexp key)))
(match acl
(('acl
('entry subject-keys
('tag ('guix 'import)))
...)
(not (not (member key subject-keys))))
(_
(error "invalid access-control list" acl)))))
(define (signature-sexp data secret-key public-key)
"Return a SPKI-style sexp for the signature of DATA with SECRET-KEY that
includes DATA, the actual signature value (with a 'sig-val' tag), and
PUBLIC-KEY (see </~cme/spki.txt> for examples.)"
(string->canonical-sexp
(format #f
"(signature ~a ~a ~a)"
(canonical-sexp->string data)
(canonical-sexp->string (sign data secret-key))
(canonical-sexp->string public-key))))
(define (signature-subject sig)
"Return the signer's public key for SIG."
(find-sexp-token sig 'public-key))
(define (signature-signed-data sig)
"Return the signed data from SIG, typically an sexp such as
(hash \"sha256\" #...#)."
(find-sexp-token sig 'data))
(define (valid-signature? sig)
"Return #t if SIG is valid."
(let* ((data (signature-signed-data sig))
(signature (find-sexp-token sig 'sig-val))
(public-key (signature-subject sig)))
(and data signature
(verify signature data public-key))))
(define* (%signature-status signature hash
#:optional (acl (current-acl)))
"Return a symbol denoting the status of SIGNATURE vs. HASH vs. ACL.
This procedure must only be used internally, because it would be easy to
forget some of the cases."
(let ((subject (signature-subject signature))
(data (signature-signed-data signature)))
(if (and data subject)
(if (authorized-key? subject acl)
(if (equal? (hash-data->bytevector data) hash)
(if (valid-signature? signature)
'valid-signature
'invalid-signature)
'hash-mismatch)
'unauthorized-key)
'corrupt-signature)))
(define-syntax signature-case
(syntax-rules (valid-signature invalid-signature
hash-mismatch unauthorized-key corrupt-signature
else)
"\
Match the cases of the verification of SIGNATURE against HASH and ACL:
- the 'valid-signature' case if SIGNATURE is indeed a signature of HASH with
a key present in ACL;
- 'invalid-signature' if SIGNATURE is incorrect;
- 'hash-mismatch' if the hash in SIGNATURE does not match HASH;
- 'unauthorized-key' if the public key in SIGNATURE is not listed in ACL;
- 'corrupt-signature' if SIGNATURE is not a valid signature sexp.
This macro guarantees at compile-time that all these cases are handled.
SIGNATURE, and ACL must be canonical sexps; HASH must be a bytevector."
;; Simple case: we only care about valid signatures.
((_ (signature hash acl)
(valid-signature valid-exp ...)
(else else-exp ...))
(case (%signature-status signature hash acl)
((valid-signature) valid-exp ...)
(else else-exp ...)))
;; Full case.
((_ (signature hash acl)
(valid-signature valid-exp ...)
(invalid-signature invalid-exp ...)
(hash-mismatch mismatch-exp ...)
(unauthorized-key unauthorized-exp ...)
(corrupt-signature corrupt-exp ...))
(case (%signature-status signature hash acl)
((valid-signature) valid-exp ...)
((invalid-signature) invalid-exp ...)
((hash-mismatch) mismatch-exp ...)
((unauthorized-key) unauthorized-exp ...)
((corrupt-signature) corrupt-exp ...)
(else (error "bogus signature status"))))))
;;; pki.scm ends here
| null |
https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/guix/pki.scm
|
scheme
|
GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix 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.
Commentary:
Public key infrastructure for the authentication and authorization of
purposes (see </~cme/spki.txt> and
<>.)
Code:
signed by the corresponding secret key (see the IETF draft at
Note: We always use PUBLIC-KEY to designate the subject. Someday we may
want to have name certificates and to use subject names instead of
complete keys.
If there's no public key file, don't attempt to create the ACL.
the empty ACL
Note: ACL is kept in native sexp form to make 'authorized-key?' faster,
by not having to convert it with 'canonical-sexp->sexp' on each call.
HASH must be a bytevector."
Simple case: we only care about valid signatures.
Full case.
pki.scm ends here
|
Copyright © 2013 , 2014 , 2016 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix pki)
#:use-module (guix config)
#:use-module (guix pk-crypto)
#:use-module ((guix utils) #:select (with-atomic-file-output))
#:use-module ((guix build utils) #:select (mkdir-p))
#:use-module (ice-9 match)
#:use-module (ice-9 rdelim)
#:use-module (ice-9 binary-ports)
#:export (%public-key-file
%private-key-file
%acl-file
current-acl
public-keys->acl
acl->public-keys
authorized-key?
write-acl
signature-sexp
signature-subject
signature-signed-data
valid-signature?
signature-case))
archive imports . This is essentially a subset of SPKI for our own
(define (public-keys->acl keys)
"Return an ACL that lists all of KEYS with a '(guix import)'
tag---meaning that all of KEYS are authorized for archive imports. Each
element in KEYS must be a canonical sexp with type 'public-key'."
Use SPKI - style ACL entry sexp for PUBLIC - KEY , authorizing imports
< /~cme/spki.txt > for the ACL format . )
`(acl ,@(map (lambda (key)
`(entry ,(canonical-sexp->sexp key)
(tag (guix import))))
keys)))
(define %acl-file
(string-append %config-directory "/acl"))
(define %public-key-file
(string-append %config-directory "/signing-key.pub"))
(define %private-key-file
(string-append %config-directory "/signing-key.sec"))
(define (ensure-acl)
"Make sure the ACL file exists, and create an initialized one if needed."
(unless (file-exists? %acl-file)
(when (file-exists? %public-key-file)
(let ((public-key (call-with-input-file %public-key-file
(compose string->canonical-sexp
read-string))))
(mkdir-p (dirname %acl-file))
(with-atomic-file-output %acl-file
(lambda (port)
(write-acl (public-keys->acl (list public-key))
port)))))))
(define (write-acl acl port)
"Write ACL to PORT in canonical-sexp format."
(let ((sexp (sexp->canonical-sexp acl)))
(display (canonical-sexp->string sexp) port)))
(define (current-acl)
"Return the current ACL."
(ensure-acl)
(if (file-exists? %acl-file)
(call-with-input-file %acl-file
(compose canonical-sexp->sexp
string->canonical-sexp
read-string))
(define (acl->public-keys acl)
"Return the public keys (as canonical sexps) listed in ACL with the '(guix
import)' tag."
(match acl
(('acl
('entry subject-keys
('tag ('guix 'import)))
...)
(map sexp->canonical-sexp subject-keys))
(_
(error "invalid access-control list" acl))))
(define* (authorized-key? key #:optional (acl (current-acl)))
"Return #t if KEY (a canonical sexp) is an authorized public key for archive
imports according to ACL."
TODO : We could use a better data type for ACLs .
(let ((key (canonical-sexp->sexp key)))
(match acl
(('acl
('entry subject-keys
('tag ('guix 'import)))
...)
(not (not (member key subject-keys))))
(_
(error "invalid access-control list" acl)))))
(define (signature-sexp data secret-key public-key)
"Return a SPKI-style sexp for the signature of DATA with SECRET-KEY that
includes DATA, the actual signature value (with a 'sig-val' tag), and
PUBLIC-KEY (see </~cme/spki.txt> for examples.)"
(string->canonical-sexp
(format #f
"(signature ~a ~a ~a)"
(canonical-sexp->string data)
(canonical-sexp->string (sign data secret-key))
(canonical-sexp->string public-key))))
(define (signature-subject sig)
"Return the signer's public key for SIG."
(find-sexp-token sig 'public-key))
(define (signature-signed-data sig)
"Return the signed data from SIG, typically an sexp such as
(hash \"sha256\" #...#)."
(find-sexp-token sig 'data))
(define (valid-signature? sig)
"Return #t if SIG is valid."
(let* ((data (signature-signed-data sig))
(signature (find-sexp-token sig 'sig-val))
(public-key (signature-subject sig)))
(and data signature
(verify signature data public-key))))
(define* (%signature-status signature hash
#:optional (acl (current-acl)))
"Return a symbol denoting the status of SIGNATURE vs. HASH vs. ACL.
This procedure must only be used internally, because it would be easy to
forget some of the cases."
(let ((subject (signature-subject signature))
(data (signature-signed-data signature)))
(if (and data subject)
(if (authorized-key? subject acl)
(if (equal? (hash-data->bytevector data) hash)
(if (valid-signature? signature)
'valid-signature
'invalid-signature)
'hash-mismatch)
'unauthorized-key)
'corrupt-signature)))
(define-syntax signature-case
(syntax-rules (valid-signature invalid-signature
hash-mismatch unauthorized-key corrupt-signature
else)
"\
Match the cases of the verification of SIGNATURE against HASH and ACL:
- the 'valid-signature' case if SIGNATURE is indeed a signature of HASH with
- 'corrupt-signature' if SIGNATURE is not a valid signature sexp.
This macro guarantees at compile-time that all these cases are handled.
((_ (signature hash acl)
(valid-signature valid-exp ...)
(else else-exp ...))
(case (%signature-status signature hash acl)
((valid-signature) valid-exp ...)
(else else-exp ...)))
((_ (signature hash acl)
(valid-signature valid-exp ...)
(invalid-signature invalid-exp ...)
(hash-mismatch mismatch-exp ...)
(unauthorized-key unauthorized-exp ...)
(corrupt-signature corrupt-exp ...))
(case (%signature-status signature hash acl)
((valid-signature) valid-exp ...)
((invalid-signature) invalid-exp ...)
((hash-mismatch) mismatch-exp ...)
((unauthorized-key) unauthorized-exp ...)
((corrupt-signature) corrupt-exp ...)
(else (error "bogus signature status"))))))
|
a1dec7757c59cb54939fdd55700808161ac44f560ddf706e08cd04beda982ba4
|
juji-io/datalevin
|
sparselist.clj
|
(ns ^:no-doc datalevin.sparselist
"Sparse array list of integers"
(:refer-clojure :exclude [get set remove])
(:require
[taoensso.nippy :as nippy])
(:import
[java.io Writer DataInput DataOutput]
[java.nio ByteBuffer]
[datalevin.utl GrowingIntArray]
[me.lemire.integercompression IntCompressor]
[me.lemire.integercompression.differential IntegratedIntCompressor]
[org.roaringbitmap RoaringBitmap]))
(defprotocol ICompressor
(compress [this obj])
(uncompress [this obj]))
(defonce compressor
(let [^IntCompressor int-compressor (IntCompressor.)]
(reify
ICompressor
(compress [_ ar]
(.compress int-compressor ar))
(uncompress [_ ar]
(.uncompress int-compressor ar)))) )
(defonce sorted-compressor
(let [^IntegratedIntCompressor sorted-int-compressor
(IntegratedIntCompressor.)]
(reify
ICompressor
(compress [_ ar]
(.compress sorted-int-compressor ar))
(uncompress [_ ar]
(.uncompress sorted-int-compressor ar)))) )
(defn- get-ints*
[compressor ^ByteBuffer bf]
(let [csize (.getInt bf)
comp? (neg? csize)
size (if comp? (- csize) csize)
car (int-array size)]
(dotimes [i size] (aset car i (.getInt bf)))
(if comp?
(uncompress ^ICompressor compressor car)
car)))
(defn- put-ints*
[compressor ^ByteBuffer bf ^ints ar]
(let [osize (alength ar)
comp? (< 3 osize) ;; don't compress small array
^ints car (if comp?
(compress ^ICompressor compressor ar)
ar)
size (alength car)]
(.putInt bf (if comp? (- size) size))
(dotimes [i size] (.putInt bf (aget car i)))))
(defn get-ints [bf] (get-ints* compressor bf))
(defn put-ints [bf ar] (put-ints* compressor bf ar))
(defn get-sorted-ints [bf] (get-ints* sorted-compressor bf))
(defn put-sorted-ints [bf ar] (put-ints* sorted-compressor bf ar))
(defprotocol ISparseIntArrayList
(contains-index? [this index] "return true if containing index")
(get [this index] "get item by index")
(set [this index item] "set an item by index")
(remove [this index] "remove an item by index")
(size [this] "return the size")
(select [this nth] "return the nth item")
(serialize [this bf] "serialize to a bytebuffer")
(deserialize [this bf] "serialize from a bytebuffer"))
(deftype SparseIntArrayList [^RoaringBitmap indices
^GrowingIntArray items]
ISparseIntArrayList
(contains-index? [_ index]
(.contains indices (int index)))
(get [_ index]
(when (.contains indices (int index))
(.get items (dec (.rank indices index)))))
(set [this index item]
(let [index (int index)]
(if (.contains indices index)
(.set items (dec (.rank indices index)) item)
(do (.add indices index)
(.insert items (dec (.rank indices index)) item))))
this)
(remove [this index]
(.remove items (dec (.rank indices index)))
(.remove indices index)
this)
(size [_] (.getCardinality indices))
(select [_ nth]
(.get items nth))
(serialize [_ bf]
(put-ints bf (.toArray items))
(.serialize indices ^ByteBuffer bf))
(deserialize [_ bf]
(.addAll items (get-ints bf))
(.deserialize indices ^ByteBuffer bf))
Object
(equals [_ other]
(and (instance? SparseIntArrayList other)
(.equals indices (.-indices ^SparseIntArrayList other))
(.equals items (.-items ^SparseIntArrayList other)))))
(nippy/extend-freeze
RoaringBitmap :dtlv/bm
[^RoaringBitmap x ^DataOutput out]
(.serialize x out))
(nippy/extend-freeze
GrowingIntArray :dtlv/gia
[^GrowingIntArray x ^DataOutput out]
(let [ar (.toArray x)
osize (alength ar)
comp? (< 3 osize)
^ints car (if comp?
(compress ^ICompressor compressor ar)
ar)
size (alength car)]
(.writeInt out (if comp? (- size) size))
(dotimes [i size] (.writeInt out (aget car i)))))
(nippy/extend-freeze
SparseIntArrayList :dtlv/sial
[^SparseIntArrayList x ^DataOutput out]
(nippy/freeze-to-out! out (.-items x))
(nippy/freeze-to-out! out (.-indices x)))
(nippy/extend-thaw
:dtlv/bm [^DataInput in]
(doto (RoaringBitmap.) (.deserialize in)))
(nippy/extend-thaw
:dtlv/gia [^DataInput in]
(let [csize (.readInt in)
comp? (neg? csize)
size (if comp? (- csize) csize)
car (int-array size)
items (GrowingIntArray.)]
(dotimes [i size] (aset car i (.readInt in)))
(.addAll items
(if comp?
(uncompress ^ICompressor compressor car)
car))
items))
(nippy/extend-thaw
:dtlv/sial [^DataInput in]
(let [items (nippy/thaw-from-in! in)]
(->SparseIntArrayList (nippy/thaw-from-in! in) items)))
(defn sparse-arraylist
([]
(->SparseIntArrayList (RoaringBitmap.) (GrowingIntArray.)))
([m]
(let [ssl (sparse-arraylist)]
(doseq [[k v] m] (set ssl k v))
ssl))
([ks vs]
(let [ssl (sparse-arraylist)]
(dorun (map #(set ssl %1 %2) ks vs))
ssl)) )
(defmethod print-method SparseIntArrayList
[^SparseIntArrayList s ^Writer w]
(.write w (str "#datalevin/SparseList "))
(binding [*out* w]
(pr (for [i (.-indices s)] [i (get s i)]))))
| null |
https://raw.githubusercontent.com/juji-io/datalevin/8eceb2fa17933eb248edb07b717a70228c1987ba/src/datalevin/sparselist.clj
|
clojure
|
don't compress small array
|
(ns ^:no-doc datalevin.sparselist
"Sparse array list of integers"
(:refer-clojure :exclude [get set remove])
(:require
[taoensso.nippy :as nippy])
(:import
[java.io Writer DataInput DataOutput]
[java.nio ByteBuffer]
[datalevin.utl GrowingIntArray]
[me.lemire.integercompression IntCompressor]
[me.lemire.integercompression.differential IntegratedIntCompressor]
[org.roaringbitmap RoaringBitmap]))
(defprotocol ICompressor
(compress [this obj])
(uncompress [this obj]))
(defonce compressor
(let [^IntCompressor int-compressor (IntCompressor.)]
(reify
ICompressor
(compress [_ ar]
(.compress int-compressor ar))
(uncompress [_ ar]
(.uncompress int-compressor ar)))) )
(defonce sorted-compressor
(let [^IntegratedIntCompressor sorted-int-compressor
(IntegratedIntCompressor.)]
(reify
ICompressor
(compress [_ ar]
(.compress sorted-int-compressor ar))
(uncompress [_ ar]
(.uncompress sorted-int-compressor ar)))) )
(defn- get-ints*
[compressor ^ByteBuffer bf]
(let [csize (.getInt bf)
comp? (neg? csize)
size (if comp? (- csize) csize)
car (int-array size)]
(dotimes [i size] (aset car i (.getInt bf)))
(if comp?
(uncompress ^ICompressor compressor car)
car)))
(defn- put-ints*
[compressor ^ByteBuffer bf ^ints ar]
(let [osize (alength ar)
^ints car (if comp?
(compress ^ICompressor compressor ar)
ar)
size (alength car)]
(.putInt bf (if comp? (- size) size))
(dotimes [i size] (.putInt bf (aget car i)))))
(defn get-ints [bf] (get-ints* compressor bf))
(defn put-ints [bf ar] (put-ints* compressor bf ar))
(defn get-sorted-ints [bf] (get-ints* sorted-compressor bf))
(defn put-sorted-ints [bf ar] (put-ints* sorted-compressor bf ar))
(defprotocol ISparseIntArrayList
(contains-index? [this index] "return true if containing index")
(get [this index] "get item by index")
(set [this index item] "set an item by index")
(remove [this index] "remove an item by index")
(size [this] "return the size")
(select [this nth] "return the nth item")
(serialize [this bf] "serialize to a bytebuffer")
(deserialize [this bf] "serialize from a bytebuffer"))
(deftype SparseIntArrayList [^RoaringBitmap indices
^GrowingIntArray items]
ISparseIntArrayList
(contains-index? [_ index]
(.contains indices (int index)))
(get [_ index]
(when (.contains indices (int index))
(.get items (dec (.rank indices index)))))
(set [this index item]
(let [index (int index)]
(if (.contains indices index)
(.set items (dec (.rank indices index)) item)
(do (.add indices index)
(.insert items (dec (.rank indices index)) item))))
this)
(remove [this index]
(.remove items (dec (.rank indices index)))
(.remove indices index)
this)
(size [_] (.getCardinality indices))
(select [_ nth]
(.get items nth))
(serialize [_ bf]
(put-ints bf (.toArray items))
(.serialize indices ^ByteBuffer bf))
(deserialize [_ bf]
(.addAll items (get-ints bf))
(.deserialize indices ^ByteBuffer bf))
Object
(equals [_ other]
(and (instance? SparseIntArrayList other)
(.equals indices (.-indices ^SparseIntArrayList other))
(.equals items (.-items ^SparseIntArrayList other)))))
(nippy/extend-freeze
RoaringBitmap :dtlv/bm
[^RoaringBitmap x ^DataOutput out]
(.serialize x out))
(nippy/extend-freeze
GrowingIntArray :dtlv/gia
[^GrowingIntArray x ^DataOutput out]
(let [ar (.toArray x)
osize (alength ar)
comp? (< 3 osize)
^ints car (if comp?
(compress ^ICompressor compressor ar)
ar)
size (alength car)]
(.writeInt out (if comp? (- size) size))
(dotimes [i size] (.writeInt out (aget car i)))))
(nippy/extend-freeze
SparseIntArrayList :dtlv/sial
[^SparseIntArrayList x ^DataOutput out]
(nippy/freeze-to-out! out (.-items x))
(nippy/freeze-to-out! out (.-indices x)))
(nippy/extend-thaw
:dtlv/bm [^DataInput in]
(doto (RoaringBitmap.) (.deserialize in)))
(nippy/extend-thaw
:dtlv/gia [^DataInput in]
(let [csize (.readInt in)
comp? (neg? csize)
size (if comp? (- csize) csize)
car (int-array size)
items (GrowingIntArray.)]
(dotimes [i size] (aset car i (.readInt in)))
(.addAll items
(if comp?
(uncompress ^ICompressor compressor car)
car))
items))
(nippy/extend-thaw
:dtlv/sial [^DataInput in]
(let [items (nippy/thaw-from-in! in)]
(->SparseIntArrayList (nippy/thaw-from-in! in) items)))
(defn sparse-arraylist
([]
(->SparseIntArrayList (RoaringBitmap.) (GrowingIntArray.)))
([m]
(let [ssl (sparse-arraylist)]
(doseq [[k v] m] (set ssl k v))
ssl))
([ks vs]
(let [ssl (sparse-arraylist)]
(dorun (map #(set ssl %1 %2) ks vs))
ssl)) )
(defmethod print-method SparseIntArrayList
[^SparseIntArrayList s ^Writer w]
(.write w (str "#datalevin/SparseList "))
(binding [*out* w]
(pr (for [i (.-indices s)] [i (get s i)]))))
|
4e5c890b776af2488f4a7d9321a55fc9d97b8f2ba431b0c279a98110a4215cac
|
techascent/tech.datatype
|
mmul_test.clj
|
(ns tech.v2.tensor.mmul-test
(:require [tech.v2.datatype :as dtype]
[tech.v2.tensor :as tens]
[tech.v2.tensor.select-test :refer [tensor-default-context]]
[clojure.test :refer :all]))
(defn do-basic-mm
[container-type datatype]
(let [n-elems (* 2 5)
test-mat (tens/->tensor (partition 5 (range n-elems))
:container-type container-type
:datatype datatype)]
(is (= [[30 80] [80 255]]
(-> (tens/matrix-multiply test-mat (tens/transpose test-mat [1 0]))
(tens/->jvm :datatype :int32)))
(with-out-str (println container-type datatype)))
(is (= [[25 30 35 40 45]
[30 37 44 51 58]
[35 44 53 62 71]
[40 51 62 73 84]
[45 58 71 84 97]]
(-> (tens/matrix-multiply (tens/transpose test-mat [1 0]) test-mat)
(tens/->jvm :datatype :int32)))
(with-out-str (println container-type datatype)))))
(deftest basic-mm
(do-basic-mm :list :float64)
(do-basic-mm :list :int32)
;;sparse is disabled for now
(comment
(do-basic-mm :sparse :int32)
(do-basic-mm :sparse :int16)))
| null |
https://raw.githubusercontent.com/techascent/tech.datatype/8cc83d771d9621d580fd5d4d0625005bd7ab0e0c/test/tech/v2/tensor/mmul_test.clj
|
clojure
|
sparse is disabled for now
|
(ns tech.v2.tensor.mmul-test
(:require [tech.v2.datatype :as dtype]
[tech.v2.tensor :as tens]
[tech.v2.tensor.select-test :refer [tensor-default-context]]
[clojure.test :refer :all]))
(defn do-basic-mm
[container-type datatype]
(let [n-elems (* 2 5)
test-mat (tens/->tensor (partition 5 (range n-elems))
:container-type container-type
:datatype datatype)]
(is (= [[30 80] [80 255]]
(-> (tens/matrix-multiply test-mat (tens/transpose test-mat [1 0]))
(tens/->jvm :datatype :int32)))
(with-out-str (println container-type datatype)))
(is (= [[25 30 35 40 45]
[30 37 44 51 58]
[35 44 53 62 71]
[40 51 62 73 84]
[45 58 71 84 97]]
(-> (tens/matrix-multiply (tens/transpose test-mat [1 0]) test-mat)
(tens/->jvm :datatype :int32)))
(with-out-str (println container-type datatype)))))
(deftest basic-mm
(do-basic-mm :list :float64)
(do-basic-mm :list :int32)
(comment
(do-basic-mm :sparse :int32)
(do-basic-mm :sparse :int16)))
|
7137e21176e0506040106a0e0afd04852ea056870044f7fd44dc1639a0135af0
|
tlaplus/tlapm
|
ext_induct.mli
|
Copyright 2006 INRIA
val is_constr : string -> bool;;
| null |
https://raw.githubusercontent.com/tlaplus/tlapm/b82e2fd049c5bc1b14508ae16890666c6928975f/zenon/ext_induct.mli
|
ocaml
|
Copyright 2006 INRIA
val is_constr : string -> bool;;
|
|
23581f5ce1f5d1deb881569dc4ad6099a5a1f111591a4d8e9a749516516c1315
|
input-output-hk/plutus-apps
|
Checkpoint.hs
|
# LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE GADTs #
{-# LANGUAGE KindSignatures #-}
# LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeOperators #-}
module Plutus.Contract.Checkpoint(
-- * Checkpoints
-- $checkpoints
Checkpoint(..)
, CheckpointError(..)
, AsCheckpointError(..)
, CheckpointStore(..)
, CheckpointStoreItem(..)
, CheckpointKey
, CheckpointLogMsg(..)
, jsonCheckpoint
, jsonCheckpointLoop
, handleCheckpoint
, completedIntervals
, maxKey
) where
import Control.Lens
import Control.Monad.Freer
import Control.Monad.Freer.Error (Error, throwError)
import Control.Monad.Freer.Extras.Log (LogMsg, logDebug, logError)
import Control.Monad.Freer.State (State, get, gets, modify, put)
import Data.Aeson (FromJSON, FromJSONKey, ToJSON, ToJSONKey, Value)
import Data.Aeson.Types qualified as JSON
import Data.IntervalMap.Interval (Interval (ClosedInterval))
import Data.IntervalSet qualified as IS
import Data.Map (Map)
import Data.Map qualified as Map
import Data.Text (Text)
import Data.Text qualified as Text
import GHC.Generics (Generic)
import Prettyprinter (Pretty (..), colon, vsep, (<+>))
-- $checkpoints
-- This module contains a checkpoints mechanism that can be used to store
intermediate results of ' Control . . Freer . Eff ' programs as JSON values
-- inside a 'CheckpointStore'. It works similar to the short-circuiting behavior
of ' Control . . Freer . Error . Error ' : Before we execute an action
-- @Eff effs a@ whose result should be checkpointed, we check if the there is
-- already a value of @a@ for this checkpoint it in the store. If there is, we
-- return it /instead/ of running the action. If there isn't, we run the action
-- @a@ and then store the result.
--
-- * To create a checkpoint use 'jsonCheckpoint'.
-- * To handle the checkpoint effect use 'handleCheckpoint'.
newtype CheckpointKey = CheckpointKey Integer
deriving stock (Eq, Ord, Show, Generic)
deriving newtype (FromJSON, ToJSON, ToJSONKey, FromJSONKey, Num, Enum, Pretty)
data CheckpointError = JSONDecodeError Text
deriving stock (Eq, Ord, Show, Generic)
deriving anyclass (FromJSON, ToJSON)
instance Pretty CheckpointError where
pretty = \case
JSONDecodeError t -> "JSON decoding error:" <+> pretty t
makeClassyPrisms ''CheckpointError
newtype CheckpointStore = CheckpointStore { unCheckpointStore :: Map CheckpointKey (CheckpointStoreItem Value) }
deriving stock (Eq, Show, Generic)
deriving anyclass (ToJSON, FromJSON)
deriving newtype (Semigroup, Monoid)
instance Pretty CheckpointStore where
pretty (CheckpointStore mp) =
let p k v = pretty k <> colon <+> (pretty . take 100 . show) v in
vsep (uncurry p <$> Map.toList mp)
_CheckpointStore :: Iso' CheckpointStore (Map CheckpointKey (CheckpointStoreItem Value))
_CheckpointStore = iso unCheckpointStore CheckpointStore
-- | Intervals of checkpoint keys that are completely covered by the
-- checkpoint store.
completedIntervals :: CheckpointStore -> IS.IntervalSet (Interval CheckpointKey)
completedIntervals = IS.fromList . fmap (uncurry f) . Map.toList . unCheckpointStore where
f (from_ :: CheckpointKey) CheckpointStoreItem{csNewKey} = ClosedInterval from_ csNewKey
-- | The maximum key that is present in the store
maxKey :: CheckpointStore -> Maybe CheckpointKey
maxKey = fmap fst . Map.lookupMax . unCheckpointStore
data CheckpointStoreItem a =
CheckpointStoreItem
{ csValue :: a
, csNewKey :: CheckpointKey
}
deriving stock (Eq, Ord, Show, Generic, Functor, Foldable, Traversable)
deriving anyclass (ToJSON, FromJSON)
data CheckpointLogMsg =
LogFoundValueRestoringKey CheckpointKey
| LogDecodingErrorAtKey CheckpointKey
| LogNoValueForKey CheckpointKey
| LogDoCheckpoint
| LogAllocateKey
| LogRetrieve CheckpointKey
| LogStore CheckpointKey CheckpointKey
| LogKeyUpdate CheckpointKey CheckpointKey
deriving (Eq, Ord, Show, Generic)
deriving anyclass (ToJSON, FromJSON)
instance Pretty CheckpointLogMsg where
pretty = \case
LogFoundValueRestoringKey k -> "Found a value, restoring previous key" <+> pretty k
LogDecodingErrorAtKey k -> "Decoding error at key" <+> pretty k
LogNoValueForKey k -> "No value for key" <+> pretty k <> ". The action will be once."
LogDoCheckpoint -> "doCheckpoint"
LogAllocateKey -> "allocateKey"
LogRetrieve k -> "retrieve" <+> pretty k
LogStore k1 k2 -> "Store; key1:" <+> pretty k1 <> "; key2:" <+> pretty k2
LogKeyUpdate k1 k2 -> "Key update; key then:" <+> pretty k1 <> "; key now:" <+> pretty k2
| Insert a new value into the checkpoint store . The first ' CheckpointKey ' is
the checkpoint key * before * running the checkpointed action , the second
' Checkpoint ' key is the value * after * running it . When we restore the
checkpoint from the state ( in ' restore ' ) we set the ' CheckpointKey ' state
to the second argument to prevent chaos .
the checkpoint key *before* running the checkpointed action, the second
'Checkpoint' key is the value *after* running it. When we restore the
checkpoint from the state (in 'restore') we set the 'CheckpointKey' state
to the second argument to prevent chaos.
-}
insert ::
( ToJSON a
, Member (State CheckpointStore) effs
)
=> CheckpointKey
-> CheckpointKey
-> a
-> Eff effs ()
insert k k' v =
let vl = CheckpointStoreItem{csValue = JSON.toJSON v, csNewKey = k'}
in modify (over _CheckpointStore (Map.insert k vl))
| @restore k@ checks for an entry for @k@ in the checkpoint store ,
and parses the result if there is such an entry . It returns
* Nothing@ if no entry was found
* @Left err@ if an entry was found but failed to parse with the
' FromJSON ' instance
* ( Just a)@ if an entry was found and parsed succesfully .
and parses the result if there is such an entry. It returns
* @Right Nothing@ if no entry was found
* @Left err@ if an entry was found but failed to parse with the
'FromJSON' instance
* @Right (Just a)@ if an entry was found and parsed succesfully.
-}
restore ::
forall a effs.
( FromJSON a
, Member (State CheckpointStore) effs
, Member (State CheckpointKey) effs
, Member (LogMsg CheckpointLogMsg) effs
)
=> CheckpointKey
-> Eff effs (Either CheckpointError (Maybe a))
restore k = do
value <- gets (view $ _CheckpointStore . at k)
let (result :: Maybe (Either String (CheckpointStoreItem a))) = fmap (traverse (JSON.parseEither JSON.parseJSON)) value
case result of
Nothing -> do
logDebug (LogNoValueForKey k)
pure $ Right Nothing
Just (Left err) -> do
logError (LogDecodingErrorAtKey k)
pure $ Left (JSONDecodeError $ Text.pack err)
Just (Right CheckpointStoreItem{csValue,csNewKey}) -> do
logDebug $ LogFoundValueRestoringKey csNewKey
let nk = succ csNewKey
put nk
pure (Right (Just csValue))
data Checkpoint r where
DoCheckpoint :: Checkpoint ()
AllocateKey :: Checkpoint CheckpointKey
Store :: (ToJSON a) => CheckpointKey -> CheckpointKey -> a -> Checkpoint ()
Retrieve :: (FromJSON a) => CheckpointKey -> Checkpoint (Either CheckpointError (Maybe a))
doCheckpoint :: forall effs. Member Checkpoint effs => Eff effs ()
doCheckpoint = send DoCheckpoint
allocateKey :: forall effs. Member Checkpoint effs => Eff effs CheckpointKey
allocateKey = send AllocateKey
store :: forall a effs. (Member Checkpoint effs, ToJSON a) => CheckpointKey -> CheckpointKey -> a -> Eff effs ()
store k1 k2 a = send @Checkpoint (Store k1 k2 a)
retrieve :: forall a effs. (Member Checkpoint effs, FromJSON a) => CheckpointKey -> Eff effs (Either CheckpointError (Maybe a))
retrieve k = send @Checkpoint (Retrieve k)
-- | Handle the 'Checkpoint' effect in terms of 'CheckpointStore' and
' CheckpointKey ' states .
handleCheckpoint ::
forall effs.
( Member (State CheckpointStore) effs
, Member (State CheckpointKey) effs
, Member (LogMsg CheckpointLogMsg) effs
)
=> Eff (Checkpoint ': effs)
~> Eff effs
handleCheckpoint = interpret $ \case
DoCheckpoint -> do
logDebug LogDoCheckpoint
modify @CheckpointKey succ
AllocateKey -> do
logDebug LogAllocateKey
get @CheckpointKey
Store k k' a -> do
logDebug $ LogStore k k'
insert k k' a
Retrieve k -> do
logDebug $ LogRetrieve k
result <- restore @_ @effs k
k' <- get @CheckpointKey
logDebug $ LogKeyUpdate k k'
pure result
| Create a checkpoint for an action .
@handleCheckpoint ( jsonCheckpoint action)@ will
* Obtain a ' CheckpointKey ' that identifies the position of the current
checkpoint in the program
* Run @action@ , convert its result to JSON and store it in the checkpoint
store if there is no value at the key
* Retrieve the result as a JSON value from the store , parse it , and return
it * instead * of running @action@ if there is a value at the key .
@handleCheckpoint (jsonCheckpoint action)@ will
* Obtain a 'CheckpointKey' that identifies the position of the current
checkpoint in the program
* Run @action@, convert its result to JSON and store it in the checkpoint
store if there is no value at the key
* Retrieve the result as a JSON value from the store, parse it, and return
it *instead* of running @action@ if there is a value at the key.
-}
jsonCheckpoint ::
forall err a effs.
( Member Checkpoint effs
, Member (Error err) effs
, ToJSON a
, FromJSON a
, AsCheckpointError err
)
=> Eff effs a -- ^ The @action@ that is checkpointed
-> Eff effs a
jsonCheckpoint action = jsonCheckpointLoop @err @() @a (\() -> Left <$> action) ()
{-
Create a checkpoint for an action that is run repeatedly.
-}
jsonCheckpointLoop ::
forall err a b effs.
( Member Checkpoint effs
, Member (Error err) effs
, ToJSON a
, FromJSON a
, ToJSON b
, FromJSON b
, AsCheckpointError err
)
=> (a -> Eff effs (Either b a)) -- ^ The action that is repeated until it returns a 'Left'. Only the accumulated result of the action will be stored.
-> a -- ^ Initial value
-> Eff effs b
jsonCheckpointLoop action initial = do
doCheckpoint
k <- allocateKey
current <- do
vl <- retrieve @_ k
case vl of
Left err -> do
throwError @err (review _CheckpointError err)
Right (Just a) -> do
pure a
Right Nothing -> do
pure (Right initial)
let go (Left b) = pure b
go (Right a) = do
actionResult <- action a
k' <- allocateKey
store @_ k k' actionResult
doCheckpoint
go actionResult
go current
| null |
https://raw.githubusercontent.com/input-output-hk/plutus-apps/d637b1916522e4ec20b719487a8a2e066937aceb/plutus-contract/src/Plutus/Contract/Checkpoint.hs
|
haskell
|
# LANGUAGE DataKinds #
# LANGUAGE DeriveAnyClass #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE KindSignatures #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
# LANGUAGE TypeOperators #
* Checkpoints
$checkpoints
$checkpoints
This module contains a checkpoints mechanism that can be used to store
inside a 'CheckpointStore'. It works similar to the short-circuiting behavior
@Eff effs a@ whose result should be checkpointed, we check if the there is
already a value of @a@ for this checkpoint it in the store. If there is, we
return it /instead/ of running the action. If there isn't, we run the action
@a@ and then store the result.
* To create a checkpoint use 'jsonCheckpoint'.
* To handle the checkpoint effect use 'handleCheckpoint'.
| Intervals of checkpoint keys that are completely covered by the
checkpoint store.
| The maximum key that is present in the store
| Handle the 'Checkpoint' effect in terms of 'CheckpointStore' and
^ The @action@ that is checkpointed
Create a checkpoint for an action that is run repeatedly.
^ The action that is repeated until it returns a 'Left'. Only the accumulated result of the action will be stored.
^ Initial value
|
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DeriveGeneric #
# LANGUAGE GADTs #
# LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
module Plutus.Contract.Checkpoint(
Checkpoint(..)
, CheckpointError(..)
, AsCheckpointError(..)
, CheckpointStore(..)
, CheckpointStoreItem(..)
, CheckpointKey
, CheckpointLogMsg(..)
, jsonCheckpoint
, jsonCheckpointLoop
, handleCheckpoint
, completedIntervals
, maxKey
) where
import Control.Lens
import Control.Monad.Freer
import Control.Monad.Freer.Error (Error, throwError)
import Control.Monad.Freer.Extras.Log (LogMsg, logDebug, logError)
import Control.Monad.Freer.State (State, get, gets, modify, put)
import Data.Aeson (FromJSON, FromJSONKey, ToJSON, ToJSONKey, Value)
import Data.Aeson.Types qualified as JSON
import Data.IntervalMap.Interval (Interval (ClosedInterval))
import Data.IntervalSet qualified as IS
import Data.Map (Map)
import Data.Map qualified as Map
import Data.Text (Text)
import Data.Text qualified as Text
import GHC.Generics (Generic)
import Prettyprinter (Pretty (..), colon, vsep, (<+>))
intermediate results of ' Control . . Freer . Eff ' programs as JSON values
of ' Control . . Freer . Error . Error ' : Before we execute an action
newtype CheckpointKey = CheckpointKey Integer
deriving stock (Eq, Ord, Show, Generic)
deriving newtype (FromJSON, ToJSON, ToJSONKey, FromJSONKey, Num, Enum, Pretty)
data CheckpointError = JSONDecodeError Text
deriving stock (Eq, Ord, Show, Generic)
deriving anyclass (FromJSON, ToJSON)
instance Pretty CheckpointError where
pretty = \case
JSONDecodeError t -> "JSON decoding error:" <+> pretty t
makeClassyPrisms ''CheckpointError
newtype CheckpointStore = CheckpointStore { unCheckpointStore :: Map CheckpointKey (CheckpointStoreItem Value) }
deriving stock (Eq, Show, Generic)
deriving anyclass (ToJSON, FromJSON)
deriving newtype (Semigroup, Monoid)
instance Pretty CheckpointStore where
pretty (CheckpointStore mp) =
let p k v = pretty k <> colon <+> (pretty . take 100 . show) v in
vsep (uncurry p <$> Map.toList mp)
_CheckpointStore :: Iso' CheckpointStore (Map CheckpointKey (CheckpointStoreItem Value))
_CheckpointStore = iso unCheckpointStore CheckpointStore
completedIntervals :: CheckpointStore -> IS.IntervalSet (Interval CheckpointKey)
completedIntervals = IS.fromList . fmap (uncurry f) . Map.toList . unCheckpointStore where
f (from_ :: CheckpointKey) CheckpointStoreItem{csNewKey} = ClosedInterval from_ csNewKey
maxKey :: CheckpointStore -> Maybe CheckpointKey
maxKey = fmap fst . Map.lookupMax . unCheckpointStore
data CheckpointStoreItem a =
CheckpointStoreItem
{ csValue :: a
, csNewKey :: CheckpointKey
}
deriving stock (Eq, Ord, Show, Generic, Functor, Foldable, Traversable)
deriving anyclass (ToJSON, FromJSON)
data CheckpointLogMsg =
LogFoundValueRestoringKey CheckpointKey
| LogDecodingErrorAtKey CheckpointKey
| LogNoValueForKey CheckpointKey
| LogDoCheckpoint
| LogAllocateKey
| LogRetrieve CheckpointKey
| LogStore CheckpointKey CheckpointKey
| LogKeyUpdate CheckpointKey CheckpointKey
deriving (Eq, Ord, Show, Generic)
deriving anyclass (ToJSON, FromJSON)
instance Pretty CheckpointLogMsg where
pretty = \case
LogFoundValueRestoringKey k -> "Found a value, restoring previous key" <+> pretty k
LogDecodingErrorAtKey k -> "Decoding error at key" <+> pretty k
LogNoValueForKey k -> "No value for key" <+> pretty k <> ". The action will be once."
LogDoCheckpoint -> "doCheckpoint"
LogAllocateKey -> "allocateKey"
LogRetrieve k -> "retrieve" <+> pretty k
LogStore k1 k2 -> "Store; key1:" <+> pretty k1 <> "; key2:" <+> pretty k2
LogKeyUpdate k1 k2 -> "Key update; key then:" <+> pretty k1 <> "; key now:" <+> pretty k2
| Insert a new value into the checkpoint store . The first ' CheckpointKey ' is
the checkpoint key * before * running the checkpointed action , the second
' Checkpoint ' key is the value * after * running it . When we restore the
checkpoint from the state ( in ' restore ' ) we set the ' CheckpointKey ' state
to the second argument to prevent chaos .
the checkpoint key *before* running the checkpointed action, the second
'Checkpoint' key is the value *after* running it. When we restore the
checkpoint from the state (in 'restore') we set the 'CheckpointKey' state
to the second argument to prevent chaos.
-}
insert ::
( ToJSON a
, Member (State CheckpointStore) effs
)
=> CheckpointKey
-> CheckpointKey
-> a
-> Eff effs ()
insert k k' v =
let vl = CheckpointStoreItem{csValue = JSON.toJSON v, csNewKey = k'}
in modify (over _CheckpointStore (Map.insert k vl))
| @restore k@ checks for an entry for @k@ in the checkpoint store ,
and parses the result if there is such an entry . It returns
* Nothing@ if no entry was found
* @Left err@ if an entry was found but failed to parse with the
' FromJSON ' instance
* ( Just a)@ if an entry was found and parsed succesfully .
and parses the result if there is such an entry. It returns
* @Right Nothing@ if no entry was found
* @Left err@ if an entry was found but failed to parse with the
'FromJSON' instance
* @Right (Just a)@ if an entry was found and parsed succesfully.
-}
restore ::
forall a effs.
( FromJSON a
, Member (State CheckpointStore) effs
, Member (State CheckpointKey) effs
, Member (LogMsg CheckpointLogMsg) effs
)
=> CheckpointKey
-> Eff effs (Either CheckpointError (Maybe a))
restore k = do
value <- gets (view $ _CheckpointStore . at k)
let (result :: Maybe (Either String (CheckpointStoreItem a))) = fmap (traverse (JSON.parseEither JSON.parseJSON)) value
case result of
Nothing -> do
logDebug (LogNoValueForKey k)
pure $ Right Nothing
Just (Left err) -> do
logError (LogDecodingErrorAtKey k)
pure $ Left (JSONDecodeError $ Text.pack err)
Just (Right CheckpointStoreItem{csValue,csNewKey}) -> do
logDebug $ LogFoundValueRestoringKey csNewKey
let nk = succ csNewKey
put nk
pure (Right (Just csValue))
data Checkpoint r where
DoCheckpoint :: Checkpoint ()
AllocateKey :: Checkpoint CheckpointKey
Store :: (ToJSON a) => CheckpointKey -> CheckpointKey -> a -> Checkpoint ()
Retrieve :: (FromJSON a) => CheckpointKey -> Checkpoint (Either CheckpointError (Maybe a))
doCheckpoint :: forall effs. Member Checkpoint effs => Eff effs ()
doCheckpoint = send DoCheckpoint
allocateKey :: forall effs. Member Checkpoint effs => Eff effs CheckpointKey
allocateKey = send AllocateKey
store :: forall a effs. (Member Checkpoint effs, ToJSON a) => CheckpointKey -> CheckpointKey -> a -> Eff effs ()
store k1 k2 a = send @Checkpoint (Store k1 k2 a)
retrieve :: forall a effs. (Member Checkpoint effs, FromJSON a) => CheckpointKey -> Eff effs (Either CheckpointError (Maybe a))
retrieve k = send @Checkpoint (Retrieve k)
' CheckpointKey ' states .
handleCheckpoint ::
forall effs.
( Member (State CheckpointStore) effs
, Member (State CheckpointKey) effs
, Member (LogMsg CheckpointLogMsg) effs
)
=> Eff (Checkpoint ': effs)
~> Eff effs
handleCheckpoint = interpret $ \case
DoCheckpoint -> do
logDebug LogDoCheckpoint
modify @CheckpointKey succ
AllocateKey -> do
logDebug LogAllocateKey
get @CheckpointKey
Store k k' a -> do
logDebug $ LogStore k k'
insert k k' a
Retrieve k -> do
logDebug $ LogRetrieve k
result <- restore @_ @effs k
k' <- get @CheckpointKey
logDebug $ LogKeyUpdate k k'
pure result
| Create a checkpoint for an action .
@handleCheckpoint ( jsonCheckpoint action)@ will
* Obtain a ' CheckpointKey ' that identifies the position of the current
checkpoint in the program
* Run @action@ , convert its result to JSON and store it in the checkpoint
store if there is no value at the key
* Retrieve the result as a JSON value from the store , parse it , and return
it * instead * of running @action@ if there is a value at the key .
@handleCheckpoint (jsonCheckpoint action)@ will
* Obtain a 'CheckpointKey' that identifies the position of the current
checkpoint in the program
* Run @action@, convert its result to JSON and store it in the checkpoint
store if there is no value at the key
* Retrieve the result as a JSON value from the store, parse it, and return
it *instead* of running @action@ if there is a value at the key.
-}
jsonCheckpoint ::
forall err a effs.
( Member Checkpoint effs
, Member (Error err) effs
, ToJSON a
, FromJSON a
, AsCheckpointError err
)
-> Eff effs a
jsonCheckpoint action = jsonCheckpointLoop @err @() @a (\() -> Left <$> action) ()
jsonCheckpointLoop ::
forall err a b effs.
( Member Checkpoint effs
, Member (Error err) effs
, ToJSON a
, FromJSON a
, ToJSON b
, FromJSON b
, AsCheckpointError err
)
-> Eff effs b
jsonCheckpointLoop action initial = do
doCheckpoint
k <- allocateKey
current <- do
vl <- retrieve @_ k
case vl of
Left err -> do
throwError @err (review _CheckpointError err)
Right (Just a) -> do
pure a
Right Nothing -> do
pure (Right initial)
let go (Left b) = pure b
go (Right a) = do
actionResult <- action a
k' <- allocateKey
store @_ k k' actionResult
doCheckpoint
go actionResult
go current
|
aa8d80561c5145c7c1c2fd85c66b2b133c1d5699fc4ec9a4060ac7df038e1885
|
M4GNV5/Geschwindigkeitsficken
|
CopyLoops.hs
|
module Brainfuck.Optimizations.CopyLoops (optimizeLoops) where
import Data.Ratio
import Data.Maybe
import Data.Foldable
import qualified Data.Map.Lazy as M
import Brainfuck
isBasicOp (Add _ (Const _)) = True
isBasicOp (Shift _) = True
isBasicOp (Comment _) = True
isBasicOp _ = False
TODO optimize ifs and infinite loops
TODO can we optimize when condVal < 0 ?
the simple copy loop is
[ ->++>++++ < < ]
or
while p[0 ] ! = 0 :
p[0 ] -= 1
p[1 ] + = 2
p[2 ] + = 4
we can simplify this to
p[1 ] + = p[0 ] * 2
p[2 ] + = p[0 ] * 4
p[0 ] = 0
the general form is
p[1 ] + = p[0 ] * x_1
...
p[n ] + = p[0 ] * ] = 0
which only works when p[0 ] gets decremented by 1
when p[0 ] is changed other than -1 we need the special AdditionsUntilZero statement
it adds x_0 to p[0 ] until it reaches zero and returns the count of additions ( note that x_0 might be < 0 )
p[0 ] = AdditionsUntilZero(p[0 ] , x_0 )
p[1 ] + = p[0 ] * x_1
...
p[n ] + = p[0 ] * ] = 0
the simple copy loop is
[->++>++++<<]
or
while p[0] != 0:
p[0] -= 1
p[1] += 2
p[2] += 4
we can simplify this to
p[1] += p[0] * 2
p[2] += p[0] * 4
p[0] = 0
the general form is
p[1] += p[0] * x_1
...
p[n] += p[0] * x_n
p[0] = 0
which only works when p[0] gets decremented by 1
when p[0] is changed other than -1 we need the special AdditionsUntilZero statement
it adds x_0 to p[0] until it reaches zero and returns the count of additions (note that x_0 might be <0)
p[0] = AdditionsUntilZero(p[0], x_0)
p[1] += p[0] * x_1
...
p[n] += p[0] * x_n
p[0] = 0
-}
analyzeLoop (shift, condOp, mathOps) (Add off (Const val))
| target == 0 = (shift, condOp + val, mathOps)
| isJust prevOp = (shift, condOp, updatedMap)
| otherwise = (shift, condOp, M.insert target val mathOps)
where
target = shift + off
prevOp = M.lookup target mathOps
updatedVal = val + fromJust prevOp
updatedMap = M.insert target updatedVal mathOps
analyzeLoop (shift, condOp, mathOps) (Shift x) = (shift + x, condOp, mathOps)
analyzeLoop state (Comment _) = state
optimizeLoop loop@(Loop off children) = if hasNonBasicOps || totalShift /= 0 || condVal == 0
then [Loop off children']
else if condVal == -1
then comments ++ optimizedChildren ++ [(Set off (Const 0))]
else comments ++ (AddUntilZero off condVal : optimizedChildren) ++ [Set off (Const 0)]
where
children' = optimizeLoops children
comments = filter isComment children
hasNonBasicOps = any (not . isBasicOp) children'
(totalShift, condVal, mathOps) = foldl analyzeLoop (0, 0, M.empty) children
optimizedChildren = map genMathOp $ M.toList mathOps
condVal' = if condVal == -1
then negate condVal
else 1
genMathOp (curr, val) = Add curr (Var off (val % condVal'))
optimizeLoops statements = concat $ map optimizeIfLoop statements
where
optimizeIfLoop x = if isLoop x
then optimizeLoop x
else [x]
| null |
https://raw.githubusercontent.com/M4GNV5/Geschwindigkeitsficken/1567ea4213f72212b43f97629809f255b6b5f8a3/src/Brainfuck/Optimizations/CopyLoops.hs
|
haskell
|
module Brainfuck.Optimizations.CopyLoops (optimizeLoops) where
import Data.Ratio
import Data.Maybe
import Data.Foldable
import qualified Data.Map.Lazy as M
import Brainfuck
isBasicOp (Add _ (Const _)) = True
isBasicOp (Shift _) = True
isBasicOp (Comment _) = True
isBasicOp _ = False
TODO optimize ifs and infinite loops
TODO can we optimize when condVal < 0 ?
the simple copy loop is
[ ->++>++++ < < ]
or
while p[0 ] ! = 0 :
p[0 ] -= 1
p[1 ] + = 2
p[2 ] + = 4
we can simplify this to
p[1 ] + = p[0 ] * 2
p[2 ] + = p[0 ] * 4
p[0 ] = 0
the general form is
p[1 ] + = p[0 ] * x_1
...
p[n ] + = p[0 ] * ] = 0
which only works when p[0 ] gets decremented by 1
when p[0 ] is changed other than -1 we need the special AdditionsUntilZero statement
it adds x_0 to p[0 ] until it reaches zero and returns the count of additions ( note that x_0 might be < 0 )
p[0 ] = AdditionsUntilZero(p[0 ] , x_0 )
p[1 ] + = p[0 ] * x_1
...
p[n ] + = p[0 ] * ] = 0
the simple copy loop is
[->++>++++<<]
or
while p[0] != 0:
p[0] -= 1
p[1] += 2
p[2] += 4
we can simplify this to
p[1] += p[0] * 2
p[2] += p[0] * 4
p[0] = 0
the general form is
p[1] += p[0] * x_1
...
p[n] += p[0] * x_n
p[0] = 0
which only works when p[0] gets decremented by 1
when p[0] is changed other than -1 we need the special AdditionsUntilZero statement
it adds x_0 to p[0] until it reaches zero and returns the count of additions (note that x_0 might be <0)
p[0] = AdditionsUntilZero(p[0], x_0)
p[1] += p[0] * x_1
...
p[n] += p[0] * x_n
p[0] = 0
-}
analyzeLoop (shift, condOp, mathOps) (Add off (Const val))
| target == 0 = (shift, condOp + val, mathOps)
| isJust prevOp = (shift, condOp, updatedMap)
| otherwise = (shift, condOp, M.insert target val mathOps)
where
target = shift + off
prevOp = M.lookup target mathOps
updatedVal = val + fromJust prevOp
updatedMap = M.insert target updatedVal mathOps
analyzeLoop (shift, condOp, mathOps) (Shift x) = (shift + x, condOp, mathOps)
analyzeLoop state (Comment _) = state
optimizeLoop loop@(Loop off children) = if hasNonBasicOps || totalShift /= 0 || condVal == 0
then [Loop off children']
else if condVal == -1
then comments ++ optimizedChildren ++ [(Set off (Const 0))]
else comments ++ (AddUntilZero off condVal : optimizedChildren) ++ [Set off (Const 0)]
where
children' = optimizeLoops children
comments = filter isComment children
hasNonBasicOps = any (not . isBasicOp) children'
(totalShift, condVal, mathOps) = foldl analyzeLoop (0, 0, M.empty) children
optimizedChildren = map genMathOp $ M.toList mathOps
condVal' = if condVal == -1
then negate condVal
else 1
genMathOp (curr, val) = Add curr (Var off (val % condVal'))
optimizeLoops statements = concat $ map optimizeIfLoop statements
where
optimizeIfLoop x = if isLoop x
then optimizeLoop x
else [x]
|
|
f30af01776ce92454566d2de0b1e5b23850997fd0efbc35b3f26baf3dc483f32
|
thangngoc89/denu
|
main.ml
|
let () = Depend_on_main.run ()
| null |
https://raw.githubusercontent.com/thangngoc89/denu/aadd9eed431181cd3da3da14063b07bacfd0377e/play/main.ml
|
ocaml
|
let () = Depend_on_main.run ()
|
|
023f772e3593b36ca15139f9b28b9f99b751f959186b2c925197af23ba20a8e1
|
gndl/graffophone
|
voice.ml
|
* Copyright ( C ) 2015 Ga �
*
* All rights reserved . This file is distributed under the terms of the
* GNU General Public License version 3.0 .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* Copyright (C) 2015 Ga�tan Dubreil
*
* All rights reserved.This file is distributed under the terms of the
* GNU General Public License version 3.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
exception End
exception Ok
let defOutputTag = "O"
type port_t = int
type 'a t = {
mutable tick : int;
mutable len : int;
mutable cor : Cornet.t;
mutable tkr : 'a;
port : port_t;
vTag : string
}
let init l f = Cornet.init l ~f
let get voice i = Cornet.get voice.cor i
let set voice i v = Cornet.set voice.cor i v
let fill voice ofs len v = Cornet.fill voice.cor ofs len v
let add voice i v = Cornet.set voice.cor i (Cornet.get voice.cor i +. v)
let sub voice i v = Cornet.set voice.cor i (Cornet.get voice.cor i -. v)
let mul voice i v = Cornet.set voice.cor i (Cornet.get voice.cor i *. v)
let div voice i v = Cornet.set voice.cor i (Cornet.get voice.cor i /. v)
let dim voice = Cornet.dim voice.cor
let getTag voice = voice.vTag
let getIdentity voice =
let tkr_id = if String.length voice.tkr#getName > 0 then voice.tkr#getName
else voice.tkr#getKind in
tkr_id ^ "." ^ voice.vTag
let getPort voice = voice.port
let getTalker voice = voice.tkr
let getTick voice = voice.tick
let getLength voice = voice.len
let getCornet voice = voice.cor
let setTalker voice v = voice.tkr <- v
let setTick voice v = voice.tick <- v
let setLength voice v = voice.len <- v
let setCornet voice v = voice.cor <- v
let checkLength voice len =
if Cornet.dim voice.cor < len then voice.cor <- Cornet.make len
let isFrom tkrId port voice = voice.port = port && voice.tkr#getId = tkrId
| null |
https://raw.githubusercontent.com/gndl/graffophone/71a12fcf8e799bb8ebfc37141b300ecbc9475c43/plugin/voice.ml
|
ocaml
|
* Copyright ( C ) 2015 Ga �
*
* All rights reserved . This file is distributed under the terms of the
* GNU General Public License version 3.0 .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* Copyright (C) 2015 Ga�tan Dubreil
*
* All rights reserved.This file is distributed under the terms of the
* GNU General Public License version 3.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
exception End
exception Ok
let defOutputTag = "O"
type port_t = int
type 'a t = {
mutable tick : int;
mutable len : int;
mutable cor : Cornet.t;
mutable tkr : 'a;
port : port_t;
vTag : string
}
let init l f = Cornet.init l ~f
let get voice i = Cornet.get voice.cor i
let set voice i v = Cornet.set voice.cor i v
let fill voice ofs len v = Cornet.fill voice.cor ofs len v
let add voice i v = Cornet.set voice.cor i (Cornet.get voice.cor i +. v)
let sub voice i v = Cornet.set voice.cor i (Cornet.get voice.cor i -. v)
let mul voice i v = Cornet.set voice.cor i (Cornet.get voice.cor i *. v)
let div voice i v = Cornet.set voice.cor i (Cornet.get voice.cor i /. v)
let dim voice = Cornet.dim voice.cor
let getTag voice = voice.vTag
let getIdentity voice =
let tkr_id = if String.length voice.tkr#getName > 0 then voice.tkr#getName
else voice.tkr#getKind in
tkr_id ^ "." ^ voice.vTag
let getPort voice = voice.port
let getTalker voice = voice.tkr
let getTick voice = voice.tick
let getLength voice = voice.len
let getCornet voice = voice.cor
let setTalker voice v = voice.tkr <- v
let setTick voice v = voice.tick <- v
let setLength voice v = voice.len <- v
let setCornet voice v = voice.cor <- v
let checkLength voice len =
if Cornet.dim voice.cor < len then voice.cor <- Cornet.make len
let isFrom tkrId port voice = voice.port = port && voice.tkr#getId = tkrId
|
|
5c86fcc91c85fd0cc75eb96f4d5bd8cfd58d66c05fc3a59bd6c803e5aa469b11
|
mbutterick/aoc-racket
|
day05.rkt
|
#lang scribble/lp2
@(require scribble/manual aoc-racket/helper)
@aoc-title[5]
@defmodule[aoc-racket/day05]
@link[""]{The puzzle}. Our @link-rp["day05-input.txt"]{input} is a list of random-looking but not really random text strings.
@chunk[<day05>
<day05-setup>
<day05-q1>
<day05-q2>
<day05-test>]
@isection{How many strings are ``nice''?}
A string is ``nice'' if it meets certain criteria:
@itemlist[
@item{Contains three vowels (= @litchar{aeiou}).}
@item{Contains a double letter.}
@item{Does not contain @litchar{ab}, @litchar{cd}, @litchar{pq}, or @litchar{xy}.}
]
This is a job for @iracket[regexp-match]. There's nothing tricky here (except for remembering that certain matching functions require the @iracket[pregexp] pattern prefix rather than @racket[regexp]).
@chunk[<day05-setup>
(require racket rackunit)
(provide (all-defined-out))
]
@chunk[<day05-q1>
(define (nice? str)
(define (three-vowels? str)
(>= (length (regexp-match* #rx"[aeiou]" str)) 3))
(define (double-letter? str)
(regexp-match #px"(.)\\1" str))
(define (no-kapu? str)
(not (regexp-match #rx"ab|cd|pq|xy" str)))
(and (three-vowels? str)
(double-letter? str)
(no-kapu? str)))
(define (q1 words)
(length (filter nice? words)))
]
@section{How many strings are ``nice'' under new rules?}
This time a string is ``nice`` if it:
@itemlist[
@item{Contains a pair of two letters that appears twice without overlapping}
@item{Contains a letter that repeats with at least one letter in between}
]
Again, a test of your regexp-writing skills.
@chunk[<day05-q2>
(define (nicer? str)
(define (nonoverlapping-pair? str)
(regexp-match #px"(..).*\\1" str))
(define (separated-repeater? str)
(regexp-match #px"(.).\\1" str))
(and (nonoverlapping-pair? str)
(separated-repeater? str) #t))
(define (q2 words)
(length (filter nicer? words)))]
@section{Testing Day 5}
@chunk[<day05-test>
(module+ test
(define input-str (file->lines "day05-input.txt"))
(check-equal? (q1 input-str) 238)
(check-equal? (q2 input-str) 69))]
| null |
https://raw.githubusercontent.com/mbutterick/aoc-racket/2c6cb2f3ad876a91a82f33ce12844f7758b969d6/day05.rkt
|
racket
|
#lang scribble/lp2
@(require scribble/manual aoc-racket/helper)
@aoc-title[5]
@defmodule[aoc-racket/day05]
@link[""]{The puzzle}. Our @link-rp["day05-input.txt"]{input} is a list of random-looking but not really random text strings.
@chunk[<day05>
<day05-setup>
<day05-q1>
<day05-q2>
<day05-test>]
@isection{How many strings are ``nice''?}
A string is ``nice'' if it meets certain criteria:
@itemlist[
@item{Contains three vowels (= @litchar{aeiou}).}
@item{Contains a double letter.}
@item{Does not contain @litchar{ab}, @litchar{cd}, @litchar{pq}, or @litchar{xy}.}
]
This is a job for @iracket[regexp-match]. There's nothing tricky here (except for remembering that certain matching functions require the @iracket[pregexp] pattern prefix rather than @racket[regexp]).
@chunk[<day05-setup>
(require racket rackunit)
(provide (all-defined-out))
]
@chunk[<day05-q1>
(define (nice? str)
(define (three-vowels? str)
(>= (length (regexp-match* #rx"[aeiou]" str)) 3))
(define (double-letter? str)
(regexp-match #px"(.)\\1" str))
(define (no-kapu? str)
(not (regexp-match #rx"ab|cd|pq|xy" str)))
(and (three-vowels? str)
(double-letter? str)
(no-kapu? str)))
(define (q1 words)
(length (filter nice? words)))
]
@section{How many strings are ``nice'' under new rules?}
This time a string is ``nice`` if it:
@itemlist[
@item{Contains a pair of two letters that appears twice without overlapping}
@item{Contains a letter that repeats with at least one letter in between}
]
Again, a test of your regexp-writing skills.
@chunk[<day05-q2>
(define (nicer? str)
(define (nonoverlapping-pair? str)
(regexp-match #px"(..).*\\1" str))
(define (separated-repeater? str)
(regexp-match #px"(.).\\1" str))
(and (nonoverlapping-pair? str)
(separated-repeater? str) #t))
(define (q2 words)
(length (filter nicer? words)))]
@section{Testing Day 5}
@chunk[<day05-test>
(module+ test
(define input-str (file->lines "day05-input.txt"))
(check-equal? (q1 input-str) 238)
(check-equal? (q2 input-str) 69))]
|
|
cc5682468e2e26ea69cadef843b373305ee89bf04c2f54748c21dde3a1cbced8
|
racket/rhombus-prototype
|
unquote-binding-primitive.rkt
|
#lang racket/base
(require (for-syntax racket/base
syntax/parse/pre
enforest/hier-name-parse
enforest/name-parse
enforest/syntax-local
"name-path-op.rkt"
"attribute-name.rkt")
syntax/parse/pre
enforest/name-parse
"pack.rkt"
"syntax-class-primitive.rkt"
(only-in "expression.rkt"
in-expression-space)
(submod "syntax-class-primitive.rkt" for-quasiquote)
(only-in "annotation.rkt"
::)
(only-in "repetition.rkt"
in-repetition-space)
"pattern-variable.rkt"
"unquote-binding.rkt"
"unquote-binding-identifier.rkt"
"name-root-space.rkt"
"name-root-ref.rkt"
"space.rkt"
"parens.rkt"
(submod "function-parse.rkt" for-call)
(only-in "import.rkt" as open)
(submod "import.rkt" for-meta)
(submod "syntax-class.rkt" for-pattern-clause))
(provide (for-space rhombus/unquote_bind
#%parens
::
pattern
&&
\|\|
#%literal
#%block
bound_as))
` # % quotes ` is implemented in " quasiquote.rkt " because it recurs as
;; nested quasiquote matching, `_` is in "quasiquote.rkt" so it can be
;; matched literally, and plain identifiers are implemented in
;; "unquote-binding-identifier.rkt"
(define-unquote-binding-syntax #%parens
(unquote-binding-transformer
(lambda (stx)
(syntax-parse stx
[(_ (parens g::unquote-binding) . tail)
(values #'g.parsed
#'tail)]
[(_ (parens) . tail)
;; empty parentheses match an empty group, which
;; is only useful for matching an empty group tail
(case (current-unquote-binding-kind)
[(group)
(values #`((group) () () ())
#'tail)]
[(term)
(raise-syntax-error #f "incompatible with this context" #'self)]
[else (values #'#f #'())])]))))
(begin-for-syntax
(define-splicing-syntax-class :syntax-class-args
(pattern (~seq (~and args (_::parens . _))))
(pattern (~seq)
#:attr args #'#f))
(define (parse-syntax-class-args stx-class rator-in arity class-args)
(cond
[(not arity)
(when (syntax-e class-args)
(raise-syntax-error #f
"syntax class does not expect arguments"
stx-class))
rator-in]
[(not (syntax-e class-args))
(raise-syntax-error #f
"syntax class expects arguments"
stx-class)]
[else
(define-values (call empty-tail)
(parse-function-call rator-in '() #`(#,stx-class #,class-args)
#:static? #t
#:rator-stx stx-class
#:rator-kind '|syntax class|
#:rator-arity arity))
call])))
(define-unquote-binding-syntax ::
(unquote-binding-infix-operator
(in-unquote-binding-space #'::)
null
'macro
(lambda (form1 stx)
(unless (or (identifier? form1)
(syntax-parse form1
[(underscore () () ())
(free-identifier=? #'underscore #'_)]))
(raise-syntax-error #f
"preceding term must be an identifier or `_`"
(syntax-parse stx
[(colons . _) #'colons])))
(define (lookup-syntax-class stx-class)
(define rsc (syntax-local-value* (in-syntax-class-space stx-class) syntax-class-ref))
(or rsc
(raise-syntax-error #f
"not bound as a syntax class"
stx-class)))
(define (parse-open-block stx tail)
(syntax-parse tail
#:datum-literals (group)
[((_::block g ...))
(values
(for/fold ([open #hasheq()]) ([g (in-list (syntax->list #'(g ...)))])
(syntax-parse g
#:datum-literals (group)
[(group id:identifier)
(free-identifier=? (in-import-space #'id) (in-import-space #'open))
(when (syntax? open)
(raise-syntax-error #f "redundant opening clause" stx #'id))
(when (and (hash? open) ((hash-count open) . > . 0))
(raise-syntax-error #f "opening clause not allowed after specific fields" stx #'id))
#'id]
[(group field:identifier as:identifier bind:identifier)
(free-identifier=? (in-import-space #'id) (in-import-space #'as))
(when (syntax? open)
(raise-syntax-error #f "specific field not allowed after opening clause" stx #'field))
(define key (syntax-e #'field))
(hash-set open key (cons (cons #'field #'bind) (hash-ref open key null)))]
[(group field:identifier ...)
(when (syntax? open)
(raise-syntax-error #f "specific field not allowed after opening clause" stx
(car (syntax-e #'(field ...)))))
(for/fold ([open open]) ([field (in-list (syntax->list #'(field ...)))])
(define key (syntax-e field))
(hash-set open key (cons (cons field field) (hash-ref open key null))))]
[_
(raise-syntax-error #f "bad exposure clause" stx g)]))
#'())]
[_ (values #f tail)]))
(define match-id (car (generate-temporaries (list form1))))
(syntax-parse stx
#:datum-literals (group)
[(_ (~and sc (_::parens (group . rest))) . tail)
#:with (~var sc-hier (:hier-name-seq in-name-root-space in-expression-space name-path-op name-root-ref)) #'rest
#:do [(define parser (syntax-local-value* #'sc-hier.name syntax-class-parser-ref))]
#:when parser
(define-values (open-attributes end-tail) (parse-open-block stx #'tail))
(define rsc ((syntax-class-parser-proc parser) (or (syntax-property #'sc-hier.name 'rhombus-dotted-name)
(syntax-e #'sc-hier.name))
#'sc
(current-unquote-binding-kind)
match-id
#'sc-hier.tail))
(if rsc
(values (build-syntax-class-pattern #'sc rsc #'#f open-attributes form1 match-id)
end-tail)
;; shortcut for kind mismatch
(values #'#f #'()))]
[(_ . rest)
#:with (~var stx-class-hier (:hier-name-seq in-name-root-space in-syntax-class-space name-path-op name-root-ref)) #'rest
(syntax-parse #'stx-class-hier.tail
#:datum-literals ()
[(args::syntax-class-args . args-tail)
(define-values (open-attributes tail) (parse-open-block stx #'args-tail))
(values (build-syntax-class-pattern #'stx-class-hier.name
(lookup-syntax-class #'stx-class-hier.name)
#'args.args
open-attributes
form1
match-id)
tail)])]))
'none))
(define-unquote-binding-syntax pattern
(unquote-binding-transformer
(lambda (stx)
(define inline-id #f)
(define rsc (parse-pattern-clause stx (current-unquote-binding-kind)))
(values (if rsc
(build-syntax-class-pattern stx
rsc
#'#f
(syntax-parse stx [(form-id . _) #'form-id])
#f
inline-id)
#'#f)
#'()))))
(begin-for-syntax
(struct open-attrib (sym bind-id var)))
;; used for `::` and for `pattern`, returns a parsed binding form that takes advantage
;; of a syntax class --- possibly an inlined syntax class and/or one with exposed fields
(define-for-syntax (build-syntax-class-pattern stx-class rsc class-args open-attributes-spec
form1 match-id)
(with-syntax ([id (if (identifier? form1) form1 #'wildcard)])
(define (compat pack* unpack*)
(define sc (rhombus-syntax-class-class rsc))
(define sc-call (parse-syntax-class-args stx-class
sc
(rhombus-syntax-class-arity rsc)
class-args))
(define temp-id (car (generate-temporaries (list #'id))))
(define vars (for/list ([l (in-list (syntax->list (rhombus-syntax-class-attributes rsc)))])
(syntax-list->pattern-variable l)))
(define swap-to-root (and (rhombus-syntax-class-root-swap rsc)
(car (rhombus-syntax-class-root-swap rsc))))
(define swap-root-to-id (and (rhombus-syntax-class-root-swap rsc)
(cdr (rhombus-syntax-class-root-swap rsc))))
(define swap-root-to (if (syntax? swap-root-to-id)
(syntax-e swap-root-to-id)
swap-root-to-id))
(define-values (attribute-bindings attribute-vars)
(for/lists (bindings descs) ([var (in-list vars)]
[temp-attr (in-list (generate-temporaries (map pattern-variable-sym vars)))]
[bind-counter (in-naturals)])
(define name (pattern-variable-sym var))
(define id (pattern-variable-id var))
(define depth (pattern-variable-depth var))
(define unpack*-id (pattern-variable-unpack*-id var))
(define id-with-attr (compose-attr-name match-id name id bind-counter))
(values #`[#,temp-attr #,(cond
[(eq? depth 'tail)
;; bridge from a primitive syntax class, where we don't want to convert to
;; a list and then convert back when the tail is used as a new tail in a
;; template
#`(pack-tail* (syntax #,id-with-attr) 0)]
[(not (or (free-identifier=? unpack*-id #'unpack-tail-list*)
(free-identifier=? unpack*-id #'unpack-multi-tail-list*)
(free-identifier=? unpack*-id #'unpack-parsed*)))
;; assume depth-compatible value checked on binding side, and
;; let `attribute` unpack syntax repetitions
#`(pack-nothing* (attribute #,id-with-attr) #,depth)]
[else
#`(#,(cond
[(free-identifier=? unpack*-id #'unpack-tail-list*)
#'pack-tail-list*]
[(free-identifier=? unpack*-id #'unpack-multi-tail-list*)
#'pack-multi-tail-list*]
[(free-identifier=? unpack*-id #'unpack-parsed*)
#'pack-parsed*]
[else #'pack-term*])
(syntax #,(let loop ([t id-with-attr] [depth depth])
(if (zero? depth)
t
(loop #`(#,t #,(quote-syntax ...)) (sub1 depth)))))
#,depth)])]
(pattern-variable name id temp-attr (if (eq? depth 'tail) 1 depth) unpack*-id))))
;; #f or (list (list bind-id var))
(define open-attributes
(cond
[(not open-attributes-spec) #f]
[(hash? open-attributes-spec)
(define found-attributes
(for/hasheq ([var (in-list attribute-vars)])
(values (pattern-variable-sym var) var)))
(for/list ([name (in-hash-keys open-attributes-spec #t)]
#:do [(define field+binds (hash-ref open-attributes-spec name))
(define var-or-root
(cond
[(eq? name swap-to-root) #f]
[(eq? name swap-root-to) 'root]
[else
(hash-ref found-attributes name #f)]))
(unless var-or-root
(raise-syntax-error #f
"not an attribute of the syntax class"
pick abritaty open for the same field name
(caar field+binds)))]
[field+bind (in-list field+binds)])
(open-attrib (syntax-e (car field+bind)) (cdr field+bind) var-or-root))]
[else
(append
(if swap-root-to
(let ([id (if (identifier? swap-root-to-id)
swap-root-to-id
(datum->syntax open-attributes-spec swap-root-to open-attributes-spec))])
(list (open-attrib (syntax-e id) id 'root)))
null)
(for/list ([var (in-list attribute-vars)]
#:unless (eq? (pattern-variable-sym var) swap-to-root))
(define id (or (pattern-variable-id var)
(datum->syntax open-attributes-spec (pattern-variable-sym var) open-attributes-spec)))
(open-attrib (syntax-e id) id var)))]))
(define pack-depth 0)
(define dotted-bind? (and sc (not (identifier? sc)) (rhombus-syntax-class-splicing? rsc)))
(define instance-id (or match-id (car (generate-temporaries '(inline)))))
(define swap-to-root-var
(for/first ([var (in-list attribute-vars)]
#:when (eq? (pattern-variable-sym var) swap-to-root))
var))
#`(#,(if sc
(if (identifier? sc)
#`(~var #,instance-id #,sc-call)
#`(~and #,(if dotted-bind?
#`(~seq #,instance-id (... ...))
instance-id)
#,sc)) ; inline syntax class
instance-id)
#,(cons #`[#,temp-id (#,pack* (syntax #,(if dotted-bind?
#`(#,instance-id (... ...))
instance-id))
#,pack-depth)]
attribute-bindings)
#,(append
(if (identifier? form1)
(list (make-pattern-variable-bind #'id
(if swap-to-root-var
(pattern-variable-val-id swap-to-root-var)
temp-id)
(if swap-to-root-var
(pattern-variable-unpack*-id swap-to-root-var)
unpack*)
(if swap-to-root-var
(pattern-variable-depth swap-to-root-var)
pack-depth)
(append
(if swap-root-to
(list
(pattern-variable->list
(pattern-variable swap-root-to #f temp-id pack-depth unpack*)))
null)
(for/list ([var (in-list attribute-vars)]
#:unless (eq? swap-to-root (pattern-variable-sym var)))
(pattern-variable->list var #:keep-id? #f)))))
null)
(if (not open-attributes)
null
(for/list ([oa (in-list open-attributes)]
#:unless (eq? 'root (open-attrib-var oa)))
(define bind-id (open-attrib-bind-id oa))
(define var (open-attrib-var oa))
(make-pattern-variable-bind bind-id (pattern-variable-val-id var) (pattern-variable-unpack*-id var)
(pattern-variable-depth var) null))))
#,(append
(if (identifier? form1)
(list
(if swap-to-root
(pattern-variable->list (struct-copy pattern-variable swap-to-root-var
[sym swap-to-root]
[id #f]))
(list #'id #'id temp-id pack-depth unpack*)))
null)
(if (not open-attributes)
null
(for/list ([oa (in-list open-attributes)])
(define var (open-attrib-var oa))
(if (eq? var 'root)
(pattern-variable->list
(pattern-variable (open-attrib-sym oa) #f temp-id pack-depth unpack*))
(pattern-variable->list (struct-copy pattern-variable var
[sym (open-attrib-sym oa)]))))))))
(define (incompat)
(raise-syntax-error #f
"syntax class incompatible with this context"
stx-class))
(define (retry) #'#f)
(define kind (current-unquote-binding-kind))
(cond
[(eq? (rhombus-syntax-class-kind rsc) 'term)
(cond
[(not (eq? kind 'term)) (retry)]
[(rhombus-syntax-class-splicing? rsc)
(compat #'pack-tail* #'unpack-group*)]
[else (compat #'pack-term* #'unpack-term*)])]
[(eq? (rhombus-syntax-class-kind rsc) 'group)
(cond
[(eq? kind 'term) (incompat)]
[(not (eq? kind 'group)) (retry)]
[else (compat #'pack-group* #'unpack-group*)])]
[(eq? (rhombus-syntax-class-kind rsc) 'multi)
(cond
[(or (eq? kind 'multi) (eq? kind 'block))
(compat #'pack-tagged-multi* #'unpack-multi-as-term*)]
[else (incompat)])]
[(eq? (rhombus-syntax-class-kind rsc) 'block)
(cond
[(eq? kind 'block)
(compat #'pack-block* #'unpack-multi-as-term*)]
[else (incompat)])]
[else
(error "unrecognized kind" kind)])))
(define-for-syntax (normalize-id form)
(if (identifier? form)
(identifier-as-unquote-binding form (current-unquote-binding-kind))
form))
(define-for-syntax (norm-seq pat like-pat)
(syntax-parse pat
[((~datum ~seq) . _) pat]
[_ (syntax-parse like-pat
[((~datum ~seq) . _) #`(~seq #,pat)]
[_ pat])]))
(define-unquote-binding-syntax &&
(unquote-binding-infix-operator
(in-unquote-binding-space #'&&)
null
'automatic
(lambda (form1 form2 stx)
(syntax-parse (normalize-id form1)
[#f #'#f]
[(pat1 (idr1 ...) (sidr1 ...) (var1 ...))
(syntax-parse (normalize-id form2)
[#f #'#f]
[(pat2 idrs2 sidrs2 vars2)
#`((~and #,(norm-seq #'pat1 #'pat2) #,(norm-seq #'pat2 #'pat1))
(idr1 ... . idrs2)
(sidr1 ... . sidrs2)
(var1 ... . vars2))])]))
'left))
(define-unquote-binding-syntax \|\|
(unquote-binding-infix-operator
(in-unquote-binding-space #'\|\|)
null
'automatic
(lambda (form1 form2 stx)
(syntax-parse (normalize-id form1)
[#f #'#f]
[(pat1 idrs1 sidrs1 vars1)
(syntax-parse (normalize-id form2)
[#f #'#f]
[(pat2 idrs2 sidrs2 vars2)
#`((~or #,(norm-seq #'pat1 #'pat2)
#,(norm-seq #'pat2 #'pat1))
()
()
())])]))
'left))
(define-unquote-binding-syntax #%literal
(unquote-binding-transformer
(lambda (stxes)
(syntax-parse stxes
[(_ x . _)
(raise-syntax-error #f
(format "misplaced ~a within a syntax binding"
(if (keyword? (syntax-e #'x))
"keyword"
"literal"))
#'x)]))))
(define-unquote-binding-syntax #%block
(unquote-binding-transformer
(lambda (stxes)
(syntax-parse stxes
[(_ b)
(raise-syntax-error #f
"not allowed as a syntax binding by itself"
#'b)]))))
(define-unquote-binding-syntax bound_as
(unquote-binding-transformer
(lambda (stxes)
(cond
[(eq? (current-unquote-binding-kind) 'term)
(syntax-parse stxes
#:datum-literals (group)
[(_ space ... (_::block (group (_::quotes (group bound::name)))))
#:with (~var sp (:hier-name-seq in-name-root-space in-space-space name-path-op name-root-ref)) #'(space ...)
(define sn (syntax-local-value* (in-space-space #'sp.name) space-name-ref))
(unless sn
(raise-syntax-error #f
"not a space name"
stxes
#'sp.name))
(values #`((~var _ (:free=-in-space
(quote-syntax #,(if (space-name-symbol sn)
((make-interned-syntax-introducer (space-name-symbol sn)) #'bound.name 'add)
#'bound.name))
'#,(space-name-symbol sn)))
()
()
())
#'())])]
[else (values #'#f #'())]))))
(define-syntax-class (:free=-in-space bound-id space-sym)
#:datum-literals (group)
(pattern t::name
#:when (free-identifier=? bound-id (if space-sym
((make-interned-syntax-introducer space-sym) #'t.name 'add)
#'t.name))))
| null |
https://raw.githubusercontent.com/racket/rhombus-prototype/b05f8a1515cf01c6b431f820c2a7f62b2b9532a8/rhombus/private/unquote-binding-primitive.rkt
|
racket
|
nested quasiquote matching, `_` is in "quasiquote.rkt" so it can be
matched literally, and plain identifiers are implemented in
"unquote-binding-identifier.rkt"
empty parentheses match an empty group, which
is only useful for matching an empty group tail
shortcut for kind mismatch
used for `::` and for `pattern`, returns a parsed binding form that takes advantage
of a syntax class --- possibly an inlined syntax class and/or one with exposed fields
bridge from a primitive syntax class, where we don't want to convert to
a list and then convert back when the tail is used as a new tail in a
template
assume depth-compatible value checked on binding side, and
let `attribute` unpack syntax repetitions
#f or (list (list bind-id var))
inline syntax class
|
#lang racket/base
(require (for-syntax racket/base
syntax/parse/pre
enforest/hier-name-parse
enforest/name-parse
enforest/syntax-local
"name-path-op.rkt"
"attribute-name.rkt")
syntax/parse/pre
enforest/name-parse
"pack.rkt"
"syntax-class-primitive.rkt"
(only-in "expression.rkt"
in-expression-space)
(submod "syntax-class-primitive.rkt" for-quasiquote)
(only-in "annotation.rkt"
::)
(only-in "repetition.rkt"
in-repetition-space)
"pattern-variable.rkt"
"unquote-binding.rkt"
"unquote-binding-identifier.rkt"
"name-root-space.rkt"
"name-root-ref.rkt"
"space.rkt"
"parens.rkt"
(submod "function-parse.rkt" for-call)
(only-in "import.rkt" as open)
(submod "import.rkt" for-meta)
(submod "syntax-class.rkt" for-pattern-clause))
(provide (for-space rhombus/unquote_bind
#%parens
::
pattern
&&
\|\|
#%literal
#%block
bound_as))
` # % quotes ` is implemented in " quasiquote.rkt " because it recurs as
(define-unquote-binding-syntax #%parens
(unquote-binding-transformer
(lambda (stx)
(syntax-parse stx
[(_ (parens g::unquote-binding) . tail)
(values #'g.parsed
#'tail)]
[(_ (parens) . tail)
(case (current-unquote-binding-kind)
[(group)
(values #`((group) () () ())
#'tail)]
[(term)
(raise-syntax-error #f "incompatible with this context" #'self)]
[else (values #'#f #'())])]))))
(begin-for-syntax
(define-splicing-syntax-class :syntax-class-args
(pattern (~seq (~and args (_::parens . _))))
(pattern (~seq)
#:attr args #'#f))
(define (parse-syntax-class-args stx-class rator-in arity class-args)
(cond
[(not arity)
(when (syntax-e class-args)
(raise-syntax-error #f
"syntax class does not expect arguments"
stx-class))
rator-in]
[(not (syntax-e class-args))
(raise-syntax-error #f
"syntax class expects arguments"
stx-class)]
[else
(define-values (call empty-tail)
(parse-function-call rator-in '() #`(#,stx-class #,class-args)
#:static? #t
#:rator-stx stx-class
#:rator-kind '|syntax class|
#:rator-arity arity))
call])))
(define-unquote-binding-syntax ::
(unquote-binding-infix-operator
(in-unquote-binding-space #'::)
null
'macro
(lambda (form1 stx)
(unless (or (identifier? form1)
(syntax-parse form1
[(underscore () () ())
(free-identifier=? #'underscore #'_)]))
(raise-syntax-error #f
"preceding term must be an identifier or `_`"
(syntax-parse stx
[(colons . _) #'colons])))
(define (lookup-syntax-class stx-class)
(define rsc (syntax-local-value* (in-syntax-class-space stx-class) syntax-class-ref))
(or rsc
(raise-syntax-error #f
"not bound as a syntax class"
stx-class)))
(define (parse-open-block stx tail)
(syntax-parse tail
#:datum-literals (group)
[((_::block g ...))
(values
(for/fold ([open #hasheq()]) ([g (in-list (syntax->list #'(g ...)))])
(syntax-parse g
#:datum-literals (group)
[(group id:identifier)
(free-identifier=? (in-import-space #'id) (in-import-space #'open))
(when (syntax? open)
(raise-syntax-error #f "redundant opening clause" stx #'id))
(when (and (hash? open) ((hash-count open) . > . 0))
(raise-syntax-error #f "opening clause not allowed after specific fields" stx #'id))
#'id]
[(group field:identifier as:identifier bind:identifier)
(free-identifier=? (in-import-space #'id) (in-import-space #'as))
(when (syntax? open)
(raise-syntax-error #f "specific field not allowed after opening clause" stx #'field))
(define key (syntax-e #'field))
(hash-set open key (cons (cons #'field #'bind) (hash-ref open key null)))]
[(group field:identifier ...)
(when (syntax? open)
(raise-syntax-error #f "specific field not allowed after opening clause" stx
(car (syntax-e #'(field ...)))))
(for/fold ([open open]) ([field (in-list (syntax->list #'(field ...)))])
(define key (syntax-e field))
(hash-set open key (cons (cons field field) (hash-ref open key null))))]
[_
(raise-syntax-error #f "bad exposure clause" stx g)]))
#'())]
[_ (values #f tail)]))
(define match-id (car (generate-temporaries (list form1))))
(syntax-parse stx
#:datum-literals (group)
[(_ (~and sc (_::parens (group . rest))) . tail)
#:with (~var sc-hier (:hier-name-seq in-name-root-space in-expression-space name-path-op name-root-ref)) #'rest
#:do [(define parser (syntax-local-value* #'sc-hier.name syntax-class-parser-ref))]
#:when parser
(define-values (open-attributes end-tail) (parse-open-block stx #'tail))
(define rsc ((syntax-class-parser-proc parser) (or (syntax-property #'sc-hier.name 'rhombus-dotted-name)
(syntax-e #'sc-hier.name))
#'sc
(current-unquote-binding-kind)
match-id
#'sc-hier.tail))
(if rsc
(values (build-syntax-class-pattern #'sc rsc #'#f open-attributes form1 match-id)
end-tail)
(values #'#f #'()))]
[(_ . rest)
#:with (~var stx-class-hier (:hier-name-seq in-name-root-space in-syntax-class-space name-path-op name-root-ref)) #'rest
(syntax-parse #'stx-class-hier.tail
#:datum-literals ()
[(args::syntax-class-args . args-tail)
(define-values (open-attributes tail) (parse-open-block stx #'args-tail))
(values (build-syntax-class-pattern #'stx-class-hier.name
(lookup-syntax-class #'stx-class-hier.name)
#'args.args
open-attributes
form1
match-id)
tail)])]))
'none))
(define-unquote-binding-syntax pattern
(unquote-binding-transformer
(lambda (stx)
(define inline-id #f)
(define rsc (parse-pattern-clause stx (current-unquote-binding-kind)))
(values (if rsc
(build-syntax-class-pattern stx
rsc
#'#f
(syntax-parse stx [(form-id . _) #'form-id])
#f
inline-id)
#'#f)
#'()))))
(begin-for-syntax
(struct open-attrib (sym bind-id var)))
(define-for-syntax (build-syntax-class-pattern stx-class rsc class-args open-attributes-spec
form1 match-id)
(with-syntax ([id (if (identifier? form1) form1 #'wildcard)])
(define (compat pack* unpack*)
(define sc (rhombus-syntax-class-class rsc))
(define sc-call (parse-syntax-class-args stx-class
sc
(rhombus-syntax-class-arity rsc)
class-args))
(define temp-id (car (generate-temporaries (list #'id))))
(define vars (for/list ([l (in-list (syntax->list (rhombus-syntax-class-attributes rsc)))])
(syntax-list->pattern-variable l)))
(define swap-to-root (and (rhombus-syntax-class-root-swap rsc)
(car (rhombus-syntax-class-root-swap rsc))))
(define swap-root-to-id (and (rhombus-syntax-class-root-swap rsc)
(cdr (rhombus-syntax-class-root-swap rsc))))
(define swap-root-to (if (syntax? swap-root-to-id)
(syntax-e swap-root-to-id)
swap-root-to-id))
(define-values (attribute-bindings attribute-vars)
(for/lists (bindings descs) ([var (in-list vars)]
[temp-attr (in-list (generate-temporaries (map pattern-variable-sym vars)))]
[bind-counter (in-naturals)])
(define name (pattern-variable-sym var))
(define id (pattern-variable-id var))
(define depth (pattern-variable-depth var))
(define unpack*-id (pattern-variable-unpack*-id var))
(define id-with-attr (compose-attr-name match-id name id bind-counter))
(values #`[#,temp-attr #,(cond
[(eq? depth 'tail)
#`(pack-tail* (syntax #,id-with-attr) 0)]
[(not (or (free-identifier=? unpack*-id #'unpack-tail-list*)
(free-identifier=? unpack*-id #'unpack-multi-tail-list*)
(free-identifier=? unpack*-id #'unpack-parsed*)))
#`(pack-nothing* (attribute #,id-with-attr) #,depth)]
[else
#`(#,(cond
[(free-identifier=? unpack*-id #'unpack-tail-list*)
#'pack-tail-list*]
[(free-identifier=? unpack*-id #'unpack-multi-tail-list*)
#'pack-multi-tail-list*]
[(free-identifier=? unpack*-id #'unpack-parsed*)
#'pack-parsed*]
[else #'pack-term*])
(syntax #,(let loop ([t id-with-attr] [depth depth])
(if (zero? depth)
t
(loop #`(#,t #,(quote-syntax ...)) (sub1 depth)))))
#,depth)])]
(pattern-variable name id temp-attr (if (eq? depth 'tail) 1 depth) unpack*-id))))
(define open-attributes
(cond
[(not open-attributes-spec) #f]
[(hash? open-attributes-spec)
(define found-attributes
(for/hasheq ([var (in-list attribute-vars)])
(values (pattern-variable-sym var) var)))
(for/list ([name (in-hash-keys open-attributes-spec #t)]
#:do [(define field+binds (hash-ref open-attributes-spec name))
(define var-or-root
(cond
[(eq? name swap-to-root) #f]
[(eq? name swap-root-to) 'root]
[else
(hash-ref found-attributes name #f)]))
(unless var-or-root
(raise-syntax-error #f
"not an attribute of the syntax class"
pick abritaty open for the same field name
(caar field+binds)))]
[field+bind (in-list field+binds)])
(open-attrib (syntax-e (car field+bind)) (cdr field+bind) var-or-root))]
[else
(append
(if swap-root-to
(let ([id (if (identifier? swap-root-to-id)
swap-root-to-id
(datum->syntax open-attributes-spec swap-root-to open-attributes-spec))])
(list (open-attrib (syntax-e id) id 'root)))
null)
(for/list ([var (in-list attribute-vars)]
#:unless (eq? (pattern-variable-sym var) swap-to-root))
(define id (or (pattern-variable-id var)
(datum->syntax open-attributes-spec (pattern-variable-sym var) open-attributes-spec)))
(open-attrib (syntax-e id) id var)))]))
(define pack-depth 0)
(define dotted-bind? (and sc (not (identifier? sc)) (rhombus-syntax-class-splicing? rsc)))
(define instance-id (or match-id (car (generate-temporaries '(inline)))))
(define swap-to-root-var
(for/first ([var (in-list attribute-vars)]
#:when (eq? (pattern-variable-sym var) swap-to-root))
var))
#`(#,(if sc
(if (identifier? sc)
#`(~var #,instance-id #,sc-call)
#`(~and #,(if dotted-bind?
#`(~seq #,instance-id (... ...))
instance-id)
instance-id)
#,(cons #`[#,temp-id (#,pack* (syntax #,(if dotted-bind?
#`(#,instance-id (... ...))
instance-id))
#,pack-depth)]
attribute-bindings)
#,(append
(if (identifier? form1)
(list (make-pattern-variable-bind #'id
(if swap-to-root-var
(pattern-variable-val-id swap-to-root-var)
temp-id)
(if swap-to-root-var
(pattern-variable-unpack*-id swap-to-root-var)
unpack*)
(if swap-to-root-var
(pattern-variable-depth swap-to-root-var)
pack-depth)
(append
(if swap-root-to
(list
(pattern-variable->list
(pattern-variable swap-root-to #f temp-id pack-depth unpack*)))
null)
(for/list ([var (in-list attribute-vars)]
#:unless (eq? swap-to-root (pattern-variable-sym var)))
(pattern-variable->list var #:keep-id? #f)))))
null)
(if (not open-attributes)
null
(for/list ([oa (in-list open-attributes)]
#:unless (eq? 'root (open-attrib-var oa)))
(define bind-id (open-attrib-bind-id oa))
(define var (open-attrib-var oa))
(make-pattern-variable-bind bind-id (pattern-variable-val-id var) (pattern-variable-unpack*-id var)
(pattern-variable-depth var) null))))
#,(append
(if (identifier? form1)
(list
(if swap-to-root
(pattern-variable->list (struct-copy pattern-variable swap-to-root-var
[sym swap-to-root]
[id #f]))
(list #'id #'id temp-id pack-depth unpack*)))
null)
(if (not open-attributes)
null
(for/list ([oa (in-list open-attributes)])
(define var (open-attrib-var oa))
(if (eq? var 'root)
(pattern-variable->list
(pattern-variable (open-attrib-sym oa) #f temp-id pack-depth unpack*))
(pattern-variable->list (struct-copy pattern-variable var
[sym (open-attrib-sym oa)]))))))))
(define (incompat)
(raise-syntax-error #f
"syntax class incompatible with this context"
stx-class))
(define (retry) #'#f)
(define kind (current-unquote-binding-kind))
(cond
[(eq? (rhombus-syntax-class-kind rsc) 'term)
(cond
[(not (eq? kind 'term)) (retry)]
[(rhombus-syntax-class-splicing? rsc)
(compat #'pack-tail* #'unpack-group*)]
[else (compat #'pack-term* #'unpack-term*)])]
[(eq? (rhombus-syntax-class-kind rsc) 'group)
(cond
[(eq? kind 'term) (incompat)]
[(not (eq? kind 'group)) (retry)]
[else (compat #'pack-group* #'unpack-group*)])]
[(eq? (rhombus-syntax-class-kind rsc) 'multi)
(cond
[(or (eq? kind 'multi) (eq? kind 'block))
(compat #'pack-tagged-multi* #'unpack-multi-as-term*)]
[else (incompat)])]
[(eq? (rhombus-syntax-class-kind rsc) 'block)
(cond
[(eq? kind 'block)
(compat #'pack-block* #'unpack-multi-as-term*)]
[else (incompat)])]
[else
(error "unrecognized kind" kind)])))
(define-for-syntax (normalize-id form)
(if (identifier? form)
(identifier-as-unquote-binding form (current-unquote-binding-kind))
form))
(define-for-syntax (norm-seq pat like-pat)
(syntax-parse pat
[((~datum ~seq) . _) pat]
[_ (syntax-parse like-pat
[((~datum ~seq) . _) #`(~seq #,pat)]
[_ pat])]))
(define-unquote-binding-syntax &&
(unquote-binding-infix-operator
(in-unquote-binding-space #'&&)
null
'automatic
(lambda (form1 form2 stx)
(syntax-parse (normalize-id form1)
[#f #'#f]
[(pat1 (idr1 ...) (sidr1 ...) (var1 ...))
(syntax-parse (normalize-id form2)
[#f #'#f]
[(pat2 idrs2 sidrs2 vars2)
#`((~and #,(norm-seq #'pat1 #'pat2) #,(norm-seq #'pat2 #'pat1))
(idr1 ... . idrs2)
(sidr1 ... . sidrs2)
(var1 ... . vars2))])]))
'left))
(define-unquote-binding-syntax \|\|
(unquote-binding-infix-operator
(in-unquote-binding-space #'\|\|)
null
'automatic
(lambda (form1 form2 stx)
(syntax-parse (normalize-id form1)
[#f #'#f]
[(pat1 idrs1 sidrs1 vars1)
(syntax-parse (normalize-id form2)
[#f #'#f]
[(pat2 idrs2 sidrs2 vars2)
#`((~or #,(norm-seq #'pat1 #'pat2)
#,(norm-seq #'pat2 #'pat1))
()
()
())])]))
'left))
(define-unquote-binding-syntax #%literal
(unquote-binding-transformer
(lambda (stxes)
(syntax-parse stxes
[(_ x . _)
(raise-syntax-error #f
(format "misplaced ~a within a syntax binding"
(if (keyword? (syntax-e #'x))
"keyword"
"literal"))
#'x)]))))
(define-unquote-binding-syntax #%block
(unquote-binding-transformer
(lambda (stxes)
(syntax-parse stxes
[(_ b)
(raise-syntax-error #f
"not allowed as a syntax binding by itself"
#'b)]))))
(define-unquote-binding-syntax bound_as
(unquote-binding-transformer
(lambda (stxes)
(cond
[(eq? (current-unquote-binding-kind) 'term)
(syntax-parse stxes
#:datum-literals (group)
[(_ space ... (_::block (group (_::quotes (group bound::name)))))
#:with (~var sp (:hier-name-seq in-name-root-space in-space-space name-path-op name-root-ref)) #'(space ...)
(define sn (syntax-local-value* (in-space-space #'sp.name) space-name-ref))
(unless sn
(raise-syntax-error #f
"not a space name"
stxes
#'sp.name))
(values #`((~var _ (:free=-in-space
(quote-syntax #,(if (space-name-symbol sn)
((make-interned-syntax-introducer (space-name-symbol sn)) #'bound.name 'add)
#'bound.name))
'#,(space-name-symbol sn)))
()
()
())
#'())])]
[else (values #'#f #'())]))))
(define-syntax-class (:free=-in-space bound-id space-sym)
#:datum-literals (group)
(pattern t::name
#:when (free-identifier=? bound-id (if space-sym
((make-interned-syntax-introducer space-sym) #'t.name 'add)
#'t.name))))
|
d5e21b191d0b3ee93fbb8e3720a2120383a45dac6fafeb4bab8feeb44a189ccd
|
keera-studios/haskell-titan
|
TestStreamChart.hs
|
import Graphics.UI.Gtk
import Graphics.UI.Gtk.StreamChart
main :: IO ()
main = do
_ <- initGUI
window <- windowNew
-- (w,h) <- widgetGetSize window
--
-- adjustX <- adjustmentNew 1 0 10000000 1 (fromIntegral w) (fromIntegral w)
-- adjustY <- adjustmentNew 1 0 10000 1 (fromIntegral h) (fromIntegral h)
-- viewport <- viewportNew adjustX adjustY
-- sw <- scrolledWindowNew (Just adjustX) (Just adjustY)
-- scrolledWindowSetPolicy sw PolicyAlways PolicyAlways
sw <- scrolledWindowNew Nothing Nothing
streamChart <- streamChartNew
widgetSetSizeRequest streamChart 10000 10000
-- viewport `onResize` (do (w,h) <- widgetGetSize window
-- adjustmentSetPageSize adjustX w
-- adjustmentSetPageSize adjustY h)
containerAdd viewport streamChart
-- containerAdd sw viewport
scrolledWindowAddWithViewport sw streamChart
containerAdd window sw
let myList = [ 'a', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd'
]
streamChartSetList streamChart myList
let defaultRenderSettingsF = \c ->
StreamChartStyle
{ renderFGColor = (0.5, 0.6, 0.7, 1.0)
, renderBGColor = if (c == 'a') then (0.9, 0.2, 0.1, 0.9) else (0.1, 0.9, 0.1, 0.9)
, renderDot = if (c /= 'b') then True else False
, renderLetter = if (c /= 'b') then Nothing else Just 'X'
}
streamChartSetStyle streamChart defaultRenderSettingsF
streamChartOnButtonEvent streamChart (\press p ->
if (p >= length myList || p < 0)
then putStrLn "Out of range"
else if press
then putStrLn $ "Pressed: " ++ [ (myList!!p) ]
else putStrLn $ "Released: " ++ [ (myList!!p) ])
window `onDestroy` mainQuit
windowSetDefaultSize window 640 480
widgetShowAll window
mainGUI
| null |
https://raw.githubusercontent.com/keera-studios/haskell-titan/958ddd2b468af00db46004a683c1c7aebe81526c/titan/examples/TestStreamChart.hs
|
haskell
|
(w,h) <- widgetGetSize window
adjustX <- adjustmentNew 1 0 10000000 1 (fromIntegral w) (fromIntegral w)
adjustY <- adjustmentNew 1 0 10000 1 (fromIntegral h) (fromIntegral h)
viewport <- viewportNew adjustX adjustY
sw <- scrolledWindowNew (Just adjustX) (Just adjustY)
scrolledWindowSetPolicy sw PolicyAlways PolicyAlways
viewport `onResize` (do (w,h) <- widgetGetSize window
adjustmentSetPageSize adjustX w
adjustmentSetPageSize adjustY h)
containerAdd sw viewport
|
import Graphics.UI.Gtk
import Graphics.UI.Gtk.StreamChart
main :: IO ()
main = do
_ <- initGUI
window <- windowNew
sw <- scrolledWindowNew Nothing Nothing
streamChart <- streamChartNew
widgetSetSizeRequest streamChart 10000 10000
containerAdd viewport streamChart
scrolledWindowAddWithViewport sw streamChart
containerAdd window sw
let myList = [ 'a', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b', 'c', 'b'
, 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd'
]
streamChartSetList streamChart myList
let defaultRenderSettingsF = \c ->
StreamChartStyle
{ renderFGColor = (0.5, 0.6, 0.7, 1.0)
, renderBGColor = if (c == 'a') then (0.9, 0.2, 0.1, 0.9) else (0.1, 0.9, 0.1, 0.9)
, renderDot = if (c /= 'b') then True else False
, renderLetter = if (c /= 'b') then Nothing else Just 'X'
}
streamChartSetStyle streamChart defaultRenderSettingsF
streamChartOnButtonEvent streamChart (\press p ->
if (p >= length myList || p < 0)
then putStrLn "Out of range"
else if press
then putStrLn $ "Pressed: " ++ [ (myList!!p) ]
else putStrLn $ "Released: " ++ [ (myList!!p) ])
window `onDestroy` mainQuit
windowSetDefaultSize window 640 480
widgetShowAll window
mainGUI
|
208aab1acd7de12dfd2446bec9b2692667cd3f25f0f6f82bd3ab057626c8a25c
|
clojure-interop/google-cloud-clients
|
SpeechSettings.clj
|
(ns com.google.cloud.speech.v1.SpeechSettings
"Settings class to configure an instance of SpeechClient.
The default instance has everything set to sensible defaults:
The default service address (speech.googleapis.com) and default port (443) are used.
Credentials are acquired automatically through Application Default Credentials.
Retries are configured for idempotent methods but not for non-idempotent methods.
The builder of this class is recursive, so contained classes are themselves builders. When
build() is called, the tree of builders is called to create the complete settings object. For
example, to set the total timeout of recognize to 30 seconds:
SpeechSettings.Builder speechSettingsBuilder =
SpeechSettings.newBuilder();
speechSettingsBuilder.recognizeSettings().getRetrySettings().toBuilder()
.setTotalTimeout(Duration.ofSeconds(30));
SpeechSettings speechSettings = speechSettingsBuilder.build();"
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.speech.v1 SpeechSettings]))
(defn *default-executor-provider-builder
"Returns a builder for the default ExecutorProvider for this service.
returns: `com.google.api.gax.core.InstantiatingExecutorProvider.Builder`"
(^com.google.api.gax.core.InstantiatingExecutorProvider.Builder []
(SpeechSettings/defaultExecutorProviderBuilder )))
(defn *get-default-endpoint
"Returns the default service endpoint.
returns: `java.lang.String`"
(^java.lang.String []
(SpeechSettings/getDefaultEndpoint )))
(defn *default-transport-channel-provider
"returns: `com.google.api.gax.rpc.TransportChannelProvider`"
(^com.google.api.gax.rpc.TransportChannelProvider []
(SpeechSettings/defaultTransportChannelProvider )))
(defn *new-builder
"Returns a new builder for this class.
client-context - `com.google.api.gax.rpc.ClientContext`
returns: `com.google.cloud.speech.v1.SpeechSettings$Builder`"
(^com.google.cloud.speech.v1.SpeechSettings$Builder [^com.google.api.gax.rpc.ClientContext client-context]
(SpeechSettings/newBuilder client-context))
(^com.google.cloud.speech.v1.SpeechSettings$Builder []
(SpeechSettings/newBuilder )))
(defn *default-credentials-provider-builder
"Returns a builder for the default credentials for this service.
returns: `com.google.api.gax.core.GoogleCredentialsProvider.Builder`"
(^com.google.api.gax.core.GoogleCredentialsProvider.Builder []
(SpeechSettings/defaultCredentialsProviderBuilder )))
(defn *create
"stub - `com.google.cloud.speech.v1.stub.SpeechStubSettings`
returns: `com.google.cloud.speech.v1.SpeechSettings`
throws: java.io.IOException"
(^com.google.cloud.speech.v1.SpeechSettings [^com.google.cloud.speech.v1.stub.SpeechStubSettings stub]
(SpeechSettings/create stub)))
(defn *default-grpc-transport-provider-builder
"Returns a builder for the default ChannelProvider for this service.
returns: `com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder`"
(^com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder []
(SpeechSettings/defaultGrpcTransportProviderBuilder )))
(defn *default-api-client-header-provider-builder
"returns: `(value="The surface for customizing headers is not stable yet and may change in the future.") com.google.api.gax.rpc.ApiClientHeaderProvider.Builder`"
([]
(SpeechSettings/defaultApiClientHeaderProviderBuilder )))
(defn *get-default-service-scopes
"Returns the default service scopes.
returns: `java.util.List<java.lang.String>`"
(^java.util.List []
(SpeechSettings/getDefaultServiceScopes )))
(defn recognize-settings
"Returns the object with the settings used for calls to recognize.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.speech.v1.RecognizeRequest,com.google.cloud.speech.v1.RecognizeResponse>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^SpeechSettings this]
(-> this (.recognizeSettings))))
(defn long-running-recognize-settings
"Returns the object with the settings used for calls to longRunningRecognize.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.speech.v1.LongRunningRecognizeRequest,com.google.longrunning.Operation>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^SpeechSettings this]
(-> this (.longRunningRecognizeSettings))))
(defn long-running-recognize-operation-settings
"Returns the object with the settings used for calls to longRunningRecognize.
returns: `(value="The surface for long-running operations is not stable yet and may change in the future.") com.google.api.gax.rpc.OperationCallSettings<com.google.cloud.speech.v1.LongRunningRecognizeRequest,com.google.cloud.speech.v1.LongRunningRecognizeResponse,com.google.cloud.speech.v1.LongRunningRecognizeMetadata>`"
([^SpeechSettings this]
(-> this (.longRunningRecognizeOperationSettings))))
(defn streaming-recognize-settings
"Returns the object with the settings used for calls to streamingRecognize.
returns: `com.google.api.gax.rpc.StreamingCallSettings<com.google.cloud.speech.v1.StreamingRecognizeRequest,com.google.cloud.speech.v1.StreamingRecognizeResponse>`"
(^com.google.api.gax.rpc.StreamingCallSettings [^SpeechSettings this]
(-> this (.streamingRecognizeSettings))))
(defn to-builder
"Returns a builder containing all the values of this settings class.
returns: `com.google.cloud.speech.v1.SpeechSettings$Builder`"
(^com.google.cloud.speech.v1.SpeechSettings$Builder [^SpeechSettings this]
(-> this (.toBuilder))))
| null |
https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.speech/src/com/google/cloud/speech/v1/SpeechSettings.clj
|
clojure
|
"
|
(ns com.google.cloud.speech.v1.SpeechSettings
"Settings class to configure an instance of SpeechClient.
The default instance has everything set to sensible defaults:
The default service address (speech.googleapis.com) and default port (443) are used.
Credentials are acquired automatically through Application Default Credentials.
Retries are configured for idempotent methods but not for non-idempotent methods.
The builder of this class is recursive, so contained classes are themselves builders. When
build() is called, the tree of builders is called to create the complete settings object. For
example, to set the total timeout of recognize to 30 seconds:
SpeechSettings.Builder speechSettingsBuilder =
speechSettingsBuilder.recognizeSettings().getRetrySettings().toBuilder()
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.speech.v1 SpeechSettings]))
(defn *default-executor-provider-builder
"Returns a builder for the default ExecutorProvider for this service.
returns: `com.google.api.gax.core.InstantiatingExecutorProvider.Builder`"
(^com.google.api.gax.core.InstantiatingExecutorProvider.Builder []
(SpeechSettings/defaultExecutorProviderBuilder )))
(defn *get-default-endpoint
"Returns the default service endpoint.
returns: `java.lang.String`"
(^java.lang.String []
(SpeechSettings/getDefaultEndpoint )))
(defn *default-transport-channel-provider
"returns: `com.google.api.gax.rpc.TransportChannelProvider`"
(^com.google.api.gax.rpc.TransportChannelProvider []
(SpeechSettings/defaultTransportChannelProvider )))
(defn *new-builder
"Returns a new builder for this class.
client-context - `com.google.api.gax.rpc.ClientContext`
returns: `com.google.cloud.speech.v1.SpeechSettings$Builder`"
(^com.google.cloud.speech.v1.SpeechSettings$Builder [^com.google.api.gax.rpc.ClientContext client-context]
(SpeechSettings/newBuilder client-context))
(^com.google.cloud.speech.v1.SpeechSettings$Builder []
(SpeechSettings/newBuilder )))
(defn *default-credentials-provider-builder
"Returns a builder for the default credentials for this service.
returns: `com.google.api.gax.core.GoogleCredentialsProvider.Builder`"
(^com.google.api.gax.core.GoogleCredentialsProvider.Builder []
(SpeechSettings/defaultCredentialsProviderBuilder )))
(defn *create
"stub - `com.google.cloud.speech.v1.stub.SpeechStubSettings`
returns: `com.google.cloud.speech.v1.SpeechSettings`
throws: java.io.IOException"
(^com.google.cloud.speech.v1.SpeechSettings [^com.google.cloud.speech.v1.stub.SpeechStubSettings stub]
(SpeechSettings/create stub)))
(defn *default-grpc-transport-provider-builder
"Returns a builder for the default ChannelProvider for this service.
returns: `com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder`"
(^com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder []
(SpeechSettings/defaultGrpcTransportProviderBuilder )))
(defn *default-api-client-header-provider-builder
"returns: `(value="The surface for customizing headers is not stable yet and may change in the future.") com.google.api.gax.rpc.ApiClientHeaderProvider.Builder`"
([]
(SpeechSettings/defaultApiClientHeaderProviderBuilder )))
(defn *get-default-service-scopes
"Returns the default service scopes.
returns: `java.util.List<java.lang.String>`"
(^java.util.List []
(SpeechSettings/getDefaultServiceScopes )))
(defn recognize-settings
"Returns the object with the settings used for calls to recognize.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.speech.v1.RecognizeRequest,com.google.cloud.speech.v1.RecognizeResponse>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^SpeechSettings this]
(-> this (.recognizeSettings))))
(defn long-running-recognize-settings
"Returns the object with the settings used for calls to longRunningRecognize.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.speech.v1.LongRunningRecognizeRequest,com.google.longrunning.Operation>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^SpeechSettings this]
(-> this (.longRunningRecognizeSettings))))
(defn long-running-recognize-operation-settings
"Returns the object with the settings used for calls to longRunningRecognize.
returns: `(value="The surface for long-running operations is not stable yet and may change in the future.") com.google.api.gax.rpc.OperationCallSettings<com.google.cloud.speech.v1.LongRunningRecognizeRequest,com.google.cloud.speech.v1.LongRunningRecognizeResponse,com.google.cloud.speech.v1.LongRunningRecognizeMetadata>`"
([^SpeechSettings this]
(-> this (.longRunningRecognizeOperationSettings))))
(defn streaming-recognize-settings
"Returns the object with the settings used for calls to streamingRecognize.
returns: `com.google.api.gax.rpc.StreamingCallSettings<com.google.cloud.speech.v1.StreamingRecognizeRequest,com.google.cloud.speech.v1.StreamingRecognizeResponse>`"
(^com.google.api.gax.rpc.StreamingCallSettings [^SpeechSettings this]
(-> this (.streamingRecognizeSettings))))
(defn to-builder
"Returns a builder containing all the values of this settings class.
returns: `com.google.cloud.speech.v1.SpeechSettings$Builder`"
(^com.google.cloud.speech.v1.SpeechSettings$Builder [^SpeechSettings this]
(-> this (.toBuilder))))
|
82da0c641e8895855468f47759d480465248bc644f8cbdcae5ab305ee1717d3c
|
ghc/ghc
|
Exit.hs
|
# LANGUAGE Trustworthy #
-----------------------------------------------------------------------------
-- |
-- Module : System.Exit
Copyright : ( c ) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- Exiting the program.
--
-----------------------------------------------------------------------------
module System.Exit
(
ExitCode(ExitSuccess,ExitFailure)
, exitWith
, exitFailure
, exitSuccess
, die
) where
import System.IO
import GHC.IO
import GHC.IO.Exception
-- ---------------------------------------------------------------------------
-- exitWith
| Computation ' exitWith ' @code@ throws ' ExitCode ' @code@.
Normally this terminates the program , returning @code@ to the
-- program's caller.
--
-- On program termination, the standard 'Handle's 'stdout' and
-- 'stderr' are flushed automatically; any other buffered 'Handle's
-- need to be flushed manually, otherwise the buffered data will be
-- discarded.
--
-- A program that fails in any other way is treated as if it had
-- called 'exitFailure'.
-- A program that terminates successfully without calling 'exitWith'
explicitly is treated as if it had called ' exitWith ' ' ExitSuccess ' .
--
-- As an 'ExitCode' is an 'Control.Exception.Exception', it can be
-- caught using the functions of "Control.Exception". This means that
-- cleanup computations added with 'Control.Exception.bracket' (from
-- "Control.Exception") are also executed properly on 'exitWith'.
--
Note : in GHC , ' exitWith ' should be called from the main program
-- thread in order to exit the process. When called from another
-- thread, 'exitWith' will throw an 'ExitCode' as normal, but the
-- exception will not cause the process itself to exit.
--
exitWith :: ExitCode -> IO a
exitWith ExitSuccess = throwIO ExitSuccess
exitWith code@(ExitFailure n)
| n /= 0 = throwIO code
| otherwise = ioError (IOError Nothing InvalidArgument "exitWith" "ExitFailure 0" Nothing Nothing)
-- | The computation 'exitFailure' is equivalent to
-- 'exitWith' @(@'ExitFailure' /exitfail/@)@,
-- where /exitfail/ is implementation-dependent.
exitFailure :: IO a
exitFailure = exitWith (ExitFailure 1)
-- | The computation 'exitSuccess' is equivalent to
' exitWith ' ' ExitSuccess ' , It terminates the program
-- successfully.
exitSuccess :: IO a
exitSuccess = exitWith ExitSuccess
-- | Write given error message to `stderr` and terminate with `exitFailure`.
--
@since 4.8.0.0
die :: String -> IO a
die err = hPutStrLn stderr err >> exitFailure
| null |
https://raw.githubusercontent.com/ghc/ghc/6fe2d778e9ad015f35c520724d7f222a015586ed/libraries/base/System/Exit.hs
|
haskell
|
---------------------------------------------------------------------------
|
Module : System.Exit
License : BSD-style (see the file libraries/base/LICENSE)
Maintainer :
Stability : provisional
Portability : portable
Exiting the program.
---------------------------------------------------------------------------
---------------------------------------------------------------------------
exitWith
program's caller.
On program termination, the standard 'Handle's 'stdout' and
'stderr' are flushed automatically; any other buffered 'Handle's
need to be flushed manually, otherwise the buffered data will be
discarded.
A program that fails in any other way is treated as if it had
called 'exitFailure'.
A program that terminates successfully without calling 'exitWith'
As an 'ExitCode' is an 'Control.Exception.Exception', it can be
caught using the functions of "Control.Exception". This means that
cleanup computations added with 'Control.Exception.bracket' (from
"Control.Exception") are also executed properly on 'exitWith'.
thread in order to exit the process. When called from another
thread, 'exitWith' will throw an 'ExitCode' as normal, but the
exception will not cause the process itself to exit.
| The computation 'exitFailure' is equivalent to
'exitWith' @(@'ExitFailure' /exitfail/@)@,
where /exitfail/ is implementation-dependent.
| The computation 'exitSuccess' is equivalent to
successfully.
| Write given error message to `stderr` and terminate with `exitFailure`.
|
# LANGUAGE Trustworthy #
Copyright : ( c ) The University of Glasgow 2001
module System.Exit
(
ExitCode(ExitSuccess,ExitFailure)
, exitWith
, exitFailure
, exitSuccess
, die
) where
import System.IO
import GHC.IO
import GHC.IO.Exception
| Computation ' exitWith ' @code@ throws ' ExitCode ' @code@.
Normally this terminates the program , returning @code@ to the
explicitly is treated as if it had called ' exitWith ' ' ExitSuccess ' .
Note : in GHC , ' exitWith ' should be called from the main program
exitWith :: ExitCode -> IO a
exitWith ExitSuccess = throwIO ExitSuccess
exitWith code@(ExitFailure n)
| n /= 0 = throwIO code
| otherwise = ioError (IOError Nothing InvalidArgument "exitWith" "ExitFailure 0" Nothing Nothing)
exitFailure :: IO a
exitFailure = exitWith (ExitFailure 1)
' exitWith ' ' ExitSuccess ' , It terminates the program
exitSuccess :: IO a
exitSuccess = exitWith ExitSuccess
@since 4.8.0.0
die :: String -> IO a
die err = hPutStrLn stderr err >> exitFailure
|
6902313fc76326c8e16b864a5677c62f91a3c5dbf663f9675a3ce38c82de048e
|
immoh/lein-nsorg
|
nsorg.clj
|
(ns leiningen.nsorg
"Organize ns forms in source files."
(:require [leiningen.core.main :as lein]
[nsorg.cli :as cli]
[nsorg.cli.terminal :as terminal]))
(defn ^:no-project-needed nsorg
"Leiningen plugin for organizing ns forms in source files.
Usage: lein nsorg [OPTIONS] [PATHS]
Clojure files are searched recursively from given paths. If no paths are given
and Leiningen is run inside project, project source and test paths are used.
Otherwise current workign directory is used.
Options:
-e, --replace Apply organizing suggestions to source files.
-i, --interactive Ask before applying suggestion (requires --replace).
-x, --exclude PATH Path to exclude from analysis."
[project & args]
(binding [terminal/*info-fn* lein/info
terminal/*error-fn* lein/warn]
(let [{:keys [success? summary]} (cli/check args {:default-paths (mapcat #(get project %)
[:source-paths :test-paths])})]
(if success?
(lein/info summary)
(lein/abort summary)))))
| null |
https://raw.githubusercontent.com/immoh/lein-nsorg/63d1c115451f6fe7883718bb3287a03d33d5d3f9/src/leiningen/nsorg.clj
|
clojure
|
(ns leiningen.nsorg
"Organize ns forms in source files."
(:require [leiningen.core.main :as lein]
[nsorg.cli :as cli]
[nsorg.cli.terminal :as terminal]))
(defn ^:no-project-needed nsorg
"Leiningen plugin for organizing ns forms in source files.
Usage: lein nsorg [OPTIONS] [PATHS]
Clojure files are searched recursively from given paths. If no paths are given
and Leiningen is run inside project, project source and test paths are used.
Otherwise current workign directory is used.
Options:
-e, --replace Apply organizing suggestions to source files.
-i, --interactive Ask before applying suggestion (requires --replace).
-x, --exclude PATH Path to exclude from analysis."
[project & args]
(binding [terminal/*info-fn* lein/info
terminal/*error-fn* lein/warn]
(let [{:keys [success? summary]} (cli/check args {:default-paths (mapcat #(get project %)
[:source-paths :test-paths])})]
(if success?
(lein/info summary)
(lein/abort summary)))))
|
|
b64f452692149d11f57143f0892f6ded9503a77c4ccecb43963800be514ef339
|
hopbit/sonic-pi-snippets
|
dp_fac_6_a.sps
|
# key: dp fac 6 a
# point_line: 0
# point_index: 0
# --
# DP FAC 6 A: Beat Factory Method implementation
class BeatFactoryMethod
def initialize(samples_path)
raise 'Use one of sublasses'
end
def createBeat(beat_name)
rais 'Unimplemented method'
end
end
# BPM 88-92
class ModeratoBeatFactory < BeatFactoryMethod
def initialize(samples_path)
@samples_path = samples_path
@tempo = 92
end
def createBeat(beat_name)
beat = nil
if beat_name == 'Impeach The President'
beat = ImpeachThePresident.new(@samples_path)
elsif beat_name == 'Funky Drummer'
beat = FunkyDrummer.new(@samples_path)
elsif beat_name == 'Big Beat'
beat = BigBeat.new(@samples_path)
elsif beat_name == 'House Beat'
beat = HouseBeat.new(@samples_path)
end
beat.bpm = @tempo
beat
end
end
# BPM around 120 – 138
class AllegroBeatFactory < BeatFactoryMethod
def initialize(samples_path)
@samples_path = samples_path
@tempo = 125
end
def createBeat(beat_name)
beat = nil
if beat_name == 'Impeach The President'
beat = ImpeachThePresident.new(@samples_path)
elsif beat_name == 'Funky Drummer'
beat = FunkyDrummer.new(@samples_path)
elsif beat_name == 'Big Beat'
beat = BigBeat.new(@samples_path)
elsif beat_name == 'House Beat'
beat = HouseBeat.new(@samples_path)
end
beat.bpm = @tempo
beat
end
end
| null |
https://raw.githubusercontent.com/hopbit/sonic-pi-snippets/2232854ac9587fc2f9f684ba04d7476e2dbaa288/dp/dp_fac_6_a.sps
|
scheme
|
# key: dp fac 6 a
# point_line: 0
# point_index: 0
# --
# DP FAC 6 A: Beat Factory Method implementation
class BeatFactoryMethod
def initialize(samples_path)
raise 'Use one of sublasses'
end
def createBeat(beat_name)
rais 'Unimplemented method'
end
end
# BPM 88-92
class ModeratoBeatFactory < BeatFactoryMethod
def initialize(samples_path)
@samples_path = samples_path
@tempo = 92
end
def createBeat(beat_name)
beat = nil
if beat_name == 'Impeach The President'
beat = ImpeachThePresident.new(@samples_path)
elsif beat_name == 'Funky Drummer'
beat = FunkyDrummer.new(@samples_path)
elsif beat_name == 'Big Beat'
beat = BigBeat.new(@samples_path)
elsif beat_name == 'House Beat'
beat = HouseBeat.new(@samples_path)
end
beat.bpm = @tempo
beat
end
end
# BPM around 120 – 138
class AllegroBeatFactory < BeatFactoryMethod
def initialize(samples_path)
@samples_path = samples_path
@tempo = 125
end
def createBeat(beat_name)
beat = nil
if beat_name == 'Impeach The President'
beat = ImpeachThePresident.new(@samples_path)
elsif beat_name == 'Funky Drummer'
beat = FunkyDrummer.new(@samples_path)
elsif beat_name == 'Big Beat'
beat = BigBeat.new(@samples_path)
elsif beat_name == 'House Beat'
beat = HouseBeat.new(@samples_path)
end
beat.bpm = @tempo
beat
end
end
|
|
51abdc996f137586b87043383c11e084308c9e5f2e5995a5c5d6e82dbeba46af
|
achirkin/vulkan
|
VK_NV_representative_fragment_test.hs
|
# OPTIONS_HADDOCK not - home #
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MagicHash #-}
# LANGUAGE PatternSynonyms #
{-# LANGUAGE Strict #-}
{-# LANGUAGE ViewPatterns #-}
module Graphics.Vulkan.Ext.VK_NV_representative_fragment_test
* Vulkan extension : @VK_NV_representative_fragment_test@
-- |
--
-- supported: @vulkan@
--
-- contact: @Kedarnath Thangudu @kthangudu@
--
author :
--
-- type: @device@
--
-- Extension number: @167@
module Graphics.Vulkan.Marshal, VkBlendFactor(..), VkBlendOp(..),
VkBlendOverlapEXT(..), AHardwareBuffer(), ANativeWindow(),
CAMetalLayer(), VkBool32(..), VkDeviceAddress(..),
VkDeviceSize(..), VkFlags(..), VkSampleMask(..),
pattern VK_COLORSPACE_SRGB_NONLINEAR_KHR,
VkColorComponentBitmask(..), VkColorSpaceKHR(..),
VkColorComponentFlagBits(), VkColorComponentFlags(),
VkCompareOp(..), VkCullModeBitmask(..), VkCullModeFlagBits(),
VkCullModeFlags(), VkAndroidSurfaceCreateFlagsKHR(..),
VkBufferViewCreateFlags(..),
VkBuildAccelerationStructureFlagsNV(..),
VkCommandPoolTrimFlags(..), VkCommandPoolTrimFlagsKHR(..),
VkDebugUtilsMessengerCallbackDataFlagsEXT(..),
VkDebugUtilsMessengerCreateFlagsEXT(..),
VkDescriptorBindingFlagsEXT(..), VkDescriptorPoolResetFlags(..),
VkDescriptorUpdateTemplateCreateFlags(..),
VkDescriptorUpdateTemplateCreateFlagsKHR(..),
VkDeviceCreateFlags(..), VkDirectFBSurfaceCreateFlagsEXT(..),
VkDisplayModeCreateFlagsKHR(..),
VkDisplaySurfaceCreateFlagsKHR(..), VkEventCreateFlags(..),
VkExternalFenceFeatureFlagsKHR(..),
VkExternalFenceHandleTypeFlagsKHR(..),
VkExternalMemoryFeatureFlagsKHR(..),
VkExternalMemoryHandleTypeFlagsKHR(..),
VkExternalSemaphoreFeatureFlagsKHR(..),
VkExternalSemaphoreHandleTypeFlagsKHR(..),
VkFenceImportFlagsKHR(..), VkGeometryFlagsNV(..),
VkGeometryInstanceFlagsNV(..), VkHeadlessSurfaceCreateFlagsEXT(..),
VkIOSSurfaceCreateFlagsMVK(..),
VkImagePipeSurfaceCreateFlagsFUCHSIA(..),
VkInstanceCreateFlags(..), VkMacOSSurfaceCreateFlagsMVK(..),
VkMemoryAllocateFlagsKHR(..), VkMemoryMapFlags(..),
VkMetalSurfaceCreateFlagsEXT(..), VkPeerMemoryFeatureFlagsKHR(..),
VkPipelineColorBlendStateCreateFlags(..),
VkPipelineCoverageModulationStateCreateFlagsNV(..),
VkPipelineCoverageReductionStateCreateFlagsNV(..),
VkPipelineCoverageToColorStateCreateFlagsNV(..),
VkPipelineDepthStencilStateCreateFlags(..),
VkPipelineDiscardRectangleStateCreateFlagsEXT(..),
VkPipelineDynamicStateCreateFlags(..),
VkPipelineInputAssemblyStateCreateFlags(..),
VkPipelineLayoutCreateFlags(..),
VkPipelineMultisampleStateCreateFlags(..),
VkPipelineRasterizationConservativeStateCreateFlagsEXT(..),
VkPipelineRasterizationDepthClipStateCreateFlagsEXT(..),
VkPipelineRasterizationStateCreateFlags(..),
VkPipelineRasterizationStateStreamCreateFlagsEXT(..),
VkPipelineTessellationStateCreateFlags(..),
VkPipelineVertexInputStateCreateFlags(..),
VkPipelineViewportStateCreateFlags(..),
VkPipelineViewportSwizzleStateCreateFlagsNV(..),
VkQueryPoolCreateFlags(..), VkResolveModeFlagsKHR(..),
VkSemaphoreCreateFlags(..), VkSemaphoreImportFlagsKHR(..),
VkSemaphoreWaitFlagsKHR(..),
VkStreamDescriptorSurfaceCreateFlagsGGP(..),
VkValidationCacheCreateFlagsEXT(..), VkViSurfaceCreateFlagsNN(..),
VkWaylandSurfaceCreateFlagsKHR(..),
VkWin32SurfaceCreateFlagsKHR(..), VkXcbSurfaceCreateFlagsKHR(..),
VkXlibSurfaceCreateFlagsKHR(..), VkDeviceCreateInfo,
VkDeviceDiagnosticsConfigBitmaskNV(..), VkDeviceEventTypeEXT(..),
VkDeviceGroupPresentModeBitmaskKHR(..), VkDeviceCreateFlagBits(..),
VkDeviceDiagnosticsConfigFlagBitsNV(),
VkDeviceDiagnosticsConfigFlagsNV(),
VkDeviceGroupPresentModeFlagBitsKHR(),
VkDeviceGroupPresentModeFlagsKHR(), VkDeviceQueueCreateBitmask(..),
VkDeviceQueueCreateFlagBits(), VkDeviceQueueCreateFlags(),
VkDeviceQueueCreateInfo, VkDynamicState(..), VkExtent2D,
VkFormat(..), VkFormatFeatureBitmask(..),
VkFormatFeatureFlagBits(), VkFormatFeatureFlags(), VkFrontFace(..),
VkGraphicsPipelineCreateInfo, VkLogicOp(..), VkOffset2D,
VkPhysicalDeviceFeatures, VkPhysicalDeviceFeatures2,
VkPhysicalDeviceRepresentativeFragmentTestFeaturesNV,
VkPipelineColorBlendAttachmentState,
VkPipelineColorBlendStateCreateInfo, VkPipelineBindPoint(..),
VkPipelineCacheHeaderVersion(..), VkPipelineCreateBitmask(..),
VkPipelineCreationFeedbackBitmaskEXT(..),
VkPipelineExecutableStatisticFormatKHR(..),
VkPipelineStageBitmask(..), VkPipelineCacheCreateBitmask(..),
VkPipelineCacheCreateFlagBits(), VkPipelineCacheCreateFlags(),
VkPipelineCompilerControlBitmaskAMD(..),
VkPipelineCompilerControlFlagBitsAMD(),
VkPipelineCompilerControlFlagsAMD(), VkPipelineCreateFlagBits(),
VkPipelineCreateFlags(), VkPipelineCreationFeedbackFlagBitsEXT(),
VkPipelineCreationFeedbackFlagsEXT(),
VkPipelineShaderStageCreateBitmask(..),
VkPipelineShaderStageCreateFlagBits(),
VkPipelineShaderStageCreateFlags(), VkPipelineStageFlagBits(),
VkPipelineStageFlags(), VkPipelineDepthStencilStateCreateInfo,
VkPipelineDynamicStateCreateInfo,
VkPipelineInputAssemblyStateCreateInfo,
VkPipelineMultisampleStateCreateInfo,
VkPipelineRasterizationStateCreateInfo,
VkPipelineRepresentativeFragmentTestStateCreateInfoNV,
VkPipelineShaderStageCreateInfo,
VkPipelineTessellationStateCreateInfo,
VkPipelineVertexInputStateCreateInfo,
VkPipelineViewportStateCreateInfo, VkPolygonMode(..),
VkPrimitiveTopology(..), VkRect2D, VkSampleCountBitmask(..),
VkSampleCountFlagBits(), VkSampleCountFlags(),
VkShaderFloatControlsIndependence(..), VkShaderInfoTypeAMD(..),
VkShaderStageBitmask(..), VkShaderCorePropertiesBitmaskAMD(..),
VkShaderCorePropertiesFlagBitsAMD(),
VkShaderCorePropertiesFlagsAMD(),
VkShaderFloatControlsIndependenceKHR(..),
VkShaderModuleCreateBitmask(..), VkShaderModuleCreateFlagBits(),
VkShaderModuleCreateFlags(), VkShaderStageFlagBits(),
VkShaderStageFlags(), VkSpecializationInfo,
VkSpecializationMapEntry, VkStencilFaceBitmask(..),
VkStencilOp(..), VkStencilFaceFlagBits(), VkStencilFaceFlags(),
VkStencilOpState, VkStructureType(..),
VkVertexInputAttributeDescription, VkVertexInputBindingDescription,
VkVertexInputRate(..), VkViewport,
-- > #include "vk_platform.h"
VK_NV_REPRESENTATIVE_FRAGMENT_TEST_SPEC_VERSION,
pattern VK_NV_REPRESENTATIVE_FRAGMENT_TEST_SPEC_VERSION,
VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME,
pattern VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME,
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_REPRESENTATIVE_FRAGMENT_TEST_FEATURES_NV,
pattern VK_STRUCTURE_TYPE_PIPELINE_REPRESENTATIVE_FRAGMENT_TEST_STATE_CREATE_INFO_NV)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
import Graphics.Vulkan.Types.BaseTypes
import Graphics.Vulkan.Types.Bitmasks
import Graphics.Vulkan.Types.Enum.Blend
import Graphics.Vulkan.Types.Enum.Color
import Graphics.Vulkan.Types.Enum.CompareOp
import Graphics.Vulkan.Types.Enum.CullModeFlags
import Graphics.Vulkan.Types.Enum.Device
import Graphics.Vulkan.Types.Enum.DynamicState
import Graphics.Vulkan.Types.Enum.Format
import Graphics.Vulkan.Types.Enum.FrontFace
import Graphics.Vulkan.Types.Enum.LogicOp
import Graphics.Vulkan.Types.Enum.Pipeline
import Graphics.Vulkan.Types.Enum.PolygonMode
import Graphics.Vulkan.Types.Enum.PrimitiveTopology
import Graphics.Vulkan.Types.Enum.SampleCountFlags
import Graphics.Vulkan.Types.Enum.Shader
import Graphics.Vulkan.Types.Enum.Stencil
import Graphics.Vulkan.Types.Enum.StructureType
import Graphics.Vulkan.Types.Enum.VertexInputRate
import Graphics.Vulkan.Types.Struct.Device (VkDeviceCreateInfo, VkDeviceQueueCreateInfo)
import Graphics.Vulkan.Types.Struct.Extent (VkExtent2D)
import Graphics.Vulkan.Types.Struct.Offset (VkOffset2D)
import Graphics.Vulkan.Types.Struct.PhysicalDevice (VkPhysicalDeviceFeatures2,
VkPhysicalDeviceRepresentativeFragmentTestFeaturesNV)
import Graphics.Vulkan.Types.Struct.PhysicalDeviceFeatures (VkPhysicalDeviceFeatures)
import Graphics.Vulkan.Types.Struct.Pipeline (VkGraphicsPipelineCreateInfo,
VkPipelineColorBlendAttachmentState,
VkPipelineColorBlendStateCreateInfo,
VkPipelineDepthStencilStateCreateInfo,
VkPipelineDynamicStateCreateInfo,
VkPipelineInputAssemblyStateCreateInfo,
VkPipelineMultisampleStateCreateInfo,
VkPipelineRasterizationStateCreateInfo,
VkPipelineRepresentativeFragmentTestStateCreateInfoNV,
VkPipelineShaderStageCreateInfo,
VkPipelineTessellationStateCreateInfo,
VkPipelineVertexInputStateCreateInfo,
VkPipelineViewportStateCreateInfo)
import Graphics.Vulkan.Types.Struct.Rect (VkRect2D)
import Graphics.Vulkan.Types.Struct.Specialization (VkSpecializationInfo,
VkSpecializationMapEntry)
import Graphics.Vulkan.Types.Struct.StencilOpState (VkStencilOpState)
import Graphics.Vulkan.Types.Struct.VertexInput (VkVertexInputAttributeDescription,
VkVertexInputBindingDescription)
import Graphics.Vulkan.Types.Struct.Viewport (VkViewport)
pattern VK_NV_REPRESENTATIVE_FRAGMENT_TEST_SPEC_VERSION ::
(Num a, Eq a) => a
pattern VK_NV_REPRESENTATIVE_FRAGMENT_TEST_SPEC_VERSION = 2
type VK_NV_REPRESENTATIVE_FRAGMENT_TEST_SPEC_VERSION = 2
pattern VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME ::
CString
pattern VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME <-
(is_VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME -> True)
where
VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME
= _VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME
# INLINE _ VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME #
_VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME :: CString
_VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME
= Ptr "VK_NV_representative_fragment_test\NUL"#
# INLINE is_VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME #
is_VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME ::
CString -> Bool
is_VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME
= (EQ ==) .
cmpCStrings _VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME
type VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME =
"VK_NV_representative_fragment_test"
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_REPRESENTATIVE_FRAGMENT_TEST_FEATURES_NV
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_REPRESENTATIVE_FRAGMENT_TEST_FEATURES_NV
= VkStructureType 1000166000
pattern VK_STRUCTURE_TYPE_PIPELINE_REPRESENTATIVE_FRAGMENT_TEST_STATE_CREATE_INFO_NV
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PIPELINE_REPRESENTATIVE_FRAGMENT_TEST_STATE_CREATE_INFO_NV
= VkStructureType 1000166001
| null |
https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/vulkan-api/src-gen/Graphics/Vulkan/Ext/VK_NV_representative_fragment_test.hs
|
haskell
|
# LANGUAGE DataKinds #
# LANGUAGE MagicHash #
# LANGUAGE Strict #
# LANGUAGE ViewPatterns #
|
supported: @vulkan@
contact: @Kedarnath Thangudu @kthangudu@
type: @device@
Extension number: @167@
> #include "vk_platform.h"
|
# OPTIONS_HADDOCK not - home #
# LANGUAGE PatternSynonyms #
module Graphics.Vulkan.Ext.VK_NV_representative_fragment_test
* Vulkan extension : @VK_NV_representative_fragment_test@
author :
module Graphics.Vulkan.Marshal, VkBlendFactor(..), VkBlendOp(..),
VkBlendOverlapEXT(..), AHardwareBuffer(), ANativeWindow(),
CAMetalLayer(), VkBool32(..), VkDeviceAddress(..),
VkDeviceSize(..), VkFlags(..), VkSampleMask(..),
pattern VK_COLORSPACE_SRGB_NONLINEAR_KHR,
VkColorComponentBitmask(..), VkColorSpaceKHR(..),
VkColorComponentFlagBits(), VkColorComponentFlags(),
VkCompareOp(..), VkCullModeBitmask(..), VkCullModeFlagBits(),
VkCullModeFlags(), VkAndroidSurfaceCreateFlagsKHR(..),
VkBufferViewCreateFlags(..),
VkBuildAccelerationStructureFlagsNV(..),
VkCommandPoolTrimFlags(..), VkCommandPoolTrimFlagsKHR(..),
VkDebugUtilsMessengerCallbackDataFlagsEXT(..),
VkDebugUtilsMessengerCreateFlagsEXT(..),
VkDescriptorBindingFlagsEXT(..), VkDescriptorPoolResetFlags(..),
VkDescriptorUpdateTemplateCreateFlags(..),
VkDescriptorUpdateTemplateCreateFlagsKHR(..),
VkDeviceCreateFlags(..), VkDirectFBSurfaceCreateFlagsEXT(..),
VkDisplayModeCreateFlagsKHR(..),
VkDisplaySurfaceCreateFlagsKHR(..), VkEventCreateFlags(..),
VkExternalFenceFeatureFlagsKHR(..),
VkExternalFenceHandleTypeFlagsKHR(..),
VkExternalMemoryFeatureFlagsKHR(..),
VkExternalMemoryHandleTypeFlagsKHR(..),
VkExternalSemaphoreFeatureFlagsKHR(..),
VkExternalSemaphoreHandleTypeFlagsKHR(..),
VkFenceImportFlagsKHR(..), VkGeometryFlagsNV(..),
VkGeometryInstanceFlagsNV(..), VkHeadlessSurfaceCreateFlagsEXT(..),
VkIOSSurfaceCreateFlagsMVK(..),
VkImagePipeSurfaceCreateFlagsFUCHSIA(..),
VkInstanceCreateFlags(..), VkMacOSSurfaceCreateFlagsMVK(..),
VkMemoryAllocateFlagsKHR(..), VkMemoryMapFlags(..),
VkMetalSurfaceCreateFlagsEXT(..), VkPeerMemoryFeatureFlagsKHR(..),
VkPipelineColorBlendStateCreateFlags(..),
VkPipelineCoverageModulationStateCreateFlagsNV(..),
VkPipelineCoverageReductionStateCreateFlagsNV(..),
VkPipelineCoverageToColorStateCreateFlagsNV(..),
VkPipelineDepthStencilStateCreateFlags(..),
VkPipelineDiscardRectangleStateCreateFlagsEXT(..),
VkPipelineDynamicStateCreateFlags(..),
VkPipelineInputAssemblyStateCreateFlags(..),
VkPipelineLayoutCreateFlags(..),
VkPipelineMultisampleStateCreateFlags(..),
VkPipelineRasterizationConservativeStateCreateFlagsEXT(..),
VkPipelineRasterizationDepthClipStateCreateFlagsEXT(..),
VkPipelineRasterizationStateCreateFlags(..),
VkPipelineRasterizationStateStreamCreateFlagsEXT(..),
VkPipelineTessellationStateCreateFlags(..),
VkPipelineVertexInputStateCreateFlags(..),
VkPipelineViewportStateCreateFlags(..),
VkPipelineViewportSwizzleStateCreateFlagsNV(..),
VkQueryPoolCreateFlags(..), VkResolveModeFlagsKHR(..),
VkSemaphoreCreateFlags(..), VkSemaphoreImportFlagsKHR(..),
VkSemaphoreWaitFlagsKHR(..),
VkStreamDescriptorSurfaceCreateFlagsGGP(..),
VkValidationCacheCreateFlagsEXT(..), VkViSurfaceCreateFlagsNN(..),
VkWaylandSurfaceCreateFlagsKHR(..),
VkWin32SurfaceCreateFlagsKHR(..), VkXcbSurfaceCreateFlagsKHR(..),
VkXlibSurfaceCreateFlagsKHR(..), VkDeviceCreateInfo,
VkDeviceDiagnosticsConfigBitmaskNV(..), VkDeviceEventTypeEXT(..),
VkDeviceGroupPresentModeBitmaskKHR(..), VkDeviceCreateFlagBits(..),
VkDeviceDiagnosticsConfigFlagBitsNV(),
VkDeviceDiagnosticsConfigFlagsNV(),
VkDeviceGroupPresentModeFlagBitsKHR(),
VkDeviceGroupPresentModeFlagsKHR(), VkDeviceQueueCreateBitmask(..),
VkDeviceQueueCreateFlagBits(), VkDeviceQueueCreateFlags(),
VkDeviceQueueCreateInfo, VkDynamicState(..), VkExtent2D,
VkFormat(..), VkFormatFeatureBitmask(..),
VkFormatFeatureFlagBits(), VkFormatFeatureFlags(), VkFrontFace(..),
VkGraphicsPipelineCreateInfo, VkLogicOp(..), VkOffset2D,
VkPhysicalDeviceFeatures, VkPhysicalDeviceFeatures2,
VkPhysicalDeviceRepresentativeFragmentTestFeaturesNV,
VkPipelineColorBlendAttachmentState,
VkPipelineColorBlendStateCreateInfo, VkPipelineBindPoint(..),
VkPipelineCacheHeaderVersion(..), VkPipelineCreateBitmask(..),
VkPipelineCreationFeedbackBitmaskEXT(..),
VkPipelineExecutableStatisticFormatKHR(..),
VkPipelineStageBitmask(..), VkPipelineCacheCreateBitmask(..),
VkPipelineCacheCreateFlagBits(), VkPipelineCacheCreateFlags(),
VkPipelineCompilerControlBitmaskAMD(..),
VkPipelineCompilerControlFlagBitsAMD(),
VkPipelineCompilerControlFlagsAMD(), VkPipelineCreateFlagBits(),
VkPipelineCreateFlags(), VkPipelineCreationFeedbackFlagBitsEXT(),
VkPipelineCreationFeedbackFlagsEXT(),
VkPipelineShaderStageCreateBitmask(..),
VkPipelineShaderStageCreateFlagBits(),
VkPipelineShaderStageCreateFlags(), VkPipelineStageFlagBits(),
VkPipelineStageFlags(), VkPipelineDepthStencilStateCreateInfo,
VkPipelineDynamicStateCreateInfo,
VkPipelineInputAssemblyStateCreateInfo,
VkPipelineMultisampleStateCreateInfo,
VkPipelineRasterizationStateCreateInfo,
VkPipelineRepresentativeFragmentTestStateCreateInfoNV,
VkPipelineShaderStageCreateInfo,
VkPipelineTessellationStateCreateInfo,
VkPipelineVertexInputStateCreateInfo,
VkPipelineViewportStateCreateInfo, VkPolygonMode(..),
VkPrimitiveTopology(..), VkRect2D, VkSampleCountBitmask(..),
VkSampleCountFlagBits(), VkSampleCountFlags(),
VkShaderFloatControlsIndependence(..), VkShaderInfoTypeAMD(..),
VkShaderStageBitmask(..), VkShaderCorePropertiesBitmaskAMD(..),
VkShaderCorePropertiesFlagBitsAMD(),
VkShaderCorePropertiesFlagsAMD(),
VkShaderFloatControlsIndependenceKHR(..),
VkShaderModuleCreateBitmask(..), VkShaderModuleCreateFlagBits(),
VkShaderModuleCreateFlags(), VkShaderStageFlagBits(),
VkShaderStageFlags(), VkSpecializationInfo,
VkSpecializationMapEntry, VkStencilFaceBitmask(..),
VkStencilOp(..), VkStencilFaceFlagBits(), VkStencilFaceFlags(),
VkStencilOpState, VkStructureType(..),
VkVertexInputAttributeDescription, VkVertexInputBindingDescription,
VkVertexInputRate(..), VkViewport,
VK_NV_REPRESENTATIVE_FRAGMENT_TEST_SPEC_VERSION,
pattern VK_NV_REPRESENTATIVE_FRAGMENT_TEST_SPEC_VERSION,
VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME,
pattern VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME,
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_REPRESENTATIVE_FRAGMENT_TEST_FEATURES_NV,
pattern VK_STRUCTURE_TYPE_PIPELINE_REPRESENTATIVE_FRAGMENT_TEST_STATE_CREATE_INFO_NV)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
import Graphics.Vulkan.Types.BaseTypes
import Graphics.Vulkan.Types.Bitmasks
import Graphics.Vulkan.Types.Enum.Blend
import Graphics.Vulkan.Types.Enum.Color
import Graphics.Vulkan.Types.Enum.CompareOp
import Graphics.Vulkan.Types.Enum.CullModeFlags
import Graphics.Vulkan.Types.Enum.Device
import Graphics.Vulkan.Types.Enum.DynamicState
import Graphics.Vulkan.Types.Enum.Format
import Graphics.Vulkan.Types.Enum.FrontFace
import Graphics.Vulkan.Types.Enum.LogicOp
import Graphics.Vulkan.Types.Enum.Pipeline
import Graphics.Vulkan.Types.Enum.PolygonMode
import Graphics.Vulkan.Types.Enum.PrimitiveTopology
import Graphics.Vulkan.Types.Enum.SampleCountFlags
import Graphics.Vulkan.Types.Enum.Shader
import Graphics.Vulkan.Types.Enum.Stencil
import Graphics.Vulkan.Types.Enum.StructureType
import Graphics.Vulkan.Types.Enum.VertexInputRate
import Graphics.Vulkan.Types.Struct.Device (VkDeviceCreateInfo, VkDeviceQueueCreateInfo)
import Graphics.Vulkan.Types.Struct.Extent (VkExtent2D)
import Graphics.Vulkan.Types.Struct.Offset (VkOffset2D)
import Graphics.Vulkan.Types.Struct.PhysicalDevice (VkPhysicalDeviceFeatures2,
VkPhysicalDeviceRepresentativeFragmentTestFeaturesNV)
import Graphics.Vulkan.Types.Struct.PhysicalDeviceFeatures (VkPhysicalDeviceFeatures)
import Graphics.Vulkan.Types.Struct.Pipeline (VkGraphicsPipelineCreateInfo,
VkPipelineColorBlendAttachmentState,
VkPipelineColorBlendStateCreateInfo,
VkPipelineDepthStencilStateCreateInfo,
VkPipelineDynamicStateCreateInfo,
VkPipelineInputAssemblyStateCreateInfo,
VkPipelineMultisampleStateCreateInfo,
VkPipelineRasterizationStateCreateInfo,
VkPipelineRepresentativeFragmentTestStateCreateInfoNV,
VkPipelineShaderStageCreateInfo,
VkPipelineTessellationStateCreateInfo,
VkPipelineVertexInputStateCreateInfo,
VkPipelineViewportStateCreateInfo)
import Graphics.Vulkan.Types.Struct.Rect (VkRect2D)
import Graphics.Vulkan.Types.Struct.Specialization (VkSpecializationInfo,
VkSpecializationMapEntry)
import Graphics.Vulkan.Types.Struct.StencilOpState (VkStencilOpState)
import Graphics.Vulkan.Types.Struct.VertexInput (VkVertexInputAttributeDescription,
VkVertexInputBindingDescription)
import Graphics.Vulkan.Types.Struct.Viewport (VkViewport)
pattern VK_NV_REPRESENTATIVE_FRAGMENT_TEST_SPEC_VERSION ::
(Num a, Eq a) => a
pattern VK_NV_REPRESENTATIVE_FRAGMENT_TEST_SPEC_VERSION = 2
type VK_NV_REPRESENTATIVE_FRAGMENT_TEST_SPEC_VERSION = 2
pattern VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME ::
CString
pattern VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME <-
(is_VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME -> True)
where
VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME
= _VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME
# INLINE _ VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME #
_VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME :: CString
_VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME
= Ptr "VK_NV_representative_fragment_test\NUL"#
# INLINE is_VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME #
is_VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME ::
CString -> Bool
is_VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME
= (EQ ==) .
cmpCStrings _VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME
type VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME =
"VK_NV_representative_fragment_test"
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_REPRESENTATIVE_FRAGMENT_TEST_FEATURES_NV
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_REPRESENTATIVE_FRAGMENT_TEST_FEATURES_NV
= VkStructureType 1000166000
pattern VK_STRUCTURE_TYPE_PIPELINE_REPRESENTATIVE_FRAGMENT_TEST_STATE_CREATE_INFO_NV
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PIPELINE_REPRESENTATIVE_FRAGMENT_TEST_STATE_CREATE_INFO_NV
= VkStructureType 1000166001
|
e674c0bc19b4af2f18774cfa4ebc0b10dd050b48bcb82d4df1611b8647f6c15a
|
dbuenzli/trel
|
mkv_test.ml
|
---------------------------------------------------------------------------
Copyright ( c ) 2017 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2017 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
let assert_vals ?limit d q vals =
let q = Mkv.(query d @@ reifier q value_get) in
assert (Mkv.(seq_to_list ?limit @@ run q) = vals)
let assert_find_vals ?limit d q vals =
let q = Mkv.(query d @@ reifier q value_find) in
assert (Mkv.(seq_to_list ?limit @@ run q) = vals)
let assert_2vals ?limit d0 d1 q vals =
let reify x y = Mkv.(value_get x, value_get y) in
let q = Mkv.(query d1 @@ query d0 @@ reifier q reify) in
assert (Mkv.(seq_to_list ?limit @@ run q) = vals)
let dint = Mkv.dom ~equal:(( = ) : int -> int -> bool)
let int = Mkv.const dint
let test_fair_disj () =
let rec fivel x = Mkv.(x = int 5 || delay @@ lazy (fivel x)) in
let rec fiver x = Mkv.(delay @@ lazy (fiver x) || x = int 5) in
assert_vals ~limit:3 dint fivel [5;5;5];
assert_vals ~limit:3 dint fiver [5;5;5];
()
let test_unfair_conj () =
let rec faill x = Mkv.(fail && delay @@ lazy (faill x)) in
assert_find_vals ~limit:3 dint faill [];
let rec failr x = @@ lazy ( failr x ) & & fail ) in
assert_find_vals ~limit:3 dint failr [ ] ;
let rec failr x = Mkv.(delay @@ lazy (failr x) && fail) in
assert_find_vals ~limit:3 dint failr []; *)
()
let listo d dl =
let empty = Mkv.(const dl []) in
let cons x xs =
Mkv.(pure (fun x xs -> x :: xs) |> app x |> app xs |> ret dl)
in
let list l = List.fold_right (fun x xs -> cons (Mkv.const d x) xs) l empty in
let rec appendo l0 l1 l =
let open Mkv in
(l0 = empty && l1 = l) ||
(fresh d @@ fun x -> fresh dl @@ fun xs -> fresh dl @@ fun tl ->
cons x xs = l0 &&
cons x tl = l &&
delay @@ lazy (appendo xs l1 tl))
in
let rec revo l r =
let open Mkv in
(l = empty && r = empty) ||
(fresh d @@ fun x -> fresh dl @@ fun xs -> fresh dl @@ fun rt ->
cons x xs = l &&
appendo rt (cons x empty) r &&
delay @@ lazy (revo xs rt))
in
empty, cons, list, appendo, revo
let dilist = Mkv.dom ~equal:( = )
let iempty, icons, ilist, iappendo, irevo = listo dint dilist
let test_match () =
let m4tch x xs = Mkv.(icons x xs = ilist [1;2;3]) in
assert_2vals dint dilist m4tch [(1, [2;3])];
()
let test_appendo () =
assert_vals dilist
(fun l -> iappendo (ilist [1;2]) (ilist [3;4]) l) [[1;2;3;4]];
assert_vals dilist
(fun l -> iappendo l (ilist [3;4]) (ilist [1;2;3;4])) [[1;2]];
assert_vals dilist
(fun l -> iappendo (ilist [1;2]) l (ilist [1;2;3;4])) [[3;4]];
()
let test_pre_suf () =
let pre l pre = Mkv.(fresh dilist @@ fun suf -> iappendo pre suf l) in
let suf l suf = Mkv.(fresh dilist @@ fun pre -> iappendo pre suf l) in
let pre_suf l pre suf = iappendo pre suf l in
let l = ilist [1;2;3;4] in
assert_vals dilist (pre l) [[]; [1]; [1;2]; [1;2;3]; [1;2;3;4]];
assert_vals dilist (suf l) [[1;2;3;4]; [2;3;4]; [3;4]; [4]; []];
assert_2vals dilist dilist (pre_suf l)
[([], [1;2;3;4]);
([1], [2;3;4]);
([1;2], [3;4]);
([1;2;3], [4]);
([1;2;3;4], [])];
()
let test_revo () =
assert_vals ~limit:1 dilist (fun r -> irevo (ilist [1;2;3]) r) [[3;2;1]];
assert_vals ~limit:1 dilist (fun r -> irevo r (ilist [1;2;3])) [[3;2;1]];
()
let test () =
test_fair_disj ();
test_unfair_conj ();
test_match ();
test_appendo ();
test_pre_suf ();
test_revo ();
print_endline "All Mkv tests succeeded!";
()
let () = test ()
---------------------------------------------------------------------------
Copyright ( c ) 2017
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2017 Daniel C. Bünzli
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| null |
https://raw.githubusercontent.com/dbuenzli/trel/990084e92fe44a0f1ffa2d8a0ebc20731ab9eafc/test/mkv_test.ml
|
ocaml
|
---------------------------------------------------------------------------
Copyright ( c ) 2017 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2017 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
let assert_vals ?limit d q vals =
let q = Mkv.(query d @@ reifier q value_get) in
assert (Mkv.(seq_to_list ?limit @@ run q) = vals)
let assert_find_vals ?limit d q vals =
let q = Mkv.(query d @@ reifier q value_find) in
assert (Mkv.(seq_to_list ?limit @@ run q) = vals)
let assert_2vals ?limit d0 d1 q vals =
let reify x y = Mkv.(value_get x, value_get y) in
let q = Mkv.(query d1 @@ query d0 @@ reifier q reify) in
assert (Mkv.(seq_to_list ?limit @@ run q) = vals)
let dint = Mkv.dom ~equal:(( = ) : int -> int -> bool)
let int = Mkv.const dint
let test_fair_disj () =
let rec fivel x = Mkv.(x = int 5 || delay @@ lazy (fivel x)) in
let rec fiver x = Mkv.(delay @@ lazy (fiver x) || x = int 5) in
assert_vals ~limit:3 dint fivel [5;5;5];
assert_vals ~limit:3 dint fiver [5;5;5];
()
let test_unfair_conj () =
let rec faill x = Mkv.(fail && delay @@ lazy (faill x)) in
assert_find_vals ~limit:3 dint faill [];
let rec failr x = @@ lazy ( failr x ) & & fail ) in
assert_find_vals ~limit:3 dint failr [ ] ;
let rec failr x = Mkv.(delay @@ lazy (failr x) && fail) in
assert_find_vals ~limit:3 dint failr []; *)
()
let listo d dl =
let empty = Mkv.(const dl []) in
let cons x xs =
Mkv.(pure (fun x xs -> x :: xs) |> app x |> app xs |> ret dl)
in
let list l = List.fold_right (fun x xs -> cons (Mkv.const d x) xs) l empty in
let rec appendo l0 l1 l =
let open Mkv in
(l0 = empty && l1 = l) ||
(fresh d @@ fun x -> fresh dl @@ fun xs -> fresh dl @@ fun tl ->
cons x xs = l0 &&
cons x tl = l &&
delay @@ lazy (appendo xs l1 tl))
in
let rec revo l r =
let open Mkv in
(l = empty && r = empty) ||
(fresh d @@ fun x -> fresh dl @@ fun xs -> fresh dl @@ fun rt ->
cons x xs = l &&
appendo rt (cons x empty) r &&
delay @@ lazy (revo xs rt))
in
empty, cons, list, appendo, revo
let dilist = Mkv.dom ~equal:( = )
let iempty, icons, ilist, iappendo, irevo = listo dint dilist
let test_match () =
let m4tch x xs = Mkv.(icons x xs = ilist [1;2;3]) in
assert_2vals dint dilist m4tch [(1, [2;3])];
()
let test_appendo () =
assert_vals dilist
(fun l -> iappendo (ilist [1;2]) (ilist [3;4]) l) [[1;2;3;4]];
assert_vals dilist
(fun l -> iappendo l (ilist [3;4]) (ilist [1;2;3;4])) [[1;2]];
assert_vals dilist
(fun l -> iappendo (ilist [1;2]) l (ilist [1;2;3;4])) [[3;4]];
()
let test_pre_suf () =
let pre l pre = Mkv.(fresh dilist @@ fun suf -> iappendo pre suf l) in
let suf l suf = Mkv.(fresh dilist @@ fun pre -> iappendo pre suf l) in
let pre_suf l pre suf = iappendo pre suf l in
let l = ilist [1;2;3;4] in
assert_vals dilist (pre l) [[]; [1]; [1;2]; [1;2;3]; [1;2;3;4]];
assert_vals dilist (suf l) [[1;2;3;4]; [2;3;4]; [3;4]; [4]; []];
assert_2vals dilist dilist (pre_suf l)
[([], [1;2;3;4]);
([1], [2;3;4]);
([1;2], [3;4]);
([1;2;3], [4]);
([1;2;3;4], [])];
()
let test_revo () =
assert_vals ~limit:1 dilist (fun r -> irevo (ilist [1;2;3]) r) [[3;2;1]];
assert_vals ~limit:1 dilist (fun r -> irevo r (ilist [1;2;3])) [[3;2;1]];
()
let test () =
test_fair_disj ();
test_unfair_conj ();
test_match ();
test_appendo ();
test_pre_suf ();
test_revo ();
print_endline "All Mkv tests succeeded!";
()
let () = test ()
---------------------------------------------------------------------------
Copyright ( c ) 2017
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2017 Daniel C. Bünzli
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
|
|
b2d1741cbb6aaa2d479026b7b8fab27af57a239eb3777edadf78124c5ec9d99a
|
juxt/roll
|
service_security.cljs
|
(ns roll.modules.service-security
(:require [roll.utils :refer [resolve-path ->json $ ->snake]]))
(defn- aws-security-groups
"Generate a security group for each service."
[{:keys [environment] :as config}]
(into {} (for [[service-k {:keys [port]}] (:services config)
:let [environment (str environment "-" (name service-k))]]
[service-k
{:name environment
:description (str "Allow access to " environment" application")
:vpc-id ($ [:local :vpc-id])
:ingress (remove nil?
[{:from-port 22
:to-port 22
:protocol "tcp"
:cidr-blocks ["0.0.0.0/0"]}
(when port
{:from-port port
:to-port port
:protocol "tcp"
:cidr-blocks ["0.0.0.0/0"]})])
:egress [{:from-port 0
:to-port 65535
:protocol "tcp"
:cidr-blocks ["0.0.0.0/0"]}]
:tags {:name environment}}])))
(def default-iam-policy
{:Version "2012-10-17"
:Statement [{:Sid ""
:Action "sts:AssumeRole"
:Effect "Allow"
:Principal {:Service "ec2.amazonaws.com"}}]})
(defn- aws-iam-roles
"Generate an IAM role for each service."
[{:keys [environment] :as config}]
(into {} (for [service (keys (:services config))
:let [environment (str environment "-" (name service))]]
[service
{:name (->snake (str environment"_role"))
:assume-role-policy (->json default-iam-policy)}])))
(defn- aws-iam-instance-profile
[{:keys [environment] :as config}]
(into {} (for [service (keys (:services config))
:let [environment (str environment "-" (name service))]]
[service
{:name environment
:role ($ [:aws-iam-role service :name])}])))
(defn- aws-iam-role-policies
"Every service we run needs access to S3 to fetch releases, plus
additional policies as described."
[{:keys [releases-bucket environment services]}]
(into {} (for [[service {:keys [policies]}] services]
[service
{:name (str environment "-" (name service))
:role ($ [:aws-iam-role service :id])
:policy (->json
{:Statement
(concat [{:Effect "Allow"
:Action ["s3:GetObject"]
:Resource [(str "arn:aws:s3:::" releases-bucket "/*")]}]
policies)})}])))
(defn generate [{:keys [environment] :as config}]
{:resource
{:aws-security-group (aws-security-groups config)
:aws-iam-role (aws-iam-roles config)
:aws-iam-instance-profile (aws-iam-instance-profile config)
:aws-iam-role-policy (aws-iam-role-policies config)}})
| null |
https://raw.githubusercontent.com/juxt/roll/1ef07d72f05b5604eec4f7d6a5dbf0d21ec3c8b3/src/roll/modules/service_security.cljs
|
clojure
|
(ns roll.modules.service-security
(:require [roll.utils :refer [resolve-path ->json $ ->snake]]))
(defn- aws-security-groups
"Generate a security group for each service."
[{:keys [environment] :as config}]
(into {} (for [[service-k {:keys [port]}] (:services config)
:let [environment (str environment "-" (name service-k))]]
[service-k
{:name environment
:description (str "Allow access to " environment" application")
:vpc-id ($ [:local :vpc-id])
:ingress (remove nil?
[{:from-port 22
:to-port 22
:protocol "tcp"
:cidr-blocks ["0.0.0.0/0"]}
(when port
{:from-port port
:to-port port
:protocol "tcp"
:cidr-blocks ["0.0.0.0/0"]})])
:egress [{:from-port 0
:to-port 65535
:protocol "tcp"
:cidr-blocks ["0.0.0.0/0"]}]
:tags {:name environment}}])))
(def default-iam-policy
{:Version "2012-10-17"
:Statement [{:Sid ""
:Action "sts:AssumeRole"
:Effect "Allow"
:Principal {:Service "ec2.amazonaws.com"}}]})
(defn- aws-iam-roles
"Generate an IAM role for each service."
[{:keys [environment] :as config}]
(into {} (for [service (keys (:services config))
:let [environment (str environment "-" (name service))]]
[service
{:name (->snake (str environment"_role"))
:assume-role-policy (->json default-iam-policy)}])))
(defn- aws-iam-instance-profile
[{:keys [environment] :as config}]
(into {} (for [service (keys (:services config))
:let [environment (str environment "-" (name service))]]
[service
{:name environment
:role ($ [:aws-iam-role service :name])}])))
(defn- aws-iam-role-policies
"Every service we run needs access to S3 to fetch releases, plus
additional policies as described."
[{:keys [releases-bucket environment services]}]
(into {} (for [[service {:keys [policies]}] services]
[service
{:name (str environment "-" (name service))
:role ($ [:aws-iam-role service :id])
:policy (->json
{:Statement
(concat [{:Effect "Allow"
:Action ["s3:GetObject"]
:Resource [(str "arn:aws:s3:::" releases-bucket "/*")]}]
policies)})}])))
(defn generate [{:keys [environment] :as config}]
{:resource
{:aws-security-group (aws-security-groups config)
:aws-iam-role (aws-iam-roles config)
:aws-iam-instance-profile (aws-iam-instance-profile config)
:aws-iam-role-policy (aws-iam-role-policies config)}})
|
|
08eff6af01a86f992645efbac66e3526885db4966740923c3d4d4c13048c3d08
|
fukamachi/fast-websocket
|
fast-websocket.lisp
|
(in-package :cl-user)
(defpackage fast-websocket
(:use :cl
#:fast-websocket.constants
#:fast-websocket.ws)
(:import-from :fast-websocket.parser
#:make-ll-parser)
(:import-from :fast-websocket.compose
#:compose-frame)
(:import-from :fast-websocket.payload
#:fast-write-masked-sequence
#:mask-message)
(:import-from :fast-websocket.error
#:websocket-error
#:websocket-parse-error
#:protocol-error
#:too-large
#:unacceptable
#:encoding-error
#:acceptable-error-code-p
#:error-code)
(:import-from :fast-io
#:make-output-buffer
#:finish-output-buffer
#:fast-write-sequence)
(:import-from :babel
#:octets-to-string
#:character-decoding-error)
(:export #:make-parser
#:compose-frame
#:ws
#:make-ws
#:ws-fin
#:ws-opcode
#:ws-mask
#:ws-masking-key
#:ws-length
#:ws-stage
#:opcode
#:opcode-name
;; errors
#:websocket-error
#:websocket-parse-error
#:protocol-error
#:too-large
#:unacceptable
#:encoding-error
#:error-code))
(in-package :fast-websocket)
(defun make-payload-callback (ws message-callback ping-callback pong-callback close-callback)
(declare (type (or null function)
message-callback ping-callback pong-callback close-callback))
(let ((buffer (make-output-buffer)))
(lambda (payload &key (start 0) (end (length payload)))
(declare (optimize (speed 3) (safety 2))
(type (simple-array (unsigned-byte 8) (*)) payload)
(type integer start end))
(ecase (opcode-name (ws-opcode ws))
(:continuation
(fast-write-sequence payload buffer start end)
(when (ws-fin ws)
(let ((message (finish-output-buffer buffer)))
(when (ws-mask ws)
(mask-message message (ws-masking-key ws)))
(setf buffer (make-output-buffer))
(when message-callback
(funcall (the function message-callback)
(if (eq (ws-mode ws) :text)
(handler-case
(octets-to-string message :encoding :utf-8)
(character-decoding-error ()
(error 'encoding-error)))
message))))))
(:text
(if (ws-fin ws)
(when message-callback
(handler-case
(funcall (the function message-callback)
(if (ws-mask ws)
(octets-to-string
(let ((payload (subseq payload start end)))
(mask-message payload (ws-masking-key ws)))
:encoding :utf-8)
(octets-to-string payload
:encoding :utf-8
:start start :end end)))
(character-decoding-error ()
(error 'encoding-error))))
(fast-write-sequence payload buffer start end)))
(:binary
(if (ws-fin ws)
(when message-callback
(funcall message-callback
(if (ws-mask ws)
(let ((payload (subseq payload start end)))
(mask-message payload (ws-masking-key ws)))
(subseq payload start end))))
(fast-write-sequence payload buffer start end)))
(:close
(let* ((payload (subseq payload start end))
(payload (if (ws-mask ws)
(mask-message payload (ws-masking-key ws))
payload))
(length (- end start))
(has-code (<= 2 length))
(code (if has-code
(+ (* 256 (aref payload 0)) (aref payload 1))
nil)))
(declare (type integer length))
(unless (or (zerop length)
(acceptable-error-code-p code))
(setq code (error-code :protocol-error)))
(if has-code
(let ((reason (octets-to-string payload :encoding :utf-8 :start 2)))
(funcall close-callback reason :code code))
(funcall close-callback "" :code code))))
(:ping
(when ping-callback
(let ((payload (subseq payload start end)))
(when (ws-mask ws)
(mask-message payload (ws-masking-key ws)))
(funcall (the function ping-callback) payload))))
(:pong
(when pong-callback
(let ((payload (subseq payload start end)))
(when (ws-mask ws)
(mask-message payload (ws-masking-key ws)))
(funcall (the function pong-callback) payload))))))))
(defun make-parser (ws &key
(require-masking t)
(max-length #x3ffffff)
message-callback ;; (message)
ping-callback ;; (payload)
pong-callback ;; (payload)
close-callback ;; (payload &key code)
error-callback) ;; (code reason)
(declare (type (or null function) error-callback))
(let ((parser
(make-ll-parser ws
:require-masking require-masking
:max-length max-length
:payload-callback
(make-payload-callback ws
message-callback
ping-callback
pong-callback
close-callback)))
(bufferedp nil)
(buffer (make-output-buffer)))
(lambda (data &key start end)
(setq start (or start 0)
end (or end (length data)))
(when bufferedp
(fast-write-sequence data buffer start end)
(setq data (finish-output-buffer buffer))
(setq buffer (make-output-buffer)
bufferedp nil)
(setq start 0
end (length data)))
(multiple-value-bind (i eofp)
(handler-case
(funcall parser data :start start :end (or end (length data)))
(protocol-error (e)
(when error-callback
(funcall (the function error-callback)
(error-code e)
(princ-to-string e)))))
(when eofp
(setq bufferedp t)
(fast-write-sequence data buffer i))))))
| null |
https://raw.githubusercontent.com/fukamachi/fast-websocket/24c0217e7c0d25b6ef6ab799452cba0b9fb58f44/src/fast-websocket.lisp
|
lisp
|
errors
(message)
(payload)
(payload)
(payload &key code)
(code reason)
|
(in-package :cl-user)
(defpackage fast-websocket
(:use :cl
#:fast-websocket.constants
#:fast-websocket.ws)
(:import-from :fast-websocket.parser
#:make-ll-parser)
(:import-from :fast-websocket.compose
#:compose-frame)
(:import-from :fast-websocket.payload
#:fast-write-masked-sequence
#:mask-message)
(:import-from :fast-websocket.error
#:websocket-error
#:websocket-parse-error
#:protocol-error
#:too-large
#:unacceptable
#:encoding-error
#:acceptable-error-code-p
#:error-code)
(:import-from :fast-io
#:make-output-buffer
#:finish-output-buffer
#:fast-write-sequence)
(:import-from :babel
#:octets-to-string
#:character-decoding-error)
(:export #:make-parser
#:compose-frame
#:ws
#:make-ws
#:ws-fin
#:ws-opcode
#:ws-mask
#:ws-masking-key
#:ws-length
#:ws-stage
#:opcode
#:opcode-name
#:websocket-error
#:websocket-parse-error
#:protocol-error
#:too-large
#:unacceptable
#:encoding-error
#:error-code))
(in-package :fast-websocket)
(defun make-payload-callback (ws message-callback ping-callback pong-callback close-callback)
(declare (type (or null function)
message-callback ping-callback pong-callback close-callback))
(let ((buffer (make-output-buffer)))
(lambda (payload &key (start 0) (end (length payload)))
(declare (optimize (speed 3) (safety 2))
(type (simple-array (unsigned-byte 8) (*)) payload)
(type integer start end))
(ecase (opcode-name (ws-opcode ws))
(:continuation
(fast-write-sequence payload buffer start end)
(when (ws-fin ws)
(let ((message (finish-output-buffer buffer)))
(when (ws-mask ws)
(mask-message message (ws-masking-key ws)))
(setf buffer (make-output-buffer))
(when message-callback
(funcall (the function message-callback)
(if (eq (ws-mode ws) :text)
(handler-case
(octets-to-string message :encoding :utf-8)
(character-decoding-error ()
(error 'encoding-error)))
message))))))
(:text
(if (ws-fin ws)
(when message-callback
(handler-case
(funcall (the function message-callback)
(if (ws-mask ws)
(octets-to-string
(let ((payload (subseq payload start end)))
(mask-message payload (ws-masking-key ws)))
:encoding :utf-8)
(octets-to-string payload
:encoding :utf-8
:start start :end end)))
(character-decoding-error ()
(error 'encoding-error))))
(fast-write-sequence payload buffer start end)))
(:binary
(if (ws-fin ws)
(when message-callback
(funcall message-callback
(if (ws-mask ws)
(let ((payload (subseq payload start end)))
(mask-message payload (ws-masking-key ws)))
(subseq payload start end))))
(fast-write-sequence payload buffer start end)))
(:close
(let* ((payload (subseq payload start end))
(payload (if (ws-mask ws)
(mask-message payload (ws-masking-key ws))
payload))
(length (- end start))
(has-code (<= 2 length))
(code (if has-code
(+ (* 256 (aref payload 0)) (aref payload 1))
nil)))
(declare (type integer length))
(unless (or (zerop length)
(acceptable-error-code-p code))
(setq code (error-code :protocol-error)))
(if has-code
(let ((reason (octets-to-string payload :encoding :utf-8 :start 2)))
(funcall close-callback reason :code code))
(funcall close-callback "" :code code))))
(:ping
(when ping-callback
(let ((payload (subseq payload start end)))
(when (ws-mask ws)
(mask-message payload (ws-masking-key ws)))
(funcall (the function ping-callback) payload))))
(:pong
(when pong-callback
(let ((payload (subseq payload start end)))
(when (ws-mask ws)
(mask-message payload (ws-masking-key ws)))
(funcall (the function pong-callback) payload))))))))
(defun make-parser (ws &key
(require-masking t)
(max-length #x3ffffff)
(declare (type (or null function) error-callback))
(let ((parser
(make-ll-parser ws
:require-masking require-masking
:max-length max-length
:payload-callback
(make-payload-callback ws
message-callback
ping-callback
pong-callback
close-callback)))
(bufferedp nil)
(buffer (make-output-buffer)))
(lambda (data &key start end)
(setq start (or start 0)
end (or end (length data)))
(when bufferedp
(fast-write-sequence data buffer start end)
(setq data (finish-output-buffer buffer))
(setq buffer (make-output-buffer)
bufferedp nil)
(setq start 0
end (length data)))
(multiple-value-bind (i eofp)
(handler-case
(funcall parser data :start start :end (or end (length data)))
(protocol-error (e)
(when error-callback
(funcall (the function error-callback)
(error-code e)
(princ-to-string e)))))
(when eofp
(setq bufferedp t)
(fast-write-sequence data buffer i))))))
|
ee659f52fc4798e634893799864679a50c6b8d553accfe35edff355534145026
|
bhuztez/russell
|
russell_prim_shell.erl
|
-module(russell_prim_shell).
-export([run/1, format_error/1]).
format_error({unknown_command, Name}) ->
io_lib:format("unknown command ~ts", [Name]);
format_error(step_not_allowed) ->
"proof step not allowed".
run([Filename]) ->
case russell_prim:parse(Filename) of
{ok, Forms} ->
case verify_forms(Forms, #{}) of
{ok, Defs} ->
server(Defs);
{error, _} = Error ->
russell:file_error(Filename, Error)
end;
{error, _} = Error ->
Error
end.
verify_forms([], Defs) ->
{ok, Defs};
verify_forms([{def, _, _, _}=H|T], Defs) ->
case russell_prim:verify_form(H, Defs) of
{ok, Defs1} ->
verify_forms(T, Defs1);
{error, _} = Error ->
Error
end;
verify_forms([_|T], Defs) ->
verify_forms(T, Defs).
server(Defs) ->
server_loop(none, Defs).
server_loop(State, Defs) ->
case io:get_line(">>> ") of
eof ->
io:format("~n", []);
Line ->
{ok, Tokens, _} = russell_prim_lexer:string(Line),
case handle_tokens(Tokens, State, Defs) of
{error, {_, M, E}} ->
io:format("ERROR: ~ts~n", [M:format_error(E)]),
State1 = State;
{ok, State1} ->
ok
end,
server_loop(State1, Defs)
end.
handle_tokens([], State, _) ->
{ok, State};
handle_tokens(Tokens, State, Defs) ->
case russell_prim_shell_parser:parse(Tokens) of
{error, _} = Error ->
Error;
{ok, {{var, _, V}, Args}} ->
eval_cmd(V, Args, State, Defs);
{ok, {{atom, Line, A}, Args}} ->
eval_step({A,Line}, Args, State, Defs)
end.
eval_cmd(quit, [], _, _) ->
halt();
eval_cmd(def, [Name], State, Defs) ->
case russell_core:find(Name, Defs) of
{error, _} = Error ->
Error;
{ok, {In, Out}} ->
io:format(
"~ts. ~ts.~n",
[[[" ",russell_core:format_tokens(I), ".\n"]
|| I <- In],
russell_core:format_tokens(Out)]),
{ok, State}
end;
eval_cmd(prove, [Name], _, Defs) ->
case russell_core:find(Name, Defs) of
{error, _} = Error ->
Error;
{ok, {In, Out}} ->
State1 =
#{name => Name,
next => 1,
counter => 0,
steps => [],
stmts => #{},
goal => Out},
{In1, State2} = add_stmts(In, State1),
{ok, {prove, State2#{input => lists:zip([{I,1} || I <- In1], In)}}}
end;
eval_cmd(qed, [], {prove, State = #{input := Ins, steps := Steps=[_|_], goal := Goal}}, _) ->
{_, Out} = lists:last(Steps),
case russell_core:verify_output(Ins, Out, Goal) of
{error, _} = Error ->
Error;
_ ->
show_all(State),
{ok, {done, State}}
end;
eval_cmd(save, [], {done, State = #{name := Name, steps := Steps, input := Ins}}, _) ->
io:format(
"~ts",
[russell_prim:format([{proof, {Name, [I || {I,_} <-Ins]}, [{N,[O|I]} || {{N,I},{O,_}} <- Steps]}])]),
{ok, State};
eval_cmd(dump, [], {Type, State}, _) ->
show_all(State),
{ok, {Type, State}};
eval_cmd(Name, _, _, _) ->
{error, {1, ?MODULE, {unknown_command, Name}}}.
eval_step(Name, Ins, {prove, State = #{stmts := Stmts, counter := Counter}}, Defs) ->
Defined = sets:from_list(maps:keys(Stmts)),
case russell_prim:validate_uses(Ins, Defined) of
{error, _} = Error ->
Error;
{ok, _} ->
case russell_core:verify_step(Name, Ins, Stmts, Counter, Defs) of
{error, _} = Error ->
Error;
{ok, OutStmt, Counter1} ->
{Out, State1 = #{steps := Steps}} = add_stmt(OutStmt, State#{counter => Counter1}),
Step = {{Name,Ins},{{Out,1},OutStmt}},
{ok, {prove, State1#{steps := Steps ++ [Step]}}}
end
end;
eval_step(_, _, _, _) ->
{error, {1, ?MODULE, step_not_allowed}}.
show_all(#{steps := Steps, input := Inputs}) ->
io:format(
"~ts~n~ts~n",
[russell_prim:format_stmts(Inputs),
russell_prim:format_steps(Steps)]).
add_stmts(Stmts, State) ->
lists:mapfoldl(fun add_stmt/2, State, Stmts).
add_stmt(Stmt, State = #{next := Next, stmts := Stmts}) ->
Name = list_to_atom(integer_to_list(Next)),
io:format("~ts~n", [russell_prim:format_stmt({{Name, 1}, Stmt})]),
{Name, State#{next => Next + 1, stmts => Stmts#{Name => Stmt}}}.
| null |
https://raw.githubusercontent.com/bhuztez/russell/eaafa8207f2da3e2544a567edf10e6d33120c4ce/src/russell_prim_shell.erl
|
erlang
|
-module(russell_prim_shell).
-export([run/1, format_error/1]).
format_error({unknown_command, Name}) ->
io_lib:format("unknown command ~ts", [Name]);
format_error(step_not_allowed) ->
"proof step not allowed".
run([Filename]) ->
case russell_prim:parse(Filename) of
{ok, Forms} ->
case verify_forms(Forms, #{}) of
{ok, Defs} ->
server(Defs);
{error, _} = Error ->
russell:file_error(Filename, Error)
end;
{error, _} = Error ->
Error
end.
verify_forms([], Defs) ->
{ok, Defs};
verify_forms([{def, _, _, _}=H|T], Defs) ->
case russell_prim:verify_form(H, Defs) of
{ok, Defs1} ->
verify_forms(T, Defs1);
{error, _} = Error ->
Error
end;
verify_forms([_|T], Defs) ->
verify_forms(T, Defs).
server(Defs) ->
server_loop(none, Defs).
server_loop(State, Defs) ->
case io:get_line(">>> ") of
eof ->
io:format("~n", []);
Line ->
{ok, Tokens, _} = russell_prim_lexer:string(Line),
case handle_tokens(Tokens, State, Defs) of
{error, {_, M, E}} ->
io:format("ERROR: ~ts~n", [M:format_error(E)]),
State1 = State;
{ok, State1} ->
ok
end,
server_loop(State1, Defs)
end.
handle_tokens([], State, _) ->
{ok, State};
handle_tokens(Tokens, State, Defs) ->
case russell_prim_shell_parser:parse(Tokens) of
{error, _} = Error ->
Error;
{ok, {{var, _, V}, Args}} ->
eval_cmd(V, Args, State, Defs);
{ok, {{atom, Line, A}, Args}} ->
eval_step({A,Line}, Args, State, Defs)
end.
eval_cmd(quit, [], _, _) ->
halt();
eval_cmd(def, [Name], State, Defs) ->
case russell_core:find(Name, Defs) of
{error, _} = Error ->
Error;
{ok, {In, Out}} ->
io:format(
"~ts. ~ts.~n",
[[[" ",russell_core:format_tokens(I), ".\n"]
|| I <- In],
russell_core:format_tokens(Out)]),
{ok, State}
end;
eval_cmd(prove, [Name], _, Defs) ->
case russell_core:find(Name, Defs) of
{error, _} = Error ->
Error;
{ok, {In, Out}} ->
State1 =
#{name => Name,
next => 1,
counter => 0,
steps => [],
stmts => #{},
goal => Out},
{In1, State2} = add_stmts(In, State1),
{ok, {prove, State2#{input => lists:zip([{I,1} || I <- In1], In)}}}
end;
eval_cmd(qed, [], {prove, State = #{input := Ins, steps := Steps=[_|_], goal := Goal}}, _) ->
{_, Out} = lists:last(Steps),
case russell_core:verify_output(Ins, Out, Goal) of
{error, _} = Error ->
Error;
_ ->
show_all(State),
{ok, {done, State}}
end;
eval_cmd(save, [], {done, State = #{name := Name, steps := Steps, input := Ins}}, _) ->
io:format(
"~ts",
[russell_prim:format([{proof, {Name, [I || {I,_} <-Ins]}, [{N,[O|I]} || {{N,I},{O,_}} <- Steps]}])]),
{ok, State};
eval_cmd(dump, [], {Type, State}, _) ->
show_all(State),
{ok, {Type, State}};
eval_cmd(Name, _, _, _) ->
{error, {1, ?MODULE, {unknown_command, Name}}}.
eval_step(Name, Ins, {prove, State = #{stmts := Stmts, counter := Counter}}, Defs) ->
Defined = sets:from_list(maps:keys(Stmts)),
case russell_prim:validate_uses(Ins, Defined) of
{error, _} = Error ->
Error;
{ok, _} ->
case russell_core:verify_step(Name, Ins, Stmts, Counter, Defs) of
{error, _} = Error ->
Error;
{ok, OutStmt, Counter1} ->
{Out, State1 = #{steps := Steps}} = add_stmt(OutStmt, State#{counter => Counter1}),
Step = {{Name,Ins},{{Out,1},OutStmt}},
{ok, {prove, State1#{steps := Steps ++ [Step]}}}
end
end;
eval_step(_, _, _, _) ->
{error, {1, ?MODULE, step_not_allowed}}.
show_all(#{steps := Steps, input := Inputs}) ->
io:format(
"~ts~n~ts~n",
[russell_prim:format_stmts(Inputs),
russell_prim:format_steps(Steps)]).
add_stmts(Stmts, State) ->
lists:mapfoldl(fun add_stmt/2, State, Stmts).
add_stmt(Stmt, State = #{next := Next, stmts := Stmts}) ->
Name = list_to_atom(integer_to_list(Next)),
io:format("~ts~n", [russell_prim:format_stmt({{Name, 1}, Stmt})]),
{Name, State#{next => Next + 1, stmts => Stmts#{Name => Stmt}}}.
|
|
4e53df6ec27a409829ec8e94cbac11d64d642e60199f38f6c1d4e7394f3e5d35
|
nikita-volkov/rerebase
|
Complex.hs
|
module Data.Complex
(
module Rebase.Data.Complex
)
where
import Rebase.Data.Complex
| null |
https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/Data/Complex.hs
|
haskell
|
module Data.Complex
(
module Rebase.Data.Complex
)
where
import Rebase.Data.Complex
|
|
80079a5c60ff4707f2610b9e52021c1a61a5141a9a9cbe47acbb6c94fe4ef1bd
|
brendanhay/gogol
|
Product.hs
|
# LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . TPU.Internal . Product
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
module Gogol.TPU.Internal.Product
* AcceleratorType
AcceleratorType (..),
newAcceleratorType,
*
AccessConfig (..),
newAccessConfig,
* AttachedDisk
AttachedDisk (..),
newAttachedDisk,
-- * Empty
Empty (..),
newEmpty,
-- * GenerateServiceIdentityRequest
GenerateServiceIdentityRequest (..),
newGenerateServiceIdentityRequest,
-- * GenerateServiceIdentityResponse
GenerateServiceIdentityResponse (..),
newGenerateServiceIdentityResponse,
-- * GetGuestAttributesRequest
GetGuestAttributesRequest (..),
newGetGuestAttributesRequest,
-- * GetGuestAttributesResponse
GetGuestAttributesResponse (..),
newGetGuestAttributesResponse,
* GuestAttributes
GuestAttributes (..),
newGuestAttributes,
-- * GuestAttributesEntry
GuestAttributesEntry (..),
newGuestAttributesEntry,
-- * GuestAttributesValue
GuestAttributesValue (..),
newGuestAttributesValue,
-- * ListAcceleratorTypesResponse
ListAcceleratorTypesResponse (..),
newListAcceleratorTypesResponse,
* ListLocationsResponse
ListLocationsResponse (..),
newListLocationsResponse,
-- * ListNodesResponse
ListNodesResponse (..),
newListNodesResponse,
-- * ListOperationsResponse
ListOperationsResponse (..),
newListOperationsResponse,
-- * ListRuntimeVersionsResponse
ListRuntimeVersionsResponse (..),
newListRuntimeVersionsResponse,
-- * Location
Location (..),
newLocation,
-- * Location_Labels
Location_Labels (..),
newLocation_Labels,
-- * Location_Metadata
Location_Metadata (..),
newLocation_Metadata,
* NetworkConfig
NetworkConfig (..),
newNetworkConfig,
* NetworkEndpoint
NetworkEndpoint (..),
newNetworkEndpoint,
-- * Node
Node (..),
newNode,
-- * Node_Labels
Node_Labels (..),
newNode_Labels,
-- * Node_Metadata
Node_Metadata (..),
newNode_Metadata,
-- * Operation
Operation (..),
newOperation,
-- * Operation_Metadata
Operation_Metadata (..),
newOperation_Metadata,
-- * Operation_Response
Operation_Response (..),
newOperation_Response,
-- * OperationMetadata
OperationMetadata (..),
newOperationMetadata,
-- * RuntimeVersion
RuntimeVersion (..),
newRuntimeVersion,
*
SchedulingConfig (..),
newSchedulingConfig,
-- * ServiceAccount
ServiceAccount (..),
newServiceAccount,
-- * ServiceIdentity
ServiceIdentity (..),
newServiceIdentity,
-- * StartNodeRequest
StartNodeRequest (..),
newStartNodeRequest,
-- * Status
Status (..),
newStatus,
-- * Status_DetailsItem
Status_DetailsItem (..),
newStatus_DetailsItem,
-- * StopNodeRequest
StopNodeRequest (..),
newStopNodeRequest,
-- * Symptom
Symptom (..),
newSymptom,
)
where
import qualified Gogol.Prelude as Core
import Gogol.TPU.Internal.Sum
-- | A accelerator type that a Node can be configured with.
--
-- /See:/ 'newAcceleratorType' smart constructor.
data AcceleratorType = AcceleratorType
{ -- | The resource name.
name :: (Core.Maybe Core.Text),
-- | the accelerator type.
type' :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' AcceleratorType ' with the minimum fields required to make a request .
newAcceleratorType ::
AcceleratorType
newAcceleratorType = AcceleratorType {name = Core.Nothing, type' = Core.Nothing}
instance Core.FromJSON AcceleratorType where
parseJSON =
Core.withObject
"AcceleratorType"
( \o ->
AcceleratorType
Core.<$> (o Core..:? "name") Core.<*> (o Core..:? "type")
)
instance Core.ToJSON AcceleratorType where
toJSON AcceleratorType {..} =
Core.object
( Core.catMaybes
[ ("name" Core..=) Core.<$> name,
("type" Core..=) Core.<$> type'
]
)
| An access config attached to the TPU worker .
--
-- /See:/ 'newAccessConfig' smart constructor.
newtype AccessConfig = AccessConfig
| Output only . An external IP address associated with the TPU worker .
externalIp :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'AccessConfig' with the minimum fields required to make a request.
newAccessConfig ::
AccessConfig
newAccessConfig = AccessConfig {externalIp = Core.Nothing}
instance Core.FromJSON AccessConfig where
parseJSON =
Core.withObject
"AccessConfig"
( \o ->
AccessConfig Core.<$> (o Core..:? "externalIp")
)
instance Core.ToJSON AccessConfig where
toJSON AccessConfig {..} =
Core.object
( Core.catMaybes
[("externalIp" Core..=) Core.<$> externalIp]
)
| A node - attached disk resource . Next ID : 8 ;
--
-- /See:/ 'newAttachedDisk' smart constructor.
data AttachedDisk = AttachedDisk
{ -- | The mode in which to attach this disk. If not specified, the default is READ/WRITE mode. Only applicable to data/disks.
mode :: (Core.Maybe AttachedDisk_Mode),
-- | Specifies the full path to an existing disk. For example: \"projects\/my-project\/zones\/us-central1-c\/disks\/my-disk\".
sourceDisk :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' AttachedDisk ' with the minimum fields required to make a request .
newAttachedDisk ::
AttachedDisk
newAttachedDisk = AttachedDisk {mode = Core.Nothing, sourceDisk = Core.Nothing}
instance Core.FromJSON AttachedDisk where
parseJSON =
Core.withObject
"AttachedDisk"
( \o ->
AttachedDisk
Core.<$> (o Core..:? "mode")
Core.<*> (o Core..:? "sourceDisk")
)
instance Core.ToJSON AttachedDisk where
toJSON AttachedDisk {..} =
Core.object
( Core.catMaybes
[ ("mode" Core..=) Core.<$> mode,
("sourceDisk" Core..=) Core.<$> sourceDisk
]
)
| A generic empty message that you can re - use to avoid defining duplicated empty messages in your APIs . A typical example is to use it as the request or the response type of an API method . For instance : service Foo { rpc Bar(google.protobuf . Empty ) returns ( google.protobuf . Empty ) ; } The JSON representation for @Empty@ is empty JSON object @{}@.
--
/See:/ ' ' smart constructor .
data Empty = Empty
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Empty' with the minimum fields required to make a request.
newEmpty ::
Empty
newEmpty = Empty
instance Core.FromJSON Empty where
parseJSON =
Core.withObject "Empty" (\o -> Core.pure Empty)
instance Core.ToJSON Empty where
toJSON = Core.const Core.emptyObject
-- | Request for GenerateServiceIdentity.
--
-- /See:/ 'newGenerateServiceIdentityRequest' smart constructor.
data GenerateServiceIdentityRequest = GenerateServiceIdentityRequest
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GenerateServiceIdentityRequest' with the minimum fields required to make a request.
newGenerateServiceIdentityRequest ::
GenerateServiceIdentityRequest
newGenerateServiceIdentityRequest = GenerateServiceIdentityRequest
instance Core.FromJSON GenerateServiceIdentityRequest where
parseJSON =
Core.withObject
"GenerateServiceIdentityRequest"
(\o -> Core.pure GenerateServiceIdentityRequest)
instance Core.ToJSON GenerateServiceIdentityRequest where
toJSON = Core.const Core.emptyObject
-- | Response for GenerateServiceIdentity.
--
-- /See:/ 'newGenerateServiceIdentityResponse' smart constructor.
newtype GenerateServiceIdentityResponse = GenerateServiceIdentityResponse
| ServiceIdentity that was created or retrieved .
identity :: (Core.Maybe ServiceIdentity)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GenerateServiceIdentityResponse' with the minimum fields required to make a request.
newGenerateServiceIdentityResponse ::
GenerateServiceIdentityResponse
newGenerateServiceIdentityResponse =
GenerateServiceIdentityResponse {identity = Core.Nothing}
instance
Core.FromJSON
GenerateServiceIdentityResponse
where
parseJSON =
Core.withObject
"GenerateServiceIdentityResponse"
( \o ->
GenerateServiceIdentityResponse
Core.<$> (o Core..:? "identity")
)
instance Core.ToJSON GenerateServiceIdentityResponse where
toJSON GenerateServiceIdentityResponse {..} =
Core.object
( Core.catMaybes
[("identity" Core..=) Core.<$> identity]
)
-- | Request for GetGuestAttributes.
--
-- /See:/ 'newGetGuestAttributesRequest' smart constructor.
data GetGuestAttributesRequest = GetGuestAttributesRequest
{ -- | The guest attributes path to be queried.
queryPath :: (Core.Maybe Core.Text),
| The 0 - based worker ID . If it is empty , all workers\ ' GuestAttributes will be returned .
workerIds :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GetGuestAttributesRequest' with the minimum fields required to make a request.
newGetGuestAttributesRequest ::
GetGuestAttributesRequest
newGetGuestAttributesRequest =
GetGuestAttributesRequest {queryPath = Core.Nothing, workerIds = Core.Nothing}
instance Core.FromJSON GetGuestAttributesRequest where
parseJSON =
Core.withObject
"GetGuestAttributesRequest"
( \o ->
GetGuestAttributesRequest
Core.<$> (o Core..:? "queryPath")
Core.<*> (o Core..:? "workerIds")
)
instance Core.ToJSON GetGuestAttributesRequest where
toJSON GetGuestAttributesRequest {..} =
Core.object
( Core.catMaybes
[ ("queryPath" Core..=) Core.<$> queryPath,
("workerIds" Core..=) Core.<$> workerIds
]
)
-- | Response for GetGuestAttributes.
--
-- /See:/ 'newGetGuestAttributesResponse' smart constructor.
newtype GetGuestAttributesResponse = GetGuestAttributesResponse
| The guest attributes for the TPU workers .
guestAttributes :: (Core.Maybe [GuestAttributes])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GetGuestAttributesResponse' with the minimum fields required to make a request.
newGetGuestAttributesResponse ::
GetGuestAttributesResponse
newGetGuestAttributesResponse =
GetGuestAttributesResponse {guestAttributes = Core.Nothing}
instance Core.FromJSON GetGuestAttributesResponse where
parseJSON =
Core.withObject
"GetGuestAttributesResponse"
( \o ->
GetGuestAttributesResponse
Core.<$> (o Core..:? "guestAttributes")
)
instance Core.ToJSON GetGuestAttributesResponse where
toJSON GetGuestAttributesResponse {..} =
Core.object
( Core.catMaybes
[ ("guestAttributes" Core..=)
Core.<$> guestAttributes
]
)
-- | A guest attributes.
--
-- /See:/ 'newGuestAttributes' smart constructor.
data GuestAttributes = GuestAttributes
{ -- | The path to be queried. This can be the default namespace (\'\/\') or a nested namespace (\'\/\\\/\') or a specified key (\'\/\\\/\\\')
queryPath :: (Core.Maybe Core.Text),
-- | The value of the requested queried path.
queryValue :: (Core.Maybe GuestAttributesValue)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' GuestAttributes ' with the minimum fields required to make a request .
newGuestAttributes ::
GuestAttributes
newGuestAttributes =
GuestAttributes {queryPath = Core.Nothing, queryValue = Core.Nothing}
instance Core.FromJSON GuestAttributes where
parseJSON =
Core.withObject
"GuestAttributes"
( \o ->
GuestAttributes
Core.<$> (o Core..:? "queryPath")
Core.<*> (o Core..:? "queryValue")
)
instance Core.ToJSON GuestAttributes where
toJSON GuestAttributes {..} =
Core.object
( Core.catMaybes
[ ("queryPath" Core..=) Core.<$> queryPath,
("queryValue" Core..=) Core.<$> queryValue
]
)
-- | A guest attributes namespace\/key\/value entry.
--
-- /See:/ 'newGuestAttributesEntry' smart constructor.
data GuestAttributesEntry = GuestAttributesEntry
{ -- | Key for the guest attribute entry.
key :: (Core.Maybe Core.Text),
-- | Namespace for the guest attribute entry.
namespace :: (Core.Maybe Core.Text),
-- | Value for the guest attribute entry.
value :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GuestAttributesEntry' with the minimum fields required to make a request.
newGuestAttributesEntry ::
GuestAttributesEntry
newGuestAttributesEntry =
GuestAttributesEntry
{ key = Core.Nothing,
namespace = Core.Nothing,
value = Core.Nothing
}
instance Core.FromJSON GuestAttributesEntry where
parseJSON =
Core.withObject
"GuestAttributesEntry"
( \o ->
GuestAttributesEntry
Core.<$> (o Core..:? "key")
Core.<*> (o Core..:? "namespace")
Core.<*> (o Core..:? "value")
)
instance Core.ToJSON GuestAttributesEntry where
toJSON GuestAttributesEntry {..} =
Core.object
( Core.catMaybes
[ ("key" Core..=) Core.<$> key,
("namespace" Core..=) Core.<$> namespace,
("value" Core..=) Core.<$> value
]
)
-- | Array of guest attribute namespace\/key\/value tuples.
--
-- /See:/ 'newGuestAttributesValue' smart constructor.
newtype GuestAttributesValue = GuestAttributesValue
{ -- | The list of guest attributes entries.
items :: (Core.Maybe [GuestAttributesEntry])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GuestAttributesValue' with the minimum fields required to make a request.
newGuestAttributesValue ::
GuestAttributesValue
newGuestAttributesValue = GuestAttributesValue {items = Core.Nothing}
instance Core.FromJSON GuestAttributesValue where
parseJSON =
Core.withObject
"GuestAttributesValue"
( \o ->
GuestAttributesValue Core.<$> (o Core..:? "items")
)
instance Core.ToJSON GuestAttributesValue where
toJSON GuestAttributesValue {..} =
Core.object
(Core.catMaybes [("items" Core..=) Core.<$> items])
-- | Response for ListAcceleratorTypes.
--
-- /See:/ 'newListAcceleratorTypesResponse' smart constructor.
data ListAcceleratorTypesResponse = ListAcceleratorTypesResponse
{ -- | The listed nodes.
acceleratorTypes :: (Core.Maybe [AcceleratorType]),
-- | The next page token or empty if none.
nextPageToken :: (Core.Maybe Core.Text),
-- | Locations that could not be reached.
unreachable :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ListAcceleratorTypesResponse' with the minimum fields required to make a request.
newListAcceleratorTypesResponse ::
ListAcceleratorTypesResponse
newListAcceleratorTypesResponse =
ListAcceleratorTypesResponse
{ acceleratorTypes = Core.Nothing,
nextPageToken = Core.Nothing,
unreachable = Core.Nothing
}
instance Core.FromJSON ListAcceleratorTypesResponse where
parseJSON =
Core.withObject
"ListAcceleratorTypesResponse"
( \o ->
ListAcceleratorTypesResponse
Core.<$> (o Core..:? "acceleratorTypes")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "unreachable")
)
instance Core.ToJSON ListAcceleratorTypesResponse where
toJSON ListAcceleratorTypesResponse {..} =
Core.object
( Core.catMaybes
[ ("acceleratorTypes" Core..=)
Core.<$> acceleratorTypes,
("nextPageToken" Core..=) Core.<$> nextPageToken,
("unreachable" Core..=) Core.<$> unreachable
]
)
-- | The response message for Locations.ListLocations.
--
-- /See:/ 'newListLocationsResponse' smart constructor.
data ListLocationsResponse = ListLocationsResponse
{ -- | A list of locations that matches the specified filter in the request.
locations :: (Core.Maybe [Location]),
-- | The standard List next-page token.
nextPageToken :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ListLocationsResponse ' with the minimum fields required to make a request .
newListLocationsResponse ::
ListLocationsResponse
newListLocationsResponse =
ListLocationsResponse {locations = Core.Nothing, nextPageToken = Core.Nothing}
instance Core.FromJSON ListLocationsResponse where
parseJSON =
Core.withObject
"ListLocationsResponse"
( \o ->
ListLocationsResponse
Core.<$> (o Core..:? "locations")
Core.<*> (o Core..:? "nextPageToken")
)
instance Core.ToJSON ListLocationsResponse where
toJSON ListLocationsResponse {..} =
Core.object
( Core.catMaybes
[ ("locations" Core..=) Core.<$> locations,
("nextPageToken" Core..=) Core.<$> nextPageToken
]
)
| Response for ListNodes .
--
-- /See:/ 'newListNodesResponse' smart constructor.
data ListNodesResponse = ListNodesResponse
{ -- | The next page token or empty if none.
nextPageToken :: (Core.Maybe Core.Text),
-- | The listed nodes.
nodes :: (Core.Maybe [Node]),
-- | Locations that could not be reached.
unreachable :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ListNodesResponse ' with the minimum fields required to make a request .
newListNodesResponse ::
ListNodesResponse
newListNodesResponse =
ListNodesResponse
{ nextPageToken = Core.Nothing,
nodes = Core.Nothing,
unreachable = Core.Nothing
}
instance Core.FromJSON ListNodesResponse where
parseJSON =
Core.withObject
"ListNodesResponse"
( \o ->
ListNodesResponse
Core.<$> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "nodes")
Core.<*> (o Core..:? "unreachable")
)
instance Core.ToJSON ListNodesResponse where
toJSON ListNodesResponse {..} =
Core.object
( Core.catMaybes
[ ("nextPageToken" Core..=) Core.<$> nextPageToken,
("nodes" Core..=) Core.<$> nodes,
("unreachable" Core..=) Core.<$> unreachable
]
)
| The response message for Operations . ListOperations .
--
-- /See:/ 'newListOperationsResponse' smart constructor.
data ListOperationsResponse = ListOperationsResponse
{ -- | The standard List next-page token.
nextPageToken :: (Core.Maybe Core.Text),
-- | A list of operations that matches the specified filter in the request.
operations :: (Core.Maybe [Operation])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ListOperationsResponse' with the minimum fields required to make a request.
newListOperationsResponse ::
ListOperationsResponse
newListOperationsResponse =
ListOperationsResponse
{ nextPageToken = Core.Nothing,
operations = Core.Nothing
}
instance Core.FromJSON ListOperationsResponse where
parseJSON =
Core.withObject
"ListOperationsResponse"
( \o ->
ListOperationsResponse
Core.<$> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "operations")
)
instance Core.ToJSON ListOperationsResponse where
toJSON ListOperationsResponse {..} =
Core.object
( Core.catMaybes
[ ("nextPageToken" Core..=) Core.<$> nextPageToken,
("operations" Core..=) Core.<$> operations
]
)
-- | Response for ListRuntimeVersions.
--
-- /See:/ 'newListRuntimeVersionsResponse' smart constructor.
data ListRuntimeVersionsResponse = ListRuntimeVersionsResponse
{ -- | The next page token or empty if none.
nextPageToken :: (Core.Maybe Core.Text),
-- | The listed nodes.
runtimeVersions :: (Core.Maybe [RuntimeVersion]),
-- | Locations that could not be reached.
unreachable :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ListRuntimeVersionsResponse' with the minimum fields required to make a request.
newListRuntimeVersionsResponse ::
ListRuntimeVersionsResponse
newListRuntimeVersionsResponse =
ListRuntimeVersionsResponse
{ nextPageToken = Core.Nothing,
runtimeVersions = Core.Nothing,
unreachable = Core.Nothing
}
instance Core.FromJSON ListRuntimeVersionsResponse where
parseJSON =
Core.withObject
"ListRuntimeVersionsResponse"
( \o ->
ListRuntimeVersionsResponse
Core.<$> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "runtimeVersions")
Core.<*> (o Core..:? "unreachable")
)
instance Core.ToJSON ListRuntimeVersionsResponse where
toJSON ListRuntimeVersionsResponse {..} =
Core.object
( Core.catMaybes
[ ("nextPageToken" Core..=) Core.<$> nextPageToken,
("runtimeVersions" Core..=) Core.<$> runtimeVersions,
("unreachable" Core..=) Core.<$> unreachable
]
)
| A resource that represents Google Cloud Platform location .
--
/See:/ ' newLocation ' smart constructor .
data Location = Location
{ -- | The friendly name for this location, typically a nearby city name. For example, \"Tokyo\".
displayName :: (Core.Maybe Core.Text),
-- | Cross-service attributes for the location. For example {\"cloud.googleapis.com\/region\": \"us-east1\"}
labels :: (Core.Maybe Location_Labels),
| The canonical i d for this location . For example : @\"us - east1\"@.
locationId :: (Core.Maybe Core.Text),
-- | Service-specific metadata. For example the available capacity at the given location.
metadata :: (Core.Maybe Location_Metadata),
-- | Resource name for the location, which may vary between implementations. For example: @\"projects\/example-project\/locations\/us-east1\"@
name :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Location' with the minimum fields required to make a request.
newLocation ::
Location
newLocation =
Location
{ displayName = Core.Nothing,
labels = Core.Nothing,
locationId = Core.Nothing,
metadata = Core.Nothing,
name = Core.Nothing
}
instance Core.FromJSON Location where
parseJSON =
Core.withObject
"Location"
( \o ->
Location
Core.<$> (o Core..:? "displayName")
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "locationId")
Core.<*> (o Core..:? "metadata")
Core.<*> (o Core..:? "name")
)
instance Core.ToJSON Location where
toJSON Location {..} =
Core.object
( Core.catMaybes
[ ("displayName" Core..=) Core.<$> displayName,
("labels" Core..=) Core.<$> labels,
("locationId" Core..=) Core.<$> locationId,
("metadata" Core..=) Core.<$> metadata,
("name" Core..=) Core.<$> name
]
)
-- | Cross-service attributes for the location. For example {\"cloud.googleapis.com\/region\": \"us-east1\"}
--
-- /See:/ 'newLocation_Labels' smart constructor.
newtype Location_Labels = Location_Labels
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Location_Labels' with the minimum fields required to make a request.
newLocation_Labels ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
Location_Labels
newLocation_Labels additional = Location_Labels {additional = additional}
instance Core.FromJSON Location_Labels where
parseJSON =
Core.withObject
"Location_Labels"
( \o ->
Location_Labels Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Location_Labels where
toJSON Location_Labels {..} = Core.toJSON additional
-- | Service-specific metadata. For example the available capacity at the given location.
--
-- /See:/ 'newLocation_Metadata' smart constructor.
newtype Location_Metadata = Location_Metadata
{ -- | Properties of the object. Contains field \@type with type URL.
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Location_Metadata' with the minimum fields required to make a request.
newLocation_Metadata ::
-- | Properties of the object. Contains field \@type with type URL. See 'additional'.
Core.HashMap Core.Text Core.Value ->
Location_Metadata
newLocation_Metadata additional = Location_Metadata {additional = additional}
instance Core.FromJSON Location_Metadata where
parseJSON =
Core.withObject
"Location_Metadata"
( \o ->
Location_Metadata Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Location_Metadata where
toJSON Location_Metadata {..} = Core.toJSON additional
-- | Network related configurations.
--
-- /See:/ 'newNetworkConfig' smart constructor.
data NetworkConfig = NetworkConfig
| Allows the TPU node to send and receive packets with non - matching destination or source IPs . This is required if you plan to use the TPU workers to forward routes .
canIpForward :: (Core.Maybe Core.Bool),
| Indicates that external IP addresses would be associated with the TPU workers . If set to false , the specified subnetwork or network should have Private Google Access enabled .
enableExternalIps :: (Core.Maybe Core.Bool),
| The name of the network for the TPU node . It must be a preexisting Google Compute Engine network . If none is provided , \"default\ " will be used .
network :: (Core.Maybe Core.Text),
| The name of the subnetwork for the TPU node . It must be a preexisting Google Compute Engine subnetwork . If none is provided , \"default\ " will be used .
subnetwork :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' NetworkConfig ' with the minimum fields required to make a request .
newNetworkConfig ::
NetworkConfig
newNetworkConfig =
NetworkConfig
{ canIpForward = Core.Nothing,
enableExternalIps = Core.Nothing,
network = Core.Nothing,
subnetwork = Core.Nothing
}
instance Core.FromJSON NetworkConfig where
parseJSON =
Core.withObject
"NetworkConfig"
( \o ->
NetworkConfig
Core.<$> (o Core..:? "canIpForward")
Core.<*> (o Core..:? "enableExternalIps")
Core.<*> (o Core..:? "network")
Core.<*> (o Core..:? "subnetwork")
)
instance Core.ToJSON NetworkConfig where
toJSON NetworkConfig {..} =
Core.object
( Core.catMaybes
[ ("canIpForward" Core..=) Core.<$> canIpForward,
("enableExternalIps" Core..=)
Core.<$> enableExternalIps,
("network" Core..=) Core.<$> network,
("subnetwork" Core..=) Core.<$> subnetwork
]
)
| A network endpoint over which a TPU worker can be reached .
--
/See:/ ' newNetworkEndpoint ' smart constructor .
data NetworkEndpoint = NetworkEndpoint
| The access config for the TPU worker .
accessConfig :: (Core.Maybe AccessConfig),
-- | The internal IP address of this network endpoint.
ipAddress :: (Core.Maybe Core.Text),
-- | The port of this network endpoint.
port :: (Core.Maybe Core.Int32)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' NetworkEndpoint ' with the minimum fields required to make a request .
newNetworkEndpoint ::
NetworkEndpoint
newNetworkEndpoint =
NetworkEndpoint
{ accessConfig = Core.Nothing,
ipAddress = Core.Nothing,
port = Core.Nothing
}
instance Core.FromJSON NetworkEndpoint where
parseJSON =
Core.withObject
"NetworkEndpoint"
( \o ->
NetworkEndpoint
Core.<$> (o Core..:? "accessConfig")
Core.<*> (o Core..:? "ipAddress")
Core.<*> (o Core..:? "port")
)
instance Core.ToJSON NetworkEndpoint where
toJSON NetworkEndpoint {..} =
Core.object
( Core.catMaybes
[ ("accessConfig" Core..=) Core.<$> accessConfig,
("ipAddress" Core..=) Core.<$> ipAddress,
("port" Core..=) Core.<$> port
]
)
-- | A TPU instance.
--
-- /See:/ 'newNode' smart constructor.
data Node = Node
{ -- | Required. The type of hardware accelerators associated with this node.
acceleratorType :: (Core.Maybe Core.Text),
-- | Output only. The API version that created this Node.
apiVersion :: (Core.Maybe Node_ApiVersion),
| The CIDR block that the TPU node will use when selecting an IP address . This CIDR block must be a \/29 block ; the Compute Engine networks API forbids a smaller block , and using a larger block would be wasteful ( a node can only consume one IP address ) . Errors will occur if the CIDR block has already been used for a currently existing TPU node , the CIDR block conflicts with any subnetworks in the user\ 's provided network , or the provided network is peered with another network that is using that CIDR block .
cidrBlock :: (Core.Maybe Core.Text),
-- | Output only. The time when the node was created.
createTime :: (Core.Maybe Core.DateTime),
| The additional data disks for the Node .
dataDisks :: (Core.Maybe [AttachedDisk]),
| The user - supplied description of the TPU . Maximum of 512 characters .
description :: (Core.Maybe Core.Text),
| The health status of the TPU node .
health :: (Core.Maybe Node_Health),
-- | Output only. If this field is populated, it contains a description of why the TPU Node is unhealthy.
healthDescription :: (Core.Maybe Core.Text),
-- | Output only. The unique identifier for the TPU Node.
id :: (Core.Maybe Core.Int64),
-- | Resource labels to represent user-provided metadata.
labels :: (Core.Maybe Node_Labels),
-- | Custom metadata to apply to the TPU Node. Can set startup-script and shutdown-script
metadata :: (Core.Maybe Node_Metadata),
| Output only . Immutable . The name of the TPU .
name :: (Core.Maybe Core.Text),
| Network configurations for the TPU node .
networkConfig :: (Core.Maybe NetworkConfig),
| Output only . The network endpoints where TPU workers can be accessed and sent work . It is recommended that runtime clients of the node reach out to the 0th entry in this map first .
networkEndpoints :: (Core.Maybe [NetworkEndpoint]),
| Required . The runtime version running in the Node .
runtimeVersion :: (Core.Maybe Core.Text),
-- | The scheduling options for this node.
schedulingConfig :: (Core.Maybe SchedulingConfig),
| The Google Cloud Platform Service Account to be used by the TPU node VMs . If None is specified , the default compute service account will be used .
serviceAccount :: (Core.Maybe ServiceAccount),
-- | Output only. The current state for the TPU Node.
state :: (Core.Maybe Node_State),
-- | Output only. The Symptoms that have occurred to the TPU Node.
symptoms :: (Core.Maybe [Symptom]),
-- | Tags to apply to the TPU Node. Tags are used to identify valid sources or targets for network firewalls.
tags :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Node' with the minimum fields required to make a request.
newNode ::
Node
newNode =
Node
{ acceleratorType = Core.Nothing,
apiVersion = Core.Nothing,
cidrBlock = Core.Nothing,
createTime = Core.Nothing,
dataDisks = Core.Nothing,
description = Core.Nothing,
health = Core.Nothing,
healthDescription = Core.Nothing,
id = Core.Nothing,
labels = Core.Nothing,
metadata = Core.Nothing,
name = Core.Nothing,
networkConfig = Core.Nothing,
networkEndpoints = Core.Nothing,
runtimeVersion = Core.Nothing,
schedulingConfig = Core.Nothing,
serviceAccount = Core.Nothing,
state = Core.Nothing,
symptoms = Core.Nothing,
tags = Core.Nothing
}
instance Core.FromJSON Node where
parseJSON =
Core.withObject
"Node"
( \o ->
Node
Core.<$> (o Core..:? "acceleratorType")
Core.<*> (o Core..:? "apiVersion")
Core.<*> (o Core..:? "cidrBlock")
Core.<*> (o Core..:? "createTime")
Core.<*> (o Core..:? "dataDisks")
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "health")
Core.<*> (o Core..:? "healthDescription")
Core.<*> (o Core..:? "id" Core.<&> Core.fmap Core.fromAsText)
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "metadata")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "networkConfig")
Core.<*> (o Core..:? "networkEndpoints")
Core.<*> (o Core..:? "runtimeVersion")
Core.<*> (o Core..:? "schedulingConfig")
Core.<*> (o Core..:? "serviceAccount")
Core.<*> (o Core..:? "state")
Core.<*> (o Core..:? "symptoms")
Core.<*> (o Core..:? "tags")
)
instance Core.ToJSON Node where
toJSON Node {..} =
Core.object
( Core.catMaybes
[ ("acceleratorType" Core..=)
Core.<$> acceleratorType,
("apiVersion" Core..=) Core.<$> apiVersion,
("cidrBlock" Core..=) Core.<$> cidrBlock,
("createTime" Core..=) Core.<$> createTime,
("dataDisks" Core..=) Core.<$> dataDisks,
("description" Core..=) Core.<$> description,
("health" Core..=) Core.<$> health,
("healthDescription" Core..=)
Core.<$> healthDescription,
("id" Core..=) Core.. Core.AsText Core.<$> id,
("labels" Core..=) Core.<$> labels,
("metadata" Core..=) Core.<$> metadata,
("name" Core..=) Core.<$> name,
("networkConfig" Core..=) Core.<$> networkConfig,
("networkEndpoints" Core..=)
Core.<$> networkEndpoints,
("runtimeVersion" Core..=) Core.<$> runtimeVersion,
("schedulingConfig" Core..=)
Core.<$> schedulingConfig,
("serviceAccount" Core..=) Core.<$> serviceAccount,
("state" Core..=) Core.<$> state,
("symptoms" Core..=) Core.<$> symptoms,
("tags" Core..=) Core.<$> tags
]
)
-- | Resource labels to represent user-provided metadata.
--
-- /See:/ 'newNode_Labels' smart constructor.
newtype Node_Labels = Node_Labels
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Node_Labels' with the minimum fields required to make a request.
newNode_Labels ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
Node_Labels
newNode_Labels additional = Node_Labels {additional = additional}
instance Core.FromJSON Node_Labels where
parseJSON =
Core.withObject
"Node_Labels"
( \o ->
Node_Labels Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Node_Labels where
toJSON Node_Labels {..} = Core.toJSON additional
-- | Custom metadata to apply to the TPU Node. Can set startup-script and shutdown-script
--
-- /See:/ 'newNode_Metadata' smart constructor.
newtype Node_Metadata = Node_Metadata
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Node_Metadata' with the minimum fields required to make a request.
newNode_Metadata ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
Node_Metadata
newNode_Metadata additional = Node_Metadata {additional = additional}
instance Core.FromJSON Node_Metadata where
parseJSON =
Core.withObject
"Node_Metadata"
( \o ->
Node_Metadata Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Node_Metadata where
toJSON Node_Metadata {..} = Core.toJSON additional
-- | This resource represents a long-running operation that is the result of a network API call.
--
-- /See:/ 'newOperation' smart constructor.
data Operation = Operation
| If the value is @false@ , it means the operation is still in progress . If @true@ , the operation is completed , and either @error@ or @response@ is available .
done :: (Core.Maybe Core.Bool),
-- | The error result of the operation in case of failure or cancellation.
error :: (Core.Maybe Status),
-- | Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
metadata :: (Core.Maybe Operation_Metadata),
| The server - assigned name , which is only unique within the same service that originally returns it . If you use the default HTTP mapping , the @name@ should be a resource name ending with
name :: (Core.Maybe Core.Text),
| The normal response of the operation in case of success . If the original method returns no data on success , such as @Delete@ , the response is @google.protobuf . Empty@. If the original method is standard @Get@\/@Create@\/@Update@ , the response should be the resource . For other methods , the response should have the type @XxxResponse@ , where @Xxx@ is the original method name . For example , if the original method name is , the inferred response type is @TakeSnapshotResponse@.
response :: (Core.Maybe Operation_Response)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Operation' with the minimum fields required to make a request.
newOperation ::
Operation
newOperation =
Operation
{ done = Core.Nothing,
error = Core.Nothing,
metadata = Core.Nothing,
name = Core.Nothing,
response = Core.Nothing
}
instance Core.FromJSON Operation where
parseJSON =
Core.withObject
"Operation"
( \o ->
Operation
Core.<$> (o Core..:? "done")
Core.<*> (o Core..:? "error")
Core.<*> (o Core..:? "metadata")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "response")
)
instance Core.ToJSON Operation where
toJSON Operation {..} =
Core.object
( Core.catMaybes
[ ("done" Core..=) Core.<$> done,
("error" Core..=) Core.<$> error,
("metadata" Core..=) Core.<$> metadata,
("name" Core..=) Core.<$> name,
("response" Core..=) Core.<$> response
]
)
-- | Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
--
-- /See:/ 'newOperation_Metadata' smart constructor.
newtype Operation_Metadata = Operation_Metadata
{ -- | Properties of the object. Contains field \@type with type URL.
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Operation_Metadata' with the minimum fields required to make a request.
newOperation_Metadata ::
-- | Properties of the object. Contains field \@type with type URL. See 'additional'.
Core.HashMap Core.Text Core.Value ->
Operation_Metadata
newOperation_Metadata additional = Operation_Metadata {additional = additional}
instance Core.FromJSON Operation_Metadata where
parseJSON =
Core.withObject
"Operation_Metadata"
( \o ->
Operation_Metadata Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Operation_Metadata where
toJSON Operation_Metadata {..} =
Core.toJSON additional
| The normal response of the operation in case of success . If the original method returns no data on success , such as @Delete@ , the response is @google.protobuf . Empty@. If the original method is standard @Get@\/@Create@\/@Update@ , the response should be the resource . For other methods , the response should have the type @XxxResponse@ , where @Xxx@ is the original method name . For example , if the original method name is , the inferred response type is @TakeSnapshotResponse@.
--
-- /See:/ 'newOperation_Response' smart constructor.
newtype Operation_Response = Operation_Response
{ -- | Properties of the object. Contains field \@type with type URL.
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Operation_Response' with the minimum fields required to make a request.
newOperation_Response ::
-- | Properties of the object. Contains field \@type with type URL. See 'additional'.
Core.HashMap Core.Text Core.Value ->
Operation_Response
newOperation_Response additional = Operation_Response {additional = additional}
instance Core.FromJSON Operation_Response where
parseJSON =
Core.withObject
"Operation_Response"
( \o ->
Operation_Response Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Operation_Response where
toJSON Operation_Response {..} =
Core.toJSON additional
-- | Metadata describing an Operation
--
/See:/ ' newOperationMetadata ' smart constructor .
data OperationMetadata = OperationMetadata
{ -- | API version.
apiVersion :: (Core.Maybe Core.Text),
-- | Specifies if cancellation was requested for the operation.
cancelRequested :: (Core.Maybe Core.Bool),
-- | The time the operation was created.
createTime :: (Core.Maybe Core.DateTime),
-- | The time the operation finished running.
endTime :: (Core.Maybe Core.DateTime),
-- | Human-readable status of the operation, if any.
statusDetail :: (Core.Maybe Core.Text),
-- | Target of the operation - for example projects\/project-1\/connectivityTests\/test-1
target :: (Core.Maybe Core.Text),
-- | Name of the verb executed by the operation.
verb :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' OperationMetadata ' with the minimum fields required to make a request .
newOperationMetadata ::
OperationMetadata
newOperationMetadata =
OperationMetadata
{ apiVersion = Core.Nothing,
cancelRequested = Core.Nothing,
createTime = Core.Nothing,
endTime = Core.Nothing,
statusDetail = Core.Nothing,
target = Core.Nothing,
verb = Core.Nothing
}
instance Core.FromJSON OperationMetadata where
parseJSON =
Core.withObject
"OperationMetadata"
( \o ->
OperationMetadata
Core.<$> (o Core..:? "apiVersion")
Core.<*> (o Core..:? "cancelRequested")
Core.<*> (o Core..:? "createTime")
Core.<*> (o Core..:? "endTime")
Core.<*> (o Core..:? "statusDetail")
Core.<*> (o Core..:? "target")
Core.<*> (o Core..:? "verb")
)
instance Core.ToJSON OperationMetadata where
toJSON OperationMetadata {..} =
Core.object
( Core.catMaybes
[ ("apiVersion" Core..=) Core.<$> apiVersion,
("cancelRequested" Core..=) Core.<$> cancelRequested,
("createTime" Core..=) Core.<$> createTime,
("endTime" Core..=) Core.<$> endTime,
("statusDetail" Core..=) Core.<$> statusDetail,
("target" Core..=) Core.<$> target,
("verb" Core..=) Core.<$> verb
]
)
-- | A runtime version that a Node can be configured with.
--
-- /See:/ 'newRuntimeVersion' smart constructor.
data RuntimeVersion = RuntimeVersion
{ -- | The resource name.
name :: (Core.Maybe Core.Text),
-- | The runtime version.
version :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'RuntimeVersion' with the minimum fields required to make a request.
newRuntimeVersion ::
RuntimeVersion
newRuntimeVersion = RuntimeVersion {name = Core.Nothing, version = Core.Nothing}
instance Core.FromJSON RuntimeVersion where
parseJSON =
Core.withObject
"RuntimeVersion"
( \o ->
RuntimeVersion
Core.<$> (o Core..:? "name") Core.<*> (o Core..:? "version")
)
instance Core.ToJSON RuntimeVersion where
toJSON RuntimeVersion {..} =
Core.object
( Core.catMaybes
[ ("name" Core..=) Core.<$> name,
("version" Core..=) Core.<$> version
]
)
-- | Sets the scheduling options for this node.
--
-- /See:/ 'newSchedulingConfig' smart constructor.
data SchedulingConfig = SchedulingConfig
{ -- | Defines whether the node is preemptible.
preemptible :: (Core.Maybe Core.Bool),
-- | Whether the node is created under a reservation.
reserved :: (Core.Maybe Core.Bool)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ' with the minimum fields required to make a request .
newSchedulingConfig ::
SchedulingConfig
newSchedulingConfig =
SchedulingConfig {preemptible = Core.Nothing, reserved = Core.Nothing}
instance Core.FromJSON SchedulingConfig where
parseJSON =
Core.withObject
"SchedulingConfig"
( \o ->
SchedulingConfig
Core.<$> (o Core..:? "preemptible")
Core.<*> (o Core..:? "reserved")
)
instance Core.ToJSON SchedulingConfig where
toJSON SchedulingConfig {..} =
Core.object
( Core.catMaybes
[ ("preemptible" Core..=) Core.<$> preemptible,
("reserved" Core..=) Core.<$> reserved
]
)
-- | A service account.
--
/See:/ ' newServiceAccount ' smart constructor .
data ServiceAccount = ServiceAccount
{ -- | Email address of the service account. If empty, default Compute service account will be used.
email :: (Core.Maybe Core.Text),
-- | The list of scopes to be made available for this service account. If empty, access to all Cloud APIs will be allowed.
scope :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ServiceAccount' with the minimum fields required to make a request.
newServiceAccount ::
ServiceAccount
newServiceAccount = ServiceAccount {email = Core.Nothing, scope = Core.Nothing}
instance Core.FromJSON ServiceAccount where
parseJSON =
Core.withObject
"ServiceAccount"
( \o ->
ServiceAccount
Core.<$> (o Core..:? "email") Core.<*> (o Core..:? "scope")
)
instance Core.ToJSON ServiceAccount where
toJSON ServiceAccount {..} =
Core.object
( Core.catMaybes
[ ("email" Core..=) Core.<$> email,
("scope" Core..=) Core.<$> scope
]
)
-- | The per-product per-project service identity for Cloud TPU service.
--
-- /See:/ 'newServiceIdentity' smart constructor.
newtype ServiceIdentity = ServiceIdentity
{ -- | The email address of the service identity.
email :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ServiceIdentity' with the minimum fields required to make a request.
newServiceIdentity ::
ServiceIdentity
newServiceIdentity = ServiceIdentity {email = Core.Nothing}
instance Core.FromJSON ServiceIdentity where
parseJSON =
Core.withObject
"ServiceIdentity"
( \o ->
ServiceIdentity Core.<$> (o Core..:? "email")
)
instance Core.ToJSON ServiceIdentity where
toJSON ServiceIdentity {..} =
Core.object
(Core.catMaybes [("email" Core..=) Core.<$> email])
| Request for StartNode .
--
-- /See:/ 'newStartNodeRequest' smart constructor.
data StartNodeRequest = StartNodeRequest
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'StartNodeRequest' with the minimum fields required to make a request.
newStartNodeRequest ::
StartNodeRequest
newStartNodeRequest = StartNodeRequest
instance Core.FromJSON StartNodeRequest where
parseJSON =
Core.withObject
"StartNodeRequest"
(\o -> Core.pure StartNodeRequest)
instance Core.ToJSON StartNodeRequest where
toJSON = Core.const Core.emptyObject
| The @Status@ type defines a logical error model that is suitable for different programming environments , including REST APIs and RPC APIs . It is used by < > . Each @Status@ message contains three pieces of data : error code , error message , and error details . You can find out more about this error model and how to work with it in the < API Design Guide > .
--
/See:/ ' newStatus ' smart constructor .
data Status = Status
{ -- | The status code, which should be an enum value of google.rpc.Code.
code :: (Core.Maybe Core.Int32),
-- | A list of messages that carry the error details. There is a common set of message types for APIs to use.
details :: (Core.Maybe [Status_DetailsItem]),
| A developer - facing error message , which should be in English . Any user - facing error message should be localized and sent in the google.rpc.Status.details field , or localized by the client .
message :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Status' with the minimum fields required to make a request.
newStatus ::
Status
newStatus =
Status {code = Core.Nothing, details = Core.Nothing, message = Core.Nothing}
instance Core.FromJSON Status where
parseJSON =
Core.withObject
"Status"
( \o ->
Status
Core.<$> (o Core..:? "code")
Core.<*> (o Core..:? "details")
Core.<*> (o Core..:? "message")
)
instance Core.ToJSON Status where
toJSON Status {..} =
Core.object
( Core.catMaybes
[ ("code" Core..=) Core.<$> code,
("details" Core..=) Core.<$> details,
("message" Core..=) Core.<$> message
]
)
--
-- /See:/ 'newStatus_DetailsItem' smart constructor.
newtype Status_DetailsItem = Status_DetailsItem
{ -- | Properties of the object. Contains field \@type with type URL.
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Status_DetailsItem' with the minimum fields required to make a request.
newStatus_DetailsItem ::
-- | Properties of the object. Contains field \@type with type URL. See 'additional'.
Core.HashMap Core.Text Core.Value ->
Status_DetailsItem
newStatus_DetailsItem additional = Status_DetailsItem {additional = additional}
instance Core.FromJSON Status_DetailsItem where
parseJSON =
Core.withObject
"Status_DetailsItem"
( \o ->
Status_DetailsItem Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Status_DetailsItem where
toJSON Status_DetailsItem {..} =
Core.toJSON additional
| Request for StopNode .
--
-- /See:/ 'newStopNodeRequest' smart constructor.
data StopNodeRequest = StopNodeRequest
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'StopNodeRequest' with the minimum fields required to make a request.
newStopNodeRequest ::
StopNodeRequest
newStopNodeRequest = StopNodeRequest
instance Core.FromJSON StopNodeRequest where
parseJSON =
Core.withObject
"StopNodeRequest"
(\o -> Core.pure StopNodeRequest)
instance Core.ToJSON StopNodeRequest where
toJSON = Core.const Core.emptyObject
-- | A Symptom instance.
--
/See:/ ' ' smart constructor .
data Symptom = Symptom
{ -- | Timestamp when the Symptom is created.
createTime :: (Core.Maybe Core.DateTime),
-- | Detailed information of the current Symptom.
details :: (Core.Maybe Core.Text),
-- | Type of the Symptom.
symptomType :: (Core.Maybe Symptom_SymptomType),
| A string used to uniquely distinguish a worker within a TPU node .
workerId :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Symptom' with the minimum fields required to make a request.
newSymptom ::
Symptom
newSymptom =
Symptom
{ createTime = Core.Nothing,
details = Core.Nothing,
symptomType = Core.Nothing,
workerId = Core.Nothing
}
instance Core.FromJSON Symptom where
parseJSON =
Core.withObject
"Symptom"
( \o ->
Symptom
Core.<$> (o Core..:? "createTime")
Core.<*> (o Core..:? "details")
Core.<*> (o Core..:? "symptomType")
Core.<*> (o Core..:? "workerId")
)
instance Core.ToJSON Symptom where
toJSON Symptom {..} =
Core.object
( Core.catMaybes
[ ("createTime" Core..=) Core.<$> createTime,
("details" Core..=) Core.<$> details,
("symptomType" Core..=) Core.<$> symptomType,
("workerId" Core..=) Core.<$> workerId
]
)
| null |
https://raw.githubusercontent.com/brendanhay/gogol/8cbceeaaba36a3c08712b2e272606161500fbe91/lib/services/gogol-tpu/gen/Gogol/TPU/Internal/Product.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
* Empty
* GenerateServiceIdentityRequest
* GenerateServiceIdentityResponse
* GetGuestAttributesRequest
* GetGuestAttributesResponse
* GuestAttributesEntry
* GuestAttributesValue
* ListAcceleratorTypesResponse
* ListNodesResponse
* ListOperationsResponse
* ListRuntimeVersionsResponse
* Location
* Location_Labels
* Location_Metadata
* Node
* Node_Labels
* Node_Metadata
* Operation
* Operation_Metadata
* Operation_Response
* OperationMetadata
* RuntimeVersion
* ServiceAccount
* ServiceIdentity
* StartNodeRequest
* Status
* Status_DetailsItem
* StopNodeRequest
* Symptom
| A accelerator type that a Node can be configured with.
/See:/ 'newAcceleratorType' smart constructor.
| The resource name.
| the accelerator type.
/See:/ 'newAccessConfig' smart constructor.
| Creates a value of 'AccessConfig' with the minimum fields required to make a request.
/See:/ 'newAttachedDisk' smart constructor.
| The mode in which to attach this disk. If not specified, the default is READ/WRITE mode. Only applicable to data/disks.
| Specifies the full path to an existing disk. For example: \"projects\/my-project\/zones\/us-central1-c\/disks\/my-disk\".
| Creates a value of 'Empty' with the minimum fields required to make a request.
| Request for GenerateServiceIdentity.
/See:/ 'newGenerateServiceIdentityRequest' smart constructor.
| Creates a value of 'GenerateServiceIdentityRequest' with the minimum fields required to make a request.
| Response for GenerateServiceIdentity.
/See:/ 'newGenerateServiceIdentityResponse' smart constructor.
| Creates a value of 'GenerateServiceIdentityResponse' with the minimum fields required to make a request.
| Request for GetGuestAttributes.
/See:/ 'newGetGuestAttributesRequest' smart constructor.
| The guest attributes path to be queried.
| Creates a value of 'GetGuestAttributesRequest' with the minimum fields required to make a request.
| Response for GetGuestAttributes.
/See:/ 'newGetGuestAttributesResponse' smart constructor.
| Creates a value of 'GetGuestAttributesResponse' with the minimum fields required to make a request.
| A guest attributes.
/See:/ 'newGuestAttributes' smart constructor.
| The path to be queried. This can be the default namespace (\'\/\') or a nested namespace (\'\/\\\/\') or a specified key (\'\/\\\/\\\')
| The value of the requested queried path.
| A guest attributes namespace\/key\/value entry.
/See:/ 'newGuestAttributesEntry' smart constructor.
| Key for the guest attribute entry.
| Namespace for the guest attribute entry.
| Value for the guest attribute entry.
| Creates a value of 'GuestAttributesEntry' with the minimum fields required to make a request.
| Array of guest attribute namespace\/key\/value tuples.
/See:/ 'newGuestAttributesValue' smart constructor.
| The list of guest attributes entries.
| Creates a value of 'GuestAttributesValue' with the minimum fields required to make a request.
| Response for ListAcceleratorTypes.
/See:/ 'newListAcceleratorTypesResponse' smart constructor.
| The listed nodes.
| The next page token or empty if none.
| Locations that could not be reached.
| Creates a value of 'ListAcceleratorTypesResponse' with the minimum fields required to make a request.
| The response message for Locations.ListLocations.
/See:/ 'newListLocationsResponse' smart constructor.
| A list of locations that matches the specified filter in the request.
| The standard List next-page token.
/See:/ 'newListNodesResponse' smart constructor.
| The next page token or empty if none.
| The listed nodes.
| Locations that could not be reached.
/See:/ 'newListOperationsResponse' smart constructor.
| The standard List next-page token.
| A list of operations that matches the specified filter in the request.
| Creates a value of 'ListOperationsResponse' with the minimum fields required to make a request.
| Response for ListRuntimeVersions.
/See:/ 'newListRuntimeVersionsResponse' smart constructor.
| The next page token or empty if none.
| The listed nodes.
| Locations that could not be reached.
| Creates a value of 'ListRuntimeVersionsResponse' with the minimum fields required to make a request.
| The friendly name for this location, typically a nearby city name. For example, \"Tokyo\".
| Cross-service attributes for the location. For example {\"cloud.googleapis.com\/region\": \"us-east1\"}
| Service-specific metadata. For example the available capacity at the given location.
| Resource name for the location, which may vary between implementations. For example: @\"projects\/example-project\/locations\/us-east1\"@
| Creates a value of 'Location' with the minimum fields required to make a request.
| Cross-service attributes for the location. For example {\"cloud.googleapis.com\/region\": \"us-east1\"}
/See:/ 'newLocation_Labels' smart constructor.
|
| Creates a value of 'Location_Labels' with the minimum fields required to make a request.
| See 'additional'.
| Service-specific metadata. For example the available capacity at the given location.
/See:/ 'newLocation_Metadata' smart constructor.
| Properties of the object. Contains field \@type with type URL.
| Creates a value of 'Location_Metadata' with the minimum fields required to make a request.
| Properties of the object. Contains field \@type with type URL. See 'additional'.
| Network related configurations.
/See:/ 'newNetworkConfig' smart constructor.
| The internal IP address of this network endpoint.
| The port of this network endpoint.
| A TPU instance.
/See:/ 'newNode' smart constructor.
| Required. The type of hardware accelerators associated with this node.
| Output only. The API version that created this Node.
| Output only. The time when the node was created.
| Output only. If this field is populated, it contains a description of why the TPU Node is unhealthy.
| Output only. The unique identifier for the TPU Node.
| Resource labels to represent user-provided metadata.
| Custom metadata to apply to the TPU Node. Can set startup-script and shutdown-script
| The scheduling options for this node.
| Output only. The current state for the TPU Node.
| Output only. The Symptoms that have occurred to the TPU Node.
| Tags to apply to the TPU Node. Tags are used to identify valid sources or targets for network firewalls.
| Creates a value of 'Node' with the minimum fields required to make a request.
| Resource labels to represent user-provided metadata.
/See:/ 'newNode_Labels' smart constructor.
|
| Creates a value of 'Node_Labels' with the minimum fields required to make a request.
| See 'additional'.
| Custom metadata to apply to the TPU Node. Can set startup-script and shutdown-script
/See:/ 'newNode_Metadata' smart constructor.
|
| Creates a value of 'Node_Metadata' with the minimum fields required to make a request.
| See 'additional'.
| This resource represents a long-running operation that is the result of a network API call.
/See:/ 'newOperation' smart constructor.
| The error result of the operation in case of failure or cancellation.
| Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
| Creates a value of 'Operation' with the minimum fields required to make a request.
| Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
/See:/ 'newOperation_Metadata' smart constructor.
| Properties of the object. Contains field \@type with type URL.
| Creates a value of 'Operation_Metadata' with the minimum fields required to make a request.
| Properties of the object. Contains field \@type with type URL. See 'additional'.
/See:/ 'newOperation_Response' smart constructor.
| Properties of the object. Contains field \@type with type URL.
| Creates a value of 'Operation_Response' with the minimum fields required to make a request.
| Properties of the object. Contains field \@type with type URL. See 'additional'.
| Metadata describing an Operation
| API version.
| Specifies if cancellation was requested for the operation.
| The time the operation was created.
| The time the operation finished running.
| Human-readable status of the operation, if any.
| Target of the operation - for example projects\/project-1\/connectivityTests\/test-1
| Name of the verb executed by the operation.
| A runtime version that a Node can be configured with.
/See:/ 'newRuntimeVersion' smart constructor.
| The resource name.
| The runtime version.
| Creates a value of 'RuntimeVersion' with the minimum fields required to make a request.
| Sets the scheduling options for this node.
/See:/ 'newSchedulingConfig' smart constructor.
| Defines whether the node is preemptible.
| Whether the node is created under a reservation.
| A service account.
| Email address of the service account. If empty, default Compute service account will be used.
| The list of scopes to be made available for this service account. If empty, access to all Cloud APIs will be allowed.
| Creates a value of 'ServiceAccount' with the minimum fields required to make a request.
| The per-product per-project service identity for Cloud TPU service.
/See:/ 'newServiceIdentity' smart constructor.
| The email address of the service identity.
| Creates a value of 'ServiceIdentity' with the minimum fields required to make a request.
/See:/ 'newStartNodeRequest' smart constructor.
| Creates a value of 'StartNodeRequest' with the minimum fields required to make a request.
| The status code, which should be an enum value of google.rpc.Code.
| A list of messages that carry the error details. There is a common set of message types for APIs to use.
| Creates a value of 'Status' with the minimum fields required to make a request.
/See:/ 'newStatus_DetailsItem' smart constructor.
| Properties of the object. Contains field \@type with type URL.
| Creates a value of 'Status_DetailsItem' with the minimum fields required to make a request.
| Properties of the object. Contains field \@type with type URL. See 'additional'.
/See:/ 'newStopNodeRequest' smart constructor.
| Creates a value of 'StopNodeRequest' with the minimum fields required to make a request.
| A Symptom instance.
| Timestamp when the Symptom is created.
| Detailed information of the current Symptom.
| Type of the Symptom.
| Creates a value of 'Symptom' with the minimum fields required to make a request.
|
# LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . TPU.Internal . Product
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Gogol.TPU.Internal.Product
* AcceleratorType
AcceleratorType (..),
newAcceleratorType,
*
AccessConfig (..),
newAccessConfig,
* AttachedDisk
AttachedDisk (..),
newAttachedDisk,
Empty (..),
newEmpty,
GenerateServiceIdentityRequest (..),
newGenerateServiceIdentityRequest,
GenerateServiceIdentityResponse (..),
newGenerateServiceIdentityResponse,
GetGuestAttributesRequest (..),
newGetGuestAttributesRequest,
GetGuestAttributesResponse (..),
newGetGuestAttributesResponse,
* GuestAttributes
GuestAttributes (..),
newGuestAttributes,
GuestAttributesEntry (..),
newGuestAttributesEntry,
GuestAttributesValue (..),
newGuestAttributesValue,
ListAcceleratorTypesResponse (..),
newListAcceleratorTypesResponse,
* ListLocationsResponse
ListLocationsResponse (..),
newListLocationsResponse,
ListNodesResponse (..),
newListNodesResponse,
ListOperationsResponse (..),
newListOperationsResponse,
ListRuntimeVersionsResponse (..),
newListRuntimeVersionsResponse,
Location (..),
newLocation,
Location_Labels (..),
newLocation_Labels,
Location_Metadata (..),
newLocation_Metadata,
* NetworkConfig
NetworkConfig (..),
newNetworkConfig,
* NetworkEndpoint
NetworkEndpoint (..),
newNetworkEndpoint,
Node (..),
newNode,
Node_Labels (..),
newNode_Labels,
Node_Metadata (..),
newNode_Metadata,
Operation (..),
newOperation,
Operation_Metadata (..),
newOperation_Metadata,
Operation_Response (..),
newOperation_Response,
OperationMetadata (..),
newOperationMetadata,
RuntimeVersion (..),
newRuntimeVersion,
*
SchedulingConfig (..),
newSchedulingConfig,
ServiceAccount (..),
newServiceAccount,
ServiceIdentity (..),
newServiceIdentity,
StartNodeRequest (..),
newStartNodeRequest,
Status (..),
newStatus,
Status_DetailsItem (..),
newStatus_DetailsItem,
StopNodeRequest (..),
newStopNodeRequest,
Symptom (..),
newSymptom,
)
where
import qualified Gogol.Prelude as Core
import Gogol.TPU.Internal.Sum
data AcceleratorType = AcceleratorType
name :: (Core.Maybe Core.Text),
type' :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' AcceleratorType ' with the minimum fields required to make a request .
newAcceleratorType ::
AcceleratorType
newAcceleratorType = AcceleratorType {name = Core.Nothing, type' = Core.Nothing}
instance Core.FromJSON AcceleratorType where
parseJSON =
Core.withObject
"AcceleratorType"
( \o ->
AcceleratorType
Core.<$> (o Core..:? "name") Core.<*> (o Core..:? "type")
)
instance Core.ToJSON AcceleratorType where
toJSON AcceleratorType {..} =
Core.object
( Core.catMaybes
[ ("name" Core..=) Core.<$> name,
("type" Core..=) Core.<$> type'
]
)
| An access config attached to the TPU worker .
newtype AccessConfig = AccessConfig
| Output only . An external IP address associated with the TPU worker .
externalIp :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newAccessConfig ::
AccessConfig
newAccessConfig = AccessConfig {externalIp = Core.Nothing}
instance Core.FromJSON AccessConfig where
parseJSON =
Core.withObject
"AccessConfig"
( \o ->
AccessConfig Core.<$> (o Core..:? "externalIp")
)
instance Core.ToJSON AccessConfig where
toJSON AccessConfig {..} =
Core.object
( Core.catMaybes
[("externalIp" Core..=) Core.<$> externalIp]
)
| A node - attached disk resource . Next ID : 8 ;
data AttachedDisk = AttachedDisk
mode :: (Core.Maybe AttachedDisk_Mode),
sourceDisk :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' AttachedDisk ' with the minimum fields required to make a request .
newAttachedDisk ::
AttachedDisk
newAttachedDisk = AttachedDisk {mode = Core.Nothing, sourceDisk = Core.Nothing}
instance Core.FromJSON AttachedDisk where
parseJSON =
Core.withObject
"AttachedDisk"
( \o ->
AttachedDisk
Core.<$> (o Core..:? "mode")
Core.<*> (o Core..:? "sourceDisk")
)
instance Core.ToJSON AttachedDisk where
toJSON AttachedDisk {..} =
Core.object
( Core.catMaybes
[ ("mode" Core..=) Core.<$> mode,
("sourceDisk" Core..=) Core.<$> sourceDisk
]
)
| A generic empty message that you can re - use to avoid defining duplicated empty messages in your APIs . A typical example is to use it as the request or the response type of an API method . For instance : service Foo { rpc Bar(google.protobuf . Empty ) returns ( google.protobuf . Empty ) ; } The JSON representation for @Empty@ is empty JSON object @{}@.
/See:/ ' ' smart constructor .
data Empty = Empty
deriving (Core.Eq, Core.Show, Core.Generic)
newEmpty ::
Empty
newEmpty = Empty
instance Core.FromJSON Empty where
parseJSON =
Core.withObject "Empty" (\o -> Core.pure Empty)
instance Core.ToJSON Empty where
toJSON = Core.const Core.emptyObject
data GenerateServiceIdentityRequest = GenerateServiceIdentityRequest
deriving (Core.Eq, Core.Show, Core.Generic)
newGenerateServiceIdentityRequest ::
GenerateServiceIdentityRequest
newGenerateServiceIdentityRequest = GenerateServiceIdentityRequest
instance Core.FromJSON GenerateServiceIdentityRequest where
parseJSON =
Core.withObject
"GenerateServiceIdentityRequest"
(\o -> Core.pure GenerateServiceIdentityRequest)
instance Core.ToJSON GenerateServiceIdentityRequest where
toJSON = Core.const Core.emptyObject
newtype GenerateServiceIdentityResponse = GenerateServiceIdentityResponse
| ServiceIdentity that was created or retrieved .
identity :: (Core.Maybe ServiceIdentity)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGenerateServiceIdentityResponse ::
GenerateServiceIdentityResponse
newGenerateServiceIdentityResponse =
GenerateServiceIdentityResponse {identity = Core.Nothing}
instance
Core.FromJSON
GenerateServiceIdentityResponse
where
parseJSON =
Core.withObject
"GenerateServiceIdentityResponse"
( \o ->
GenerateServiceIdentityResponse
Core.<$> (o Core..:? "identity")
)
instance Core.ToJSON GenerateServiceIdentityResponse where
toJSON GenerateServiceIdentityResponse {..} =
Core.object
( Core.catMaybes
[("identity" Core..=) Core.<$> identity]
)
data GetGuestAttributesRequest = GetGuestAttributesRequest
queryPath :: (Core.Maybe Core.Text),
| The 0 - based worker ID . If it is empty , all workers\ ' GuestAttributes will be returned .
workerIds :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGetGuestAttributesRequest ::
GetGuestAttributesRequest
newGetGuestAttributesRequest =
GetGuestAttributesRequest {queryPath = Core.Nothing, workerIds = Core.Nothing}
instance Core.FromJSON GetGuestAttributesRequest where
parseJSON =
Core.withObject
"GetGuestAttributesRequest"
( \o ->
GetGuestAttributesRequest
Core.<$> (o Core..:? "queryPath")
Core.<*> (o Core..:? "workerIds")
)
instance Core.ToJSON GetGuestAttributesRequest where
toJSON GetGuestAttributesRequest {..} =
Core.object
( Core.catMaybes
[ ("queryPath" Core..=) Core.<$> queryPath,
("workerIds" Core..=) Core.<$> workerIds
]
)
newtype GetGuestAttributesResponse = GetGuestAttributesResponse
| The guest attributes for the TPU workers .
guestAttributes :: (Core.Maybe [GuestAttributes])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGetGuestAttributesResponse ::
GetGuestAttributesResponse
newGetGuestAttributesResponse =
GetGuestAttributesResponse {guestAttributes = Core.Nothing}
instance Core.FromJSON GetGuestAttributesResponse where
parseJSON =
Core.withObject
"GetGuestAttributesResponse"
( \o ->
GetGuestAttributesResponse
Core.<$> (o Core..:? "guestAttributes")
)
instance Core.ToJSON GetGuestAttributesResponse where
toJSON GetGuestAttributesResponse {..} =
Core.object
( Core.catMaybes
[ ("guestAttributes" Core..=)
Core.<$> guestAttributes
]
)
data GuestAttributes = GuestAttributes
queryPath :: (Core.Maybe Core.Text),
queryValue :: (Core.Maybe GuestAttributesValue)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' GuestAttributes ' with the minimum fields required to make a request .
newGuestAttributes ::
GuestAttributes
newGuestAttributes =
GuestAttributes {queryPath = Core.Nothing, queryValue = Core.Nothing}
instance Core.FromJSON GuestAttributes where
parseJSON =
Core.withObject
"GuestAttributes"
( \o ->
GuestAttributes
Core.<$> (o Core..:? "queryPath")
Core.<*> (o Core..:? "queryValue")
)
instance Core.ToJSON GuestAttributes where
toJSON GuestAttributes {..} =
Core.object
( Core.catMaybes
[ ("queryPath" Core..=) Core.<$> queryPath,
("queryValue" Core..=) Core.<$> queryValue
]
)
data GuestAttributesEntry = GuestAttributesEntry
key :: (Core.Maybe Core.Text),
namespace :: (Core.Maybe Core.Text),
value :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGuestAttributesEntry ::
GuestAttributesEntry
newGuestAttributesEntry =
GuestAttributesEntry
{ key = Core.Nothing,
namespace = Core.Nothing,
value = Core.Nothing
}
instance Core.FromJSON GuestAttributesEntry where
parseJSON =
Core.withObject
"GuestAttributesEntry"
( \o ->
GuestAttributesEntry
Core.<$> (o Core..:? "key")
Core.<*> (o Core..:? "namespace")
Core.<*> (o Core..:? "value")
)
instance Core.ToJSON GuestAttributesEntry where
toJSON GuestAttributesEntry {..} =
Core.object
( Core.catMaybes
[ ("key" Core..=) Core.<$> key,
("namespace" Core..=) Core.<$> namespace,
("value" Core..=) Core.<$> value
]
)
newtype GuestAttributesValue = GuestAttributesValue
items :: (Core.Maybe [GuestAttributesEntry])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGuestAttributesValue ::
GuestAttributesValue
newGuestAttributesValue = GuestAttributesValue {items = Core.Nothing}
instance Core.FromJSON GuestAttributesValue where
parseJSON =
Core.withObject
"GuestAttributesValue"
( \o ->
GuestAttributesValue Core.<$> (o Core..:? "items")
)
instance Core.ToJSON GuestAttributesValue where
toJSON GuestAttributesValue {..} =
Core.object
(Core.catMaybes [("items" Core..=) Core.<$> items])
data ListAcceleratorTypesResponse = ListAcceleratorTypesResponse
acceleratorTypes :: (Core.Maybe [AcceleratorType]),
nextPageToken :: (Core.Maybe Core.Text),
unreachable :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newListAcceleratorTypesResponse ::
ListAcceleratorTypesResponse
newListAcceleratorTypesResponse =
ListAcceleratorTypesResponse
{ acceleratorTypes = Core.Nothing,
nextPageToken = Core.Nothing,
unreachable = Core.Nothing
}
instance Core.FromJSON ListAcceleratorTypesResponse where
parseJSON =
Core.withObject
"ListAcceleratorTypesResponse"
( \o ->
ListAcceleratorTypesResponse
Core.<$> (o Core..:? "acceleratorTypes")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "unreachable")
)
instance Core.ToJSON ListAcceleratorTypesResponse where
toJSON ListAcceleratorTypesResponse {..} =
Core.object
( Core.catMaybes
[ ("acceleratorTypes" Core..=)
Core.<$> acceleratorTypes,
("nextPageToken" Core..=) Core.<$> nextPageToken,
("unreachable" Core..=) Core.<$> unreachable
]
)
data ListLocationsResponse = ListLocationsResponse
locations :: (Core.Maybe [Location]),
nextPageToken :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ListLocationsResponse ' with the minimum fields required to make a request .
newListLocationsResponse ::
ListLocationsResponse
newListLocationsResponse =
ListLocationsResponse {locations = Core.Nothing, nextPageToken = Core.Nothing}
instance Core.FromJSON ListLocationsResponse where
parseJSON =
Core.withObject
"ListLocationsResponse"
( \o ->
ListLocationsResponse
Core.<$> (o Core..:? "locations")
Core.<*> (o Core..:? "nextPageToken")
)
instance Core.ToJSON ListLocationsResponse where
toJSON ListLocationsResponse {..} =
Core.object
( Core.catMaybes
[ ("locations" Core..=) Core.<$> locations,
("nextPageToken" Core..=) Core.<$> nextPageToken
]
)
| Response for ListNodes .
data ListNodesResponse = ListNodesResponse
nextPageToken :: (Core.Maybe Core.Text),
nodes :: (Core.Maybe [Node]),
unreachable :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ListNodesResponse ' with the minimum fields required to make a request .
newListNodesResponse ::
ListNodesResponse
newListNodesResponse =
ListNodesResponse
{ nextPageToken = Core.Nothing,
nodes = Core.Nothing,
unreachable = Core.Nothing
}
instance Core.FromJSON ListNodesResponse where
parseJSON =
Core.withObject
"ListNodesResponse"
( \o ->
ListNodesResponse
Core.<$> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "nodes")
Core.<*> (o Core..:? "unreachable")
)
instance Core.ToJSON ListNodesResponse where
toJSON ListNodesResponse {..} =
Core.object
( Core.catMaybes
[ ("nextPageToken" Core..=) Core.<$> nextPageToken,
("nodes" Core..=) Core.<$> nodes,
("unreachable" Core..=) Core.<$> unreachable
]
)
| The response message for Operations . ListOperations .
data ListOperationsResponse = ListOperationsResponse
nextPageToken :: (Core.Maybe Core.Text),
operations :: (Core.Maybe [Operation])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newListOperationsResponse ::
ListOperationsResponse
newListOperationsResponse =
ListOperationsResponse
{ nextPageToken = Core.Nothing,
operations = Core.Nothing
}
instance Core.FromJSON ListOperationsResponse where
parseJSON =
Core.withObject
"ListOperationsResponse"
( \o ->
ListOperationsResponse
Core.<$> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "operations")
)
instance Core.ToJSON ListOperationsResponse where
toJSON ListOperationsResponse {..} =
Core.object
( Core.catMaybes
[ ("nextPageToken" Core..=) Core.<$> nextPageToken,
("operations" Core..=) Core.<$> operations
]
)
data ListRuntimeVersionsResponse = ListRuntimeVersionsResponse
nextPageToken :: (Core.Maybe Core.Text),
runtimeVersions :: (Core.Maybe [RuntimeVersion]),
unreachable :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newListRuntimeVersionsResponse ::
ListRuntimeVersionsResponse
newListRuntimeVersionsResponse =
ListRuntimeVersionsResponse
{ nextPageToken = Core.Nothing,
runtimeVersions = Core.Nothing,
unreachable = Core.Nothing
}
instance Core.FromJSON ListRuntimeVersionsResponse where
parseJSON =
Core.withObject
"ListRuntimeVersionsResponse"
( \o ->
ListRuntimeVersionsResponse
Core.<$> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "runtimeVersions")
Core.<*> (o Core..:? "unreachable")
)
instance Core.ToJSON ListRuntimeVersionsResponse where
toJSON ListRuntimeVersionsResponse {..} =
Core.object
( Core.catMaybes
[ ("nextPageToken" Core..=) Core.<$> nextPageToken,
("runtimeVersions" Core..=) Core.<$> runtimeVersions,
("unreachable" Core..=) Core.<$> unreachable
]
)
| A resource that represents Google Cloud Platform location .
/See:/ ' newLocation ' smart constructor .
data Location = Location
displayName :: (Core.Maybe Core.Text),
labels :: (Core.Maybe Location_Labels),
| The canonical i d for this location . For example : @\"us - east1\"@.
locationId :: (Core.Maybe Core.Text),
metadata :: (Core.Maybe Location_Metadata),
name :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newLocation ::
Location
newLocation =
Location
{ displayName = Core.Nothing,
labels = Core.Nothing,
locationId = Core.Nothing,
metadata = Core.Nothing,
name = Core.Nothing
}
instance Core.FromJSON Location where
parseJSON =
Core.withObject
"Location"
( \o ->
Location
Core.<$> (o Core..:? "displayName")
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "locationId")
Core.<*> (o Core..:? "metadata")
Core.<*> (o Core..:? "name")
)
instance Core.ToJSON Location where
toJSON Location {..} =
Core.object
( Core.catMaybes
[ ("displayName" Core..=) Core.<$> displayName,
("labels" Core..=) Core.<$> labels,
("locationId" Core..=) Core.<$> locationId,
("metadata" Core..=) Core.<$> metadata,
("name" Core..=) Core.<$> name
]
)
newtype Location_Labels = Location_Labels
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newLocation_Labels ::
Core.HashMap Core.Text Core.Text ->
Location_Labels
newLocation_Labels additional = Location_Labels {additional = additional}
instance Core.FromJSON Location_Labels where
parseJSON =
Core.withObject
"Location_Labels"
( \o ->
Location_Labels Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Location_Labels where
toJSON Location_Labels {..} = Core.toJSON additional
newtype Location_Metadata = Location_Metadata
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newLocation_Metadata ::
Core.HashMap Core.Text Core.Value ->
Location_Metadata
newLocation_Metadata additional = Location_Metadata {additional = additional}
instance Core.FromJSON Location_Metadata where
parseJSON =
Core.withObject
"Location_Metadata"
( \o ->
Location_Metadata Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Location_Metadata where
toJSON Location_Metadata {..} = Core.toJSON additional
data NetworkConfig = NetworkConfig
| Allows the TPU node to send and receive packets with non - matching destination or source IPs . This is required if you plan to use the TPU workers to forward routes .
canIpForward :: (Core.Maybe Core.Bool),
| Indicates that external IP addresses would be associated with the TPU workers . If set to false , the specified subnetwork or network should have Private Google Access enabled .
enableExternalIps :: (Core.Maybe Core.Bool),
| The name of the network for the TPU node . It must be a preexisting Google Compute Engine network . If none is provided , \"default\ " will be used .
network :: (Core.Maybe Core.Text),
| The name of the subnetwork for the TPU node . It must be a preexisting Google Compute Engine subnetwork . If none is provided , \"default\ " will be used .
subnetwork :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' NetworkConfig ' with the minimum fields required to make a request .
newNetworkConfig ::
NetworkConfig
newNetworkConfig =
NetworkConfig
{ canIpForward = Core.Nothing,
enableExternalIps = Core.Nothing,
network = Core.Nothing,
subnetwork = Core.Nothing
}
instance Core.FromJSON NetworkConfig where
parseJSON =
Core.withObject
"NetworkConfig"
( \o ->
NetworkConfig
Core.<$> (o Core..:? "canIpForward")
Core.<*> (o Core..:? "enableExternalIps")
Core.<*> (o Core..:? "network")
Core.<*> (o Core..:? "subnetwork")
)
instance Core.ToJSON NetworkConfig where
toJSON NetworkConfig {..} =
Core.object
( Core.catMaybes
[ ("canIpForward" Core..=) Core.<$> canIpForward,
("enableExternalIps" Core..=)
Core.<$> enableExternalIps,
("network" Core..=) Core.<$> network,
("subnetwork" Core..=) Core.<$> subnetwork
]
)
| A network endpoint over which a TPU worker can be reached .
/See:/ ' newNetworkEndpoint ' smart constructor .
data NetworkEndpoint = NetworkEndpoint
| The access config for the TPU worker .
accessConfig :: (Core.Maybe AccessConfig),
ipAddress :: (Core.Maybe Core.Text),
port :: (Core.Maybe Core.Int32)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' NetworkEndpoint ' with the minimum fields required to make a request .
newNetworkEndpoint ::
NetworkEndpoint
newNetworkEndpoint =
NetworkEndpoint
{ accessConfig = Core.Nothing,
ipAddress = Core.Nothing,
port = Core.Nothing
}
instance Core.FromJSON NetworkEndpoint where
parseJSON =
Core.withObject
"NetworkEndpoint"
( \o ->
NetworkEndpoint
Core.<$> (o Core..:? "accessConfig")
Core.<*> (o Core..:? "ipAddress")
Core.<*> (o Core..:? "port")
)
instance Core.ToJSON NetworkEndpoint where
toJSON NetworkEndpoint {..} =
Core.object
( Core.catMaybes
[ ("accessConfig" Core..=) Core.<$> accessConfig,
("ipAddress" Core..=) Core.<$> ipAddress,
("port" Core..=) Core.<$> port
]
)
data Node = Node
acceleratorType :: (Core.Maybe Core.Text),
apiVersion :: (Core.Maybe Node_ApiVersion),
| The CIDR block that the TPU node will use when selecting an IP address . This CIDR block must be a \/29 block ; the Compute Engine networks API forbids a smaller block , and using a larger block would be wasteful ( a node can only consume one IP address ) . Errors will occur if the CIDR block has already been used for a currently existing TPU node , the CIDR block conflicts with any subnetworks in the user\ 's provided network , or the provided network is peered with another network that is using that CIDR block .
cidrBlock :: (Core.Maybe Core.Text),
createTime :: (Core.Maybe Core.DateTime),
| The additional data disks for the Node .
dataDisks :: (Core.Maybe [AttachedDisk]),
| The user - supplied description of the TPU . Maximum of 512 characters .
description :: (Core.Maybe Core.Text),
| The health status of the TPU node .
health :: (Core.Maybe Node_Health),
healthDescription :: (Core.Maybe Core.Text),
id :: (Core.Maybe Core.Int64),
labels :: (Core.Maybe Node_Labels),
metadata :: (Core.Maybe Node_Metadata),
| Output only . Immutable . The name of the TPU .
name :: (Core.Maybe Core.Text),
| Network configurations for the TPU node .
networkConfig :: (Core.Maybe NetworkConfig),
| Output only . The network endpoints where TPU workers can be accessed and sent work . It is recommended that runtime clients of the node reach out to the 0th entry in this map first .
networkEndpoints :: (Core.Maybe [NetworkEndpoint]),
| Required . The runtime version running in the Node .
runtimeVersion :: (Core.Maybe Core.Text),
schedulingConfig :: (Core.Maybe SchedulingConfig),
| The Google Cloud Platform Service Account to be used by the TPU node VMs . If None is specified , the default compute service account will be used .
serviceAccount :: (Core.Maybe ServiceAccount),
state :: (Core.Maybe Node_State),
symptoms :: (Core.Maybe [Symptom]),
tags :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newNode ::
Node
newNode =
Node
{ acceleratorType = Core.Nothing,
apiVersion = Core.Nothing,
cidrBlock = Core.Nothing,
createTime = Core.Nothing,
dataDisks = Core.Nothing,
description = Core.Nothing,
health = Core.Nothing,
healthDescription = Core.Nothing,
id = Core.Nothing,
labels = Core.Nothing,
metadata = Core.Nothing,
name = Core.Nothing,
networkConfig = Core.Nothing,
networkEndpoints = Core.Nothing,
runtimeVersion = Core.Nothing,
schedulingConfig = Core.Nothing,
serviceAccount = Core.Nothing,
state = Core.Nothing,
symptoms = Core.Nothing,
tags = Core.Nothing
}
instance Core.FromJSON Node where
parseJSON =
Core.withObject
"Node"
( \o ->
Node
Core.<$> (o Core..:? "acceleratorType")
Core.<*> (o Core..:? "apiVersion")
Core.<*> (o Core..:? "cidrBlock")
Core.<*> (o Core..:? "createTime")
Core.<*> (o Core..:? "dataDisks")
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "health")
Core.<*> (o Core..:? "healthDescription")
Core.<*> (o Core..:? "id" Core.<&> Core.fmap Core.fromAsText)
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "metadata")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "networkConfig")
Core.<*> (o Core..:? "networkEndpoints")
Core.<*> (o Core..:? "runtimeVersion")
Core.<*> (o Core..:? "schedulingConfig")
Core.<*> (o Core..:? "serviceAccount")
Core.<*> (o Core..:? "state")
Core.<*> (o Core..:? "symptoms")
Core.<*> (o Core..:? "tags")
)
instance Core.ToJSON Node where
toJSON Node {..} =
Core.object
( Core.catMaybes
[ ("acceleratorType" Core..=)
Core.<$> acceleratorType,
("apiVersion" Core..=) Core.<$> apiVersion,
("cidrBlock" Core..=) Core.<$> cidrBlock,
("createTime" Core..=) Core.<$> createTime,
("dataDisks" Core..=) Core.<$> dataDisks,
("description" Core..=) Core.<$> description,
("health" Core..=) Core.<$> health,
("healthDescription" Core..=)
Core.<$> healthDescription,
("id" Core..=) Core.. Core.AsText Core.<$> id,
("labels" Core..=) Core.<$> labels,
("metadata" Core..=) Core.<$> metadata,
("name" Core..=) Core.<$> name,
("networkConfig" Core..=) Core.<$> networkConfig,
("networkEndpoints" Core..=)
Core.<$> networkEndpoints,
("runtimeVersion" Core..=) Core.<$> runtimeVersion,
("schedulingConfig" Core..=)
Core.<$> schedulingConfig,
("serviceAccount" Core..=) Core.<$> serviceAccount,
("state" Core..=) Core.<$> state,
("symptoms" Core..=) Core.<$> symptoms,
("tags" Core..=) Core.<$> tags
]
)
newtype Node_Labels = Node_Labels
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newNode_Labels ::
Core.HashMap Core.Text Core.Text ->
Node_Labels
newNode_Labels additional = Node_Labels {additional = additional}
instance Core.FromJSON Node_Labels where
parseJSON =
Core.withObject
"Node_Labels"
( \o ->
Node_Labels Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Node_Labels where
toJSON Node_Labels {..} = Core.toJSON additional
newtype Node_Metadata = Node_Metadata
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newNode_Metadata ::
Core.HashMap Core.Text Core.Text ->
Node_Metadata
newNode_Metadata additional = Node_Metadata {additional = additional}
instance Core.FromJSON Node_Metadata where
parseJSON =
Core.withObject
"Node_Metadata"
( \o ->
Node_Metadata Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Node_Metadata where
toJSON Node_Metadata {..} = Core.toJSON additional
data Operation = Operation
| If the value is @false@ , it means the operation is still in progress . If @true@ , the operation is completed , and either @error@ or @response@ is available .
done :: (Core.Maybe Core.Bool),
error :: (Core.Maybe Status),
metadata :: (Core.Maybe Operation_Metadata),
| The server - assigned name , which is only unique within the same service that originally returns it . If you use the default HTTP mapping , the @name@ should be a resource name ending with
name :: (Core.Maybe Core.Text),
| The normal response of the operation in case of success . If the original method returns no data on success , such as @Delete@ , the response is @google.protobuf . Empty@. If the original method is standard @Get@\/@Create@\/@Update@ , the response should be the resource . For other methods , the response should have the type @XxxResponse@ , where @Xxx@ is the original method name . For example , if the original method name is , the inferred response type is @TakeSnapshotResponse@.
response :: (Core.Maybe Operation_Response)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newOperation ::
Operation
newOperation =
Operation
{ done = Core.Nothing,
error = Core.Nothing,
metadata = Core.Nothing,
name = Core.Nothing,
response = Core.Nothing
}
instance Core.FromJSON Operation where
parseJSON =
Core.withObject
"Operation"
( \o ->
Operation
Core.<$> (o Core..:? "done")
Core.<*> (o Core..:? "error")
Core.<*> (o Core..:? "metadata")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "response")
)
instance Core.ToJSON Operation where
toJSON Operation {..} =
Core.object
( Core.catMaybes
[ ("done" Core..=) Core.<$> done,
("error" Core..=) Core.<$> error,
("metadata" Core..=) Core.<$> metadata,
("name" Core..=) Core.<$> name,
("response" Core..=) Core.<$> response
]
)
newtype Operation_Metadata = Operation_Metadata
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newOperation_Metadata ::
Core.HashMap Core.Text Core.Value ->
Operation_Metadata
newOperation_Metadata additional = Operation_Metadata {additional = additional}
instance Core.FromJSON Operation_Metadata where
parseJSON =
Core.withObject
"Operation_Metadata"
( \o ->
Operation_Metadata Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Operation_Metadata where
toJSON Operation_Metadata {..} =
Core.toJSON additional
| The normal response of the operation in case of success . If the original method returns no data on success , such as @Delete@ , the response is @google.protobuf . Empty@. If the original method is standard @Get@\/@Create@\/@Update@ , the response should be the resource . For other methods , the response should have the type @XxxResponse@ , where @Xxx@ is the original method name . For example , if the original method name is , the inferred response type is @TakeSnapshotResponse@.
newtype Operation_Response = Operation_Response
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newOperation_Response ::
Core.HashMap Core.Text Core.Value ->
Operation_Response
newOperation_Response additional = Operation_Response {additional = additional}
instance Core.FromJSON Operation_Response where
parseJSON =
Core.withObject
"Operation_Response"
( \o ->
Operation_Response Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Operation_Response where
toJSON Operation_Response {..} =
Core.toJSON additional
/See:/ ' newOperationMetadata ' smart constructor .
data OperationMetadata = OperationMetadata
apiVersion :: (Core.Maybe Core.Text),
cancelRequested :: (Core.Maybe Core.Bool),
createTime :: (Core.Maybe Core.DateTime),
endTime :: (Core.Maybe Core.DateTime),
statusDetail :: (Core.Maybe Core.Text),
target :: (Core.Maybe Core.Text),
verb :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' OperationMetadata ' with the minimum fields required to make a request .
newOperationMetadata ::
OperationMetadata
newOperationMetadata =
OperationMetadata
{ apiVersion = Core.Nothing,
cancelRequested = Core.Nothing,
createTime = Core.Nothing,
endTime = Core.Nothing,
statusDetail = Core.Nothing,
target = Core.Nothing,
verb = Core.Nothing
}
instance Core.FromJSON OperationMetadata where
parseJSON =
Core.withObject
"OperationMetadata"
( \o ->
OperationMetadata
Core.<$> (o Core..:? "apiVersion")
Core.<*> (o Core..:? "cancelRequested")
Core.<*> (o Core..:? "createTime")
Core.<*> (o Core..:? "endTime")
Core.<*> (o Core..:? "statusDetail")
Core.<*> (o Core..:? "target")
Core.<*> (o Core..:? "verb")
)
instance Core.ToJSON OperationMetadata where
toJSON OperationMetadata {..} =
Core.object
( Core.catMaybes
[ ("apiVersion" Core..=) Core.<$> apiVersion,
("cancelRequested" Core..=) Core.<$> cancelRequested,
("createTime" Core..=) Core.<$> createTime,
("endTime" Core..=) Core.<$> endTime,
("statusDetail" Core..=) Core.<$> statusDetail,
("target" Core..=) Core.<$> target,
("verb" Core..=) Core.<$> verb
]
)
data RuntimeVersion = RuntimeVersion
name :: (Core.Maybe Core.Text),
version :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newRuntimeVersion ::
RuntimeVersion
newRuntimeVersion = RuntimeVersion {name = Core.Nothing, version = Core.Nothing}
instance Core.FromJSON RuntimeVersion where
parseJSON =
Core.withObject
"RuntimeVersion"
( \o ->
RuntimeVersion
Core.<$> (o Core..:? "name") Core.<*> (o Core..:? "version")
)
instance Core.ToJSON RuntimeVersion where
toJSON RuntimeVersion {..} =
Core.object
( Core.catMaybes
[ ("name" Core..=) Core.<$> name,
("version" Core..=) Core.<$> version
]
)
data SchedulingConfig = SchedulingConfig
preemptible :: (Core.Maybe Core.Bool),
reserved :: (Core.Maybe Core.Bool)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ' with the minimum fields required to make a request .
newSchedulingConfig ::
SchedulingConfig
newSchedulingConfig =
SchedulingConfig {preemptible = Core.Nothing, reserved = Core.Nothing}
instance Core.FromJSON SchedulingConfig where
parseJSON =
Core.withObject
"SchedulingConfig"
( \o ->
SchedulingConfig
Core.<$> (o Core..:? "preemptible")
Core.<*> (o Core..:? "reserved")
)
instance Core.ToJSON SchedulingConfig where
toJSON SchedulingConfig {..} =
Core.object
( Core.catMaybes
[ ("preemptible" Core..=) Core.<$> preemptible,
("reserved" Core..=) Core.<$> reserved
]
)
/See:/ ' newServiceAccount ' smart constructor .
data ServiceAccount = ServiceAccount
email :: (Core.Maybe Core.Text),
scope :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newServiceAccount ::
ServiceAccount
newServiceAccount = ServiceAccount {email = Core.Nothing, scope = Core.Nothing}
instance Core.FromJSON ServiceAccount where
parseJSON =
Core.withObject
"ServiceAccount"
( \o ->
ServiceAccount
Core.<$> (o Core..:? "email") Core.<*> (o Core..:? "scope")
)
instance Core.ToJSON ServiceAccount where
toJSON ServiceAccount {..} =
Core.object
( Core.catMaybes
[ ("email" Core..=) Core.<$> email,
("scope" Core..=) Core.<$> scope
]
)
newtype ServiceIdentity = ServiceIdentity
email :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newServiceIdentity ::
ServiceIdentity
newServiceIdentity = ServiceIdentity {email = Core.Nothing}
instance Core.FromJSON ServiceIdentity where
parseJSON =
Core.withObject
"ServiceIdentity"
( \o ->
ServiceIdentity Core.<$> (o Core..:? "email")
)
instance Core.ToJSON ServiceIdentity where
toJSON ServiceIdentity {..} =
Core.object
(Core.catMaybes [("email" Core..=) Core.<$> email])
| Request for StartNode .
data StartNodeRequest = StartNodeRequest
deriving (Core.Eq, Core.Show, Core.Generic)
newStartNodeRequest ::
StartNodeRequest
newStartNodeRequest = StartNodeRequest
instance Core.FromJSON StartNodeRequest where
parseJSON =
Core.withObject
"StartNodeRequest"
(\o -> Core.pure StartNodeRequest)
instance Core.ToJSON StartNodeRequest where
toJSON = Core.const Core.emptyObject
| The @Status@ type defines a logical error model that is suitable for different programming environments , including REST APIs and RPC APIs . It is used by < > . Each @Status@ message contains three pieces of data : error code , error message , and error details . You can find out more about this error model and how to work with it in the < API Design Guide > .
/See:/ ' newStatus ' smart constructor .
data Status = Status
code :: (Core.Maybe Core.Int32),
details :: (Core.Maybe [Status_DetailsItem]),
| A developer - facing error message , which should be in English . Any user - facing error message should be localized and sent in the google.rpc.Status.details field , or localized by the client .
message :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newStatus ::
Status
newStatus =
Status {code = Core.Nothing, details = Core.Nothing, message = Core.Nothing}
instance Core.FromJSON Status where
parseJSON =
Core.withObject
"Status"
( \o ->
Status
Core.<$> (o Core..:? "code")
Core.<*> (o Core..:? "details")
Core.<*> (o Core..:? "message")
)
instance Core.ToJSON Status where
toJSON Status {..} =
Core.object
( Core.catMaybes
[ ("code" Core..=) Core.<$> code,
("details" Core..=) Core.<$> details,
("message" Core..=) Core.<$> message
]
)
newtype Status_DetailsItem = Status_DetailsItem
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newStatus_DetailsItem ::
Core.HashMap Core.Text Core.Value ->
Status_DetailsItem
newStatus_DetailsItem additional = Status_DetailsItem {additional = additional}
instance Core.FromJSON Status_DetailsItem where
parseJSON =
Core.withObject
"Status_DetailsItem"
( \o ->
Status_DetailsItem Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Status_DetailsItem where
toJSON Status_DetailsItem {..} =
Core.toJSON additional
| Request for StopNode .
data StopNodeRequest = StopNodeRequest
deriving (Core.Eq, Core.Show, Core.Generic)
newStopNodeRequest ::
StopNodeRequest
newStopNodeRequest = StopNodeRequest
instance Core.FromJSON StopNodeRequest where
parseJSON =
Core.withObject
"StopNodeRequest"
(\o -> Core.pure StopNodeRequest)
instance Core.ToJSON StopNodeRequest where
toJSON = Core.const Core.emptyObject
/See:/ ' ' smart constructor .
data Symptom = Symptom
createTime :: (Core.Maybe Core.DateTime),
details :: (Core.Maybe Core.Text),
symptomType :: (Core.Maybe Symptom_SymptomType),
| A string used to uniquely distinguish a worker within a TPU node .
workerId :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newSymptom ::
Symptom
newSymptom =
Symptom
{ createTime = Core.Nothing,
details = Core.Nothing,
symptomType = Core.Nothing,
workerId = Core.Nothing
}
instance Core.FromJSON Symptom where
parseJSON =
Core.withObject
"Symptom"
( \o ->
Symptom
Core.<$> (o Core..:? "createTime")
Core.<*> (o Core..:? "details")
Core.<*> (o Core..:? "symptomType")
Core.<*> (o Core..:? "workerId")
)
instance Core.ToJSON Symptom where
toJSON Symptom {..} =
Core.object
( Core.catMaybes
[ ("createTime" Core..=) Core.<$> createTime,
("details" Core..=) Core.<$> details,
("symptomType" Core..=) Core.<$> symptomType,
("workerId" Core..=) Core.<$> workerId
]
)
|
3bb300e4abd328f7407136e52966212802daf5d61def546d3797bdfc931339d3
|
justinethier/cyclone
|
bytevector-tests.scm
|
(import (scheme base) (scheme write))
(write #u8(1 2 3 4 5))
(write (make-bytevector 2 12)) ; =⇒ #u8(12 12)
= ⇒ # u8(1 3 5 1 3 5 )
= ⇒ # u8 ( )
(write (bytevector-append
(make-bytevector 1 1)
(make-bytevector 2 2)
(make-bytevector 3 3)
))
= ⇒ 8
(write
(let ((bv (bytevector 1 2 3 4)))
(bytevector-u8-set! bv 1 3)
bv)
= ⇒ # u8(1 3 3 4 )
TODO : does not work properly at the top - level
(let ((x 1))
(define a #u8(1 2 3 4 5))
(define b #(1 2 3 4 5))
= ⇒ # u8(3 4 )
(write b)
)
| null |
https://raw.githubusercontent.com/justinethier/cyclone/a1c2a8f282f37ce180a5921ae26a5deb04768269/tests/bytevector-tests.scm
|
scheme
|
=⇒ #u8(12 12)
|
(import (scheme base) (scheme write))
(write #u8(1 2 3 4 5))
= ⇒ # u8(1 3 5 1 3 5 )
= ⇒ # u8 ( )
(write (bytevector-append
(make-bytevector 1 1)
(make-bytevector 2 2)
(make-bytevector 3 3)
))
= ⇒ 8
(write
(let ((bv (bytevector 1 2 3 4)))
(bytevector-u8-set! bv 1 3)
bv)
= ⇒ # u8(1 3 3 4 )
TODO : does not work properly at the top - level
(let ((x 1))
(define a #u8(1 2 3 4 5))
(define b #(1 2 3 4 5))
= ⇒ # u8(3 4 )
(write b)
)
|
abd389f98c42e08421c54dcb6ee5b71a47bba21a5581a2813cfdc7a41355de88
|
CryptoKami/cryptokami-core
|
Genesis.hs
|
| Aeson instances for GenesisSpec and related datatypes .
module Pos.Aeson.Genesis
(
* FromJSONKey RedeemPublicKey
-- * FromJSON
-- ** GenesisAvvmBalances
-- ** GenesisWStakeholders
-- ** GenesisNonAvvmBalances
-- ** VssCertificatesMap
* * GenesisVssCertificatesMap
-- ** GenesisDelegation
-- ** FakeAvvmOptions
* * TestnetBalanceOptions
-- ** GenesisInitializer
-- ** ProtocolConstants
-- ** GenesisSpec
) where
import Universum
import Control.Lens (_Left)
import Data.Aeson (FromJSON (..), FromJSONKey (..), FromJSONKeyFunction (..))
import Data.Aeson.TH (deriveFromJSON)
import Serokell.Aeson.Options (defaultOptions)
import Pos.Aeson.Core ()
import Pos.Aeson.Crypto ()
import Pos.Binary.Core.Address ()
import Pos.Core.Common (StakeholderId)
import Pos.Core.Delegation.Types (ProxySKHeavy)
import Pos.Core.Genesis.Helpers (convertNonAvvmDataToBalances, recreateGenesisDelegation)
import Pos.Core.Genesis.Types (FakeAvvmOptions, GenesisAvvmBalances (..),
GenesisDelegation, GenesisInitializer,
GenesisNonAvvmBalances, GenesisSpec,
GenesisVssCertificatesMap (..), GenesisWStakeholders (..),
ProtocolConstants, TestnetBalanceOptions)
import Pos.Core.Ssc (VssCertificatesMap (..), validateVssCertificatesMap)
import Pos.Crypto (RedeemPublicKey, fromAvvmPk)
import Pos.Util.Util (toAesonError)
instance FromJSONKey RedeemPublicKey where
fromJSONKey = FromJSONKeyTextParser (toAesonError . over _Left pretty . fromAvvmPk)
fromJSONKeyList = FromJSONKeyTextParser (toAesonError . bimap pretty pure . fromAvvmPk)
deriving instance FromJSON GenesisAvvmBalances
deriving instance FromJSON GenesisWStakeholders
instance FromJSON GenesisNonAvvmBalances where
parseJSON = toAesonError . convertNonAvvmDataToBalances <=< parseJSON
instance FromJSON VssCertificatesMap where
parseJSON = parseJSON >=>
toAesonError . validateVssCertificatesMap . UnsafeVssCertificatesMap
instance FromJSON GenesisVssCertificatesMap where
parseJSON val = GenesisVssCertificatesMap <$> parseJSON val
instance FromJSON GenesisDelegation where
parseJSON = parseJSON >=> \v -> do
(elems :: HashMap StakeholderId ProxySKHeavy) <- mapM parseJSON v
toAesonError $ recreateGenesisDelegation elems
deriveFromJSON defaultOptions ''FakeAvvmOptions
deriveFromJSON defaultOptions ''TestnetBalanceOptions
deriveFromJSON defaultOptions ''GenesisInitializer
deriveFromJSON defaultOptions ''ProtocolConstants
deriveFromJSON defaultOptions ''GenesisSpec
| null |
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/core/Pos/Aeson/Genesis.hs
|
haskell
|
* FromJSON
** GenesisAvvmBalances
** GenesisWStakeholders
** GenesisNonAvvmBalances
** VssCertificatesMap
** GenesisDelegation
** FakeAvvmOptions
** GenesisInitializer
** ProtocolConstants
** GenesisSpec
|
| Aeson instances for GenesisSpec and related datatypes .
module Pos.Aeson.Genesis
(
* FromJSONKey RedeemPublicKey
* * GenesisVssCertificatesMap
* * TestnetBalanceOptions
) where
import Universum
import Control.Lens (_Left)
import Data.Aeson (FromJSON (..), FromJSONKey (..), FromJSONKeyFunction (..))
import Data.Aeson.TH (deriveFromJSON)
import Serokell.Aeson.Options (defaultOptions)
import Pos.Aeson.Core ()
import Pos.Aeson.Crypto ()
import Pos.Binary.Core.Address ()
import Pos.Core.Common (StakeholderId)
import Pos.Core.Delegation.Types (ProxySKHeavy)
import Pos.Core.Genesis.Helpers (convertNonAvvmDataToBalances, recreateGenesisDelegation)
import Pos.Core.Genesis.Types (FakeAvvmOptions, GenesisAvvmBalances (..),
GenesisDelegation, GenesisInitializer,
GenesisNonAvvmBalances, GenesisSpec,
GenesisVssCertificatesMap (..), GenesisWStakeholders (..),
ProtocolConstants, TestnetBalanceOptions)
import Pos.Core.Ssc (VssCertificatesMap (..), validateVssCertificatesMap)
import Pos.Crypto (RedeemPublicKey, fromAvvmPk)
import Pos.Util.Util (toAesonError)
instance FromJSONKey RedeemPublicKey where
fromJSONKey = FromJSONKeyTextParser (toAesonError . over _Left pretty . fromAvvmPk)
fromJSONKeyList = FromJSONKeyTextParser (toAesonError . bimap pretty pure . fromAvvmPk)
deriving instance FromJSON GenesisAvvmBalances
deriving instance FromJSON GenesisWStakeholders
instance FromJSON GenesisNonAvvmBalances where
parseJSON = toAesonError . convertNonAvvmDataToBalances <=< parseJSON
instance FromJSON VssCertificatesMap where
parseJSON = parseJSON >=>
toAesonError . validateVssCertificatesMap . UnsafeVssCertificatesMap
instance FromJSON GenesisVssCertificatesMap where
parseJSON val = GenesisVssCertificatesMap <$> parseJSON val
instance FromJSON GenesisDelegation where
parseJSON = parseJSON >=> \v -> do
(elems :: HashMap StakeholderId ProxySKHeavy) <- mapM parseJSON v
toAesonError $ recreateGenesisDelegation elems
deriveFromJSON defaultOptions ''FakeAvvmOptions
deriveFromJSON defaultOptions ''TestnetBalanceOptions
deriveFromJSON defaultOptions ''GenesisInitializer
deriveFromJSON defaultOptions ''ProtocolConstants
deriveFromJSON defaultOptions ''GenesisSpec
|
d8d109849934d33eb44e0c9f63f4b3e789fc2fd6cb9ad930abf923c8076135f6
|
Elzair/nazghul
|
earl.scm
|
;;----------------------------------------------------------------------------
;; Schedule
;;
;; The schedule below is for the place "Trigrave"
;;----------------------------------------------------------------------------
(kern-mk-sched 'sch_earl
(list 0 0 trigrave-earls-bed "sleeping")
(list 5 0 trigrave-tavern-table-3a "eating")
(list 6 0 trigrave-earls-counter "working")
(list 12 0 trigrave-tavern-table-3a "eating")
(list 13 0 trigrave-earls-counter "working")
(list 18 0 trigrave-tavern-table-3a "eating")
(list 19 0 trigrave-tavern-hall "idle")
(list 20 0 trigrave-earls-room "idle")
(list 21 0 trigrave-earls-bed "sleeping")
)
;;----------------------------------------------------------------------------
;; Gob
;;
Quest flags , etc , go here .
;;----------------------------------------------------------------------------
(define (earl-mk) nil)
;;----------------------------------------------------------------------------
;; Conv
;;
;; Earl is a merchant, and will trade with the player if he's at work. He's a
;; tall, wiry blacksmith with a very dry wit. If the town has a leader it would
;; be him because the other townsfolk respect him and look to him in times of
;; crises. He isn't interested in being a celebrity, however, and doesn't
;; exercise any real ambition. He's not interested in adventures and considers
;; (privately) that adventurers are fools. But he's happy to trade with
;; them. He drinks hard, and probably had a very wild youth.
;;----------------------------------------------------------------------------
(define (earl-trade knpc kpc)
(if (not (string=? "working" (kern-obj-get-activity knpc)))
(say knpc "Come by my shop when I'm open. "
"It's the Dry Goods store in the southwest corner, "
"open from 6:00AM to 6:00PM.")
(begin
(kern-conv-trade knpc kpc
;; weapons & arms
(list t_oil 20)
(list t_arrow 1)
(list t_bolt 2)
(list t_bow 50)
(list t_xbow 100)
(list t_spear 15)
(list t_quarterstaff 20)
(list t_leather_helm 20)
(list t_armor_leather 20)
(list t_shield_wooden_buckler 10)
(list t_sm_shield 10)
;; usable stuff
(list t_torch 5)
(list heal-potion 20)
(list cure-poison-potion 20)
(list resurrection-scroll-type 200)
;; reagents
(list sulphorous_ash 4)
(list ginseng 2)
(list garlic 2)
(list spider_silk 8)
(list blood_moss 12)
(list black_pearl 16)
(list mandrake 32)
)
(say knpc "Remember, your life depends on your gear."))))
(define earl-conv
(ifc basic-conv
;; default if the only "keyword" which may (indeed must!) be longer than
4 characters . The 4 - char limit arises from the kernel 's practice of
truncating all player queries to the first four characters . Default ,
;; on the other hand, is a feature of the ifc mechanism (see ifc.scm).
(method 'default (lambda (knpc kpc) (say knpc "I forgot.")))
(method 'hail (lambda (knpc kpc) (say knpc "Welcome, stranger.")))
(method 'bye (lambda (knpc kpc) (say knpc "Oh, were we talking? Bye.")))
(method 'job (lambda (knpc kpc) (say knpc "I keep the store. Need something?")
(if (kern-conv-get-yes-no? kpc)
(earl-trade knpc kpc)
(say knpc "Okay."))))
(method 'name (lambda (knpc kpc) (say knpc "[He thinks for a minute] Earl! That's it!")))
(method 'trad earl-trade)
(method 'join (lambda (knpc kpc) (say knpc "You're too late! I forgot all my spells.")))
(method 'batt
(lambda (knpc kpc)
(say knpc "Yep. I fought with Lord Calvin against the "
"Orkish Horde!")))
(method 'calv
(lambda (knpc kpc)
(say knpc "Now there was a warlord! Calvin conquered "
"everything from the Gray Sea to the Northern Rim!")))
(method 'hord
(lambda (knpc kpc)
(say knpc "In those days the Orks were united under one "
"chieftain, and threatened the whole Peninsula! By the "
"time Lord Calvin was done with them they were scattered "
"and hiding in the hills. They've never recovered!")))
(method 'mage
(lambda (knpc kpc)
(say knpc "I've forgotten all my magic. I even lost my staff. "
"I once knew spells that would slay whole armies.")))
(method 'spel
(lambda (knpc kpc)
(say knpc "I was a battle mage once. Long ago.")))
))
| null |
https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/haxima-1.001/earl.scm
|
scheme
|
----------------------------------------------------------------------------
Schedule
The schedule below is for the place "Trigrave"
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Gob
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Conv
Earl is a merchant, and will trade with the player if he's at work. He's a
tall, wiry blacksmith with a very dry wit. If the town has a leader it would
be him because the other townsfolk respect him and look to him in times of
crises. He isn't interested in being a celebrity, however, and doesn't
exercise any real ambition. He's not interested in adventures and considers
(privately) that adventurers are fools. But he's happy to trade with
them. He drinks hard, and probably had a very wild youth.
----------------------------------------------------------------------------
weapons & arms
usable stuff
reagents
default if the only "keyword" which may (indeed must!) be longer than
on the other hand, is a feature of the ifc mechanism (see ifc.scm).
|
(kern-mk-sched 'sch_earl
(list 0 0 trigrave-earls-bed "sleeping")
(list 5 0 trigrave-tavern-table-3a "eating")
(list 6 0 trigrave-earls-counter "working")
(list 12 0 trigrave-tavern-table-3a "eating")
(list 13 0 trigrave-earls-counter "working")
(list 18 0 trigrave-tavern-table-3a "eating")
(list 19 0 trigrave-tavern-hall "idle")
(list 20 0 trigrave-earls-room "idle")
(list 21 0 trigrave-earls-bed "sleeping")
)
Quest flags , etc , go here .
(define (earl-mk) nil)
(define (earl-trade knpc kpc)
(if (not (string=? "working" (kern-obj-get-activity knpc)))
(say knpc "Come by my shop when I'm open. "
"It's the Dry Goods store in the southwest corner, "
"open from 6:00AM to 6:00PM.")
(begin
(kern-conv-trade knpc kpc
(list t_oil 20)
(list t_arrow 1)
(list t_bolt 2)
(list t_bow 50)
(list t_xbow 100)
(list t_spear 15)
(list t_quarterstaff 20)
(list t_leather_helm 20)
(list t_armor_leather 20)
(list t_shield_wooden_buckler 10)
(list t_sm_shield 10)
(list t_torch 5)
(list heal-potion 20)
(list cure-poison-potion 20)
(list resurrection-scroll-type 200)
(list sulphorous_ash 4)
(list ginseng 2)
(list garlic 2)
(list spider_silk 8)
(list blood_moss 12)
(list black_pearl 16)
(list mandrake 32)
)
(say knpc "Remember, your life depends on your gear."))))
(define earl-conv
(ifc basic-conv
4 characters . The 4 - char limit arises from the kernel 's practice of
truncating all player queries to the first four characters . Default ,
(method 'default (lambda (knpc kpc) (say knpc "I forgot.")))
(method 'hail (lambda (knpc kpc) (say knpc "Welcome, stranger.")))
(method 'bye (lambda (knpc kpc) (say knpc "Oh, were we talking? Bye.")))
(method 'job (lambda (knpc kpc) (say knpc "I keep the store. Need something?")
(if (kern-conv-get-yes-no? kpc)
(earl-trade knpc kpc)
(say knpc "Okay."))))
(method 'name (lambda (knpc kpc) (say knpc "[He thinks for a minute] Earl! That's it!")))
(method 'trad earl-trade)
(method 'join (lambda (knpc kpc) (say knpc "You're too late! I forgot all my spells.")))
(method 'batt
(lambda (knpc kpc)
(say knpc "Yep. I fought with Lord Calvin against the "
"Orkish Horde!")))
(method 'calv
(lambda (knpc kpc)
(say knpc "Now there was a warlord! Calvin conquered "
"everything from the Gray Sea to the Northern Rim!")))
(method 'hord
(lambda (knpc kpc)
(say knpc "In those days the Orks were united under one "
"chieftain, and threatened the whole Peninsula! By the "
"time Lord Calvin was done with them they were scattered "
"and hiding in the hills. They've never recovered!")))
(method 'mage
(lambda (knpc kpc)
(say knpc "I've forgotten all my magic. I even lost my staff. "
"I once knew spells that would slay whole armies.")))
(method 'spel
(lambda (knpc kpc)
(say knpc "I was a battle mage once. Long ago.")))
))
|
66c289b89fdc1f8307a8ba50b586c7c28e30f7d069e00d7b41444d681b612a6c
|
ohri-anurag/TwoFifty-Backend
|
Card.hs
|
# LANGUAGE TemplateHaskell #
module Card where
import Data.Aeson.TH
import Data.Foldable (foldlM)
import qualified Data.Map as M
import Data.Maybe (fromJust)
import System.Random (getStdRandom, randomR)
data Suit
= Spade
| Heart
| Club
| Diamond
deriving (Eq, Ord, Show, Enum)
data CardValue
= Two
| Three
| Four
| Five
| Six
| Seven
| Eight
| Nine
| Ten
| Jack
| Queen
| King
| Ace
deriving (Eq, Ord, Show, Enum)
data Card = Card
{ value :: CardValue
, suit :: Suit
}
deriving Eq
instance Show Card where
show (Card v s) = show v ++ " of " ++ show s
instance Ord Card where
compare (Card v1 s1) (Card v2 s2)
| s1 == s2 =
compare v1 v2
| otherwise =
compare s1 s2
calculateScore :: Card -> Int
calculateScore (Card Three Spade) = 30
calculateScore (Card val _)
| val >= Ten =
10
| val == Five =
5
| otherwise =
0
suits :: [Suit]
suits = [Spade .. Diamond]
values :: [CardValue]
values = [Three .. Ace]
allCards :: [Card]
allCards = [Card v s | s <- suits, v <- values]
fisherYatesShuffle :: [a] -> IO [a]
fisherYatesShuffle items =
M.elems <$> foldlM func mapItems [1..(n-1)]
where
func mp i = do
j <- getStdRandom (randomR (i, n))
pure $ swap i j mp
mapItems = M.fromList $ zip [1..] items
n = M.size mapItems
swap i j mp =
let
vi = fromJust $ M.lookup i mp
vj = fromJust $ M.lookup j mp
in
M.insert i vj (M.insert j vi mp)
-- JSON derivations
$(deriveJSON defaultOptions ''Suit)
$(deriveJSON defaultOptions ''CardValue)
$(deriveJSON defaultOptions ''Card)
| null |
https://raw.githubusercontent.com/ohri-anurag/TwoFifty-Backend/746a57afad9abdfd47c064b3c02321ef0ff2c426/src/Card.hs
|
haskell
|
JSON derivations
|
# LANGUAGE TemplateHaskell #
module Card where
import Data.Aeson.TH
import Data.Foldable (foldlM)
import qualified Data.Map as M
import Data.Maybe (fromJust)
import System.Random (getStdRandom, randomR)
data Suit
= Spade
| Heart
| Club
| Diamond
deriving (Eq, Ord, Show, Enum)
data CardValue
= Two
| Three
| Four
| Five
| Six
| Seven
| Eight
| Nine
| Ten
| Jack
| Queen
| King
| Ace
deriving (Eq, Ord, Show, Enum)
data Card = Card
{ value :: CardValue
, suit :: Suit
}
deriving Eq
instance Show Card where
show (Card v s) = show v ++ " of " ++ show s
instance Ord Card where
compare (Card v1 s1) (Card v2 s2)
| s1 == s2 =
compare v1 v2
| otherwise =
compare s1 s2
calculateScore :: Card -> Int
calculateScore (Card Three Spade) = 30
calculateScore (Card val _)
| val >= Ten =
10
| val == Five =
5
| otherwise =
0
suits :: [Suit]
suits = [Spade .. Diamond]
values :: [CardValue]
values = [Three .. Ace]
allCards :: [Card]
allCards = [Card v s | s <- suits, v <- values]
fisherYatesShuffle :: [a] -> IO [a]
fisherYatesShuffle items =
M.elems <$> foldlM func mapItems [1..(n-1)]
where
func mp i = do
j <- getStdRandom (randomR (i, n))
pure $ swap i j mp
mapItems = M.fromList $ zip [1..] items
n = M.size mapItems
swap i j mp =
let
vi = fromJust $ M.lookup i mp
vj = fromJust $ M.lookup j mp
in
M.insert i vj (M.insert j vi mp)
$(deriveJSON defaultOptions ''Suit)
$(deriveJSON defaultOptions ''CardValue)
$(deriveJSON defaultOptions ''Card)
|
835e3de47905ceae662848efa124b404fdd41a4e43f47ed85137216450bf68e5
|
rfkm/zou
|
handler.clj
|
(ns zou.web.handler
(:require [clojure.string :as str]
[zou.util :as u]
[zou.web.handler.args-mapper :as mapper]
[zou.web.middleware.proto :as proto]))
(defmacro -defhandler
[handler-tag ns-tag name & fdecl]
(let [m {handler-tag
(if (keyword? (first fdecl))
(first fdecl)
(keyword (clojure.core/name (ns-name *ns*))
(clojure.core/name name)))}
fdecl (if (keyword? (first fdecl))
(next fdecl)
fdecl)
m (if (string? (first fdecl))
(assoc m :doc (first fdecl))
m)
fdecl (if (string? (first fdecl))
(next fdecl)
fdecl)
m (if (map? (first fdecl))
(conj m (first fdecl))
m)
fdecl (if (map? (first fdecl))
(next fdecl)
fdecl)
[params & fdecl] (if (vector? (first fdecl))
fdecl
(throw (IllegalArgumentException. "Cannot find params")))
spec (mapper/gen-destructuring-spec params)
m (assoc m :arglists (list 'quote (list (:params spec))))
m (conj (if (meta name) (meta name) {}) m)]
`(let [mapper# (:fn (mapper/gen-destructuring-spec (quote ~params)))]
(alter-meta! *ns* assoc ~ns-tag true)
(def ~(with-meta name m)
(vary-meta
(fn ~(:params spec) ~@fdecl)
assoc
:zou/args-mapper
mapper#)))))
(defmacro defhandler
{:arglists '([name handler-name? doc-string? attr-map? [params*] prepost-map? body])}
[name & fdecl]
`(-defhandler :zou/handler :zou/handler-ns ~name ~@fdecl))
(defn invoke-with-mapper [f arg]
(let [f (if (var? f) @f f)]
(if-let [mapper (:zou/args-mapper (meta f))]
(apply f (mapper arg))
(f arg))))
impls
(defmethod mapper/process-param "$req" [{:keys [sym] :as m}]
(if (= sym '$req)
(mapper/process-param (assoc m :sym '$request))
(mapper/skip m)))
(defmethod mapper/process-param "$request" [{:keys [sym] :as m}]
(if (= sym '$request)
(assoc m :fn identity)
(mapper/skip m)))
(defmethod mapper/process-param "$" [{:keys [sym] :as m}]
(let [k (keyword (subs (name sym) 1))]
(assoc m
:fn
#(get-in % [:zou/container k]))))
(defmethod mapper/process-param "|" [{:keys [sym] :as m}]
(let [ks (mapv keyword (str/split (subs (name sym) 1) #"\|"))]
(assoc m
:alias (symbol (name (last ks)))
:fn
#(get-in % ks))))
(defmethod mapper/process-param nil [{:keys [sym] :as m}]
(let [ks (map keyword (str/split (name sym) #"\|"))]
(assoc m
:alias (symbol (name (last ks)))
:fn
#(get-in % (into [:route-params] ks)
(get-in % (into [:params] ks))))))
;;; middleware
(defn wrap-args-mapper [handler]
(fn [req]
(invoke-with-mapper handler req)))
(defn args-mapper [& [conf]]
(reify proto/RingMiddleware
(wrap [this handler]
(wrap-args-mapper handler))))
| null |
https://raw.githubusercontent.com/rfkm/zou/228feefae3e008f56806589cb8019511981f7b01/web/src/zou/web/handler.clj
|
clojure
|
middleware
|
(ns zou.web.handler
(:require [clojure.string :as str]
[zou.util :as u]
[zou.web.handler.args-mapper :as mapper]
[zou.web.middleware.proto :as proto]))
(defmacro -defhandler
[handler-tag ns-tag name & fdecl]
(let [m {handler-tag
(if (keyword? (first fdecl))
(first fdecl)
(keyword (clojure.core/name (ns-name *ns*))
(clojure.core/name name)))}
fdecl (if (keyword? (first fdecl))
(next fdecl)
fdecl)
m (if (string? (first fdecl))
(assoc m :doc (first fdecl))
m)
fdecl (if (string? (first fdecl))
(next fdecl)
fdecl)
m (if (map? (first fdecl))
(conj m (first fdecl))
m)
fdecl (if (map? (first fdecl))
(next fdecl)
fdecl)
[params & fdecl] (if (vector? (first fdecl))
fdecl
(throw (IllegalArgumentException. "Cannot find params")))
spec (mapper/gen-destructuring-spec params)
m (assoc m :arglists (list 'quote (list (:params spec))))
m (conj (if (meta name) (meta name) {}) m)]
`(let [mapper# (:fn (mapper/gen-destructuring-spec (quote ~params)))]
(alter-meta! *ns* assoc ~ns-tag true)
(def ~(with-meta name m)
(vary-meta
(fn ~(:params spec) ~@fdecl)
assoc
:zou/args-mapper
mapper#)))))
(defmacro defhandler
{:arglists '([name handler-name? doc-string? attr-map? [params*] prepost-map? body])}
[name & fdecl]
`(-defhandler :zou/handler :zou/handler-ns ~name ~@fdecl))
(defn invoke-with-mapper [f arg]
(let [f (if (var? f) @f f)]
(if-let [mapper (:zou/args-mapper (meta f))]
(apply f (mapper arg))
(f arg))))
impls
(defmethod mapper/process-param "$req" [{:keys [sym] :as m}]
(if (= sym '$req)
(mapper/process-param (assoc m :sym '$request))
(mapper/skip m)))
(defmethod mapper/process-param "$request" [{:keys [sym] :as m}]
(if (= sym '$request)
(assoc m :fn identity)
(mapper/skip m)))
(defmethod mapper/process-param "$" [{:keys [sym] :as m}]
(let [k (keyword (subs (name sym) 1))]
(assoc m
:fn
#(get-in % [:zou/container k]))))
(defmethod mapper/process-param "|" [{:keys [sym] :as m}]
(let [ks (mapv keyword (str/split (subs (name sym) 1) #"\|"))]
(assoc m
:alias (symbol (name (last ks)))
:fn
#(get-in % ks))))
(defmethod mapper/process-param nil [{:keys [sym] :as m}]
(let [ks (map keyword (str/split (name sym) #"\|"))]
(assoc m
:alias (symbol (name (last ks)))
:fn
#(get-in % (into [:route-params] ks)
(get-in % (into [:params] ks))))))
(defn wrap-args-mapper [handler]
(fn [req]
(invoke-with-mapper handler req)))
(defn args-mapper [& [conf]]
(reify proto/RingMiddleware
(wrap [this handler]
(wrap-args-mapper handler))))
|
88b720834885c0f6944ba3c87bb4ffbc92fd9d391b343a5cd4a0131ea453647a
|
andy128k/cl-gobject-introspection
|
object.lisp
|
(in-package :gir)
(defgeneric field (object name))
(defgeneric set-field! (object name value))
(defun c-name (name)
(etypecase name
(string name)
(symbol (string-downcase (substitute #\_ #\- (symbol-name name))))))
(defclass object-instance ()
((class :initarg :class :reader gir-class-of)
(this :initarg :this :reader this-of)))
(defclass object-class ()
((parent :initarg :parent :reader parent-of)
(info :initarg :info :reader info-of)
(interface-infos :reader interface-infos-of)
(signals :reader signals-of)
(fields-dict :reader fields-dict-of)
(function-cache :reader function-cache-of)
(method-cache :reader method-cache-of)))
(defmethod print-object ((obj-cls object-class) s)
(format s "#O<~a>" (info-get-name (info-of obj-cls))))
(defmethod shared-initialize :after ((object-class object-class) slot-names
&key info)
(declare (ignore slot-names))
(with-slots ((object-info info) parent interface-infos signals
fields-dict function-cache method-cache)
object-class
(setf object-info info
parent (if-let ((parent-info (object-info-get-parent info)))
(find-build-interface parent-info)
nil)
interface-infos (object-info-get-interfaces info)
signals (list nil)
fields-dict (iter (for field-info :in (object-info-get-fields info))
(collect (cons (info-get-name field-info) field-info)))
function-cache (make-hash-table :test #'equal)
method-cache (make-hash-table :test #'equal))))
(defmethod build-interface ((info object-info))
(make-instance 'object-class :info info))
(defmethod build-interface ((info interface-info))
(make-instance 'interface-desc :info info))
(defun object-class-get-constructor-class-function-info (object-class cname)
(let* ((info (info-of object-class))
(function-info (object-info-find-method info cname))
flags)
(if function-info
(setf flags (function-info-get-flags function-info))
(error "Bad FFI constructor/function name ~a" cname))
(cond
((constructor? flags)
(values function-info info))
((class-function? flags)
(values function-info nil))
(t
(error "~a is not constructor or class function" cname)))))
(defun object-class-build-constructor-class-function (object-class cname)
(multiple-value-bind (function-info return-interface)
(object-class-get-constructor-class-function-info object-class cname)
(build-function function-info :return-interface return-interface)))
(defun object-class-find-function-info (object-class cname)
(with-accessors ((info info-of) (interface-infos interface-infos-of))
object-class
(or (object-info-find-method info cname)
(iter (for intf :in interface-infos)
(if-let ((func (interface-info-find-method intf cname)))
(return func))))))
(defun object-class-find-method-function-info (object-class cname)
(if-let ((function-info (object-class-find-function-info object-class cname)))
(when (method? (function-info-get-flags function-info))
function-info)
(if-let ((parent (parent-of object-class)))
(object-class-find-method-function-info parent cname))))
(defun object-class-build-method (object-class cname)
(if-let ((func-info (object-class-find-method-function-info object-class cname)))
(and func-info (build-function func-info))))
(defun object-class-find-build-method (object-class cname)
(with-accessors ((method-cache method-cache-of))
object-class
(ensure-gethash-unless-null cname method-cache
(object-class-build-method object-class cname)
(error "Bad FFI method name ~a" cname))))
(defun build-object-ptr (object-class this)
(make-instance 'object-instance :class object-class :this this))
(defun object-class-find-field (object-class name)
(with-accessors ((fields-dict fields-dict-of))
object-class
(cdr (or (assoc (c-name name) fields-dict :test #'string=)
(error "Bad FFI field name ~a" name)))))
(defmethod nsget ((object-class object-class) name)
(let ((cname (c-name name)))
(ensure-gethash-unless-null cname (function-cache-of object-class)
(object-class-build-constructor-class-function object-class cname)
(error "Bad FFI constructor/class function name ~a" name))))
(defmethod field ((object object-instance) name)
(let* ((object-class (gir-class-of object))
(field-info (object-class-find-field object-class name)))
(gir.field:get (this-of object) field-info)))
(defmethod set-field! ((object object-instance) name value)
(let* ((object-class (gir-class-of object))
(field-info (object-class-find-field object-class name)))
(gir.field:set (this-of object) field-info value)))
(defun property (object name)
(get-properties (this-of object) (list name)))
(defun (setf property) (value object name)
(set-properties! (this-of object) (list name value)))
(cffi:defcfun g-object-is-floating :boolean (obj :pointer))
(cffi:defcfun g-object-ref-sink :pointer (obj :pointer))
(cffi:defcfun g-object-ref :pointer (obj :pointer))
(cffi:defcfun g-object-unref :void (obj :pointer))
(defun object-setup-gc (object transfer)
(let* ((this (this-of object))
(floating? (g-object-is-floating this))
(a (cffi:pointer-address this)))
(if (eq transfer :everything)
(if floating? (g-object-ref-sink this))
(g-object-ref this))
(tg:finalize this (lambda () (g-object-unref (cffi:make-pointer a)))))
object)
(defgeneric find-build-method (object-class cname))
(defmethod find-build-method ((object-class object-class) cname)
(object-class-find-build-method object-class cname))
(defmethod nsget ((object object-instance) name)
(let* ((object-class (gir-class-of object))
(cname (c-name name))
(method (find-build-method object-class cname))
(this (this-of object)))
(lambda (&rest args)
(apply method (cons this args)))))
(defclass fake-object-class ()
((name :initarg :name)
(gtype :initarg :gtype)))
(defmethod print-object ((self fake-object-class) s)
(with-slots (name gtype) self
(let ((interface-p (= (g-type-fundamental gtype) 8)))
(format s "#~C<fake.~a>" (if interface-p #\I #\O)
name))))
(defvar *fake-object-classes* (make-hash-table))
(defun find-fake-object-class (gtype) ; when gtype is not in g-i
(let ((fundamental (g-type-fundamental gtype)))
(when (or (= fundamental 8) (= fundamental 80))
(assert (/= gtype 80))
(or (gethash gtype *fake-object-classes*)
(setf (gethash gtype *fake-object-classes*)
(make-instance 'fake-object-class
:gtype gtype
:name (cffi:foreign-funcall "g_type_name"
:ulong gtype :string)))))))
(defun gobject (gtype ptr)
(let* ((info (repository-find-by-gtype nil gtype))
(info-type (and info (info-get-type info)))
(object-class (if (null info) (find-fake-object-class gtype))))
(when object-class
(return-from gobject (build-object-ptr object-class ptr)))
(if (member info-type '(:object :struct))
(let ((object-class (find-build-interface info)))
(if (eq info-type :object)
(build-object-ptr object-class ptr)
(build-struct-ptr object-class ptr)))
(error "gtype ~a not found in GI. Found ~a"
gtype info-type))))
(cffi:define-foreign-type pobject ()
()
(:documentation "pointer to GObject")
(:actual-type :pointer)
(:simple-parser pobject))
(defmethod cffi:translate-to-foreign (object (type pobject))
(this-of object))
(defmethod cffi:translate-from-foreign (pointer (type pobject))
(if (cffi:null-pointer-p pointer)
nil
(gobject (gtype pointer) pointer)))
(defmethod nsget-desc ((object-class object-class) name)
(multiple-value-bind (function-info return-interface)
(object-class-get-constructor-class-function-info object-class (c-name name))
(build-callable-desc function-info :return-interface return-interface)))
(defmethod list-fields-desc ((object-class object-class))
(let ((fields-dict (fields-dict-of object-class)))
(iter (for (name . field-info) :in fields-dict)
(collect (build-variable-desc name (field-info-get-type field-info))))))
(defmethod get-field-desc ((object-class object-class) name)
(let* ((cname (c-name name))
(field-info (object-class-find-field object-class cname)))
(build-variable-desc cname (field-info-get-type field-info))))
(defmethod list-properties-desc ((object-class object-class))
(let ((info (info-of object-class)))
(iter (for prop-info :in (object-info-get-properties info))
(collect (build-variable-desc (info-get-name prop-info)
(property-info-get-type prop-info))))))
(defmethod get-property-desc ((object-class object-class) name)
(let ((cname (c-name name))
(props-desc (list-properties-desc object-class)))
(iter (for prop-desc :in props-desc)
(when (equal cname (name-of prop-desc))
(return prop-desc)))
(error "~a is not property name" cname)))
(defmethod list-methods-desc ((object-class object-class))
(let ((info (info-of object-class)))
(iter (for method-info :in (object-info-get-methods info))
(when (method? (function-info-get-flags method-info))
(collect (build-callable-desc method-info))))))
(defmethod get-method-desc ((object-class object-class) name)
(let* ((cname (c-name name))
(func-info (object-class-find-method-function-info object-class cname)))
(if func-info
(build-callable-desc func-info)
(error "~a is not method name" cname))))
(defmethod list-class-functions-desc ((object-class object-class))
(let ((info (info-of object-class)))
(iter (for method-info :in (object-info-get-methods info))
(when (class-function? (function-info-get-flags method-info))
(collect (build-callable-desc method-info))))))
(defmethod list-constructors-desc ((object-class object-class))
(let ((info (info-of object-class)))
(iter (for method-info :in (object-info-get-methods info))
(when (constructor? (function-info-get-flags method-info))
(collect (build-callable-desc method-info :return-interface info))))))
(defmethod list-signals-desc ((object-class object-class))
(let ((info (info-of object-class)))
(iter (for signal-info :in (object-info-get-signals info))
(collect (build-callable-desc signal-info)))))
(defun object-class-find-signal-info (object-class cname)
(let ((object-info (info-of object-class)))
(or (object-info-find-signal object-info cname)
(iter (for intf-info :in (object-info-get-interfaces object-info))
(when-let ((signal-info (interface-info-find-signal intf-info cname)))
(return signal-info)))
(when-let ((parent (parent-of object-class)))
(object-class-find-signal-info parent cname)))))
(defmethod get-signal-desc ((object-class object-class) name)
(let* ((cname (c-name name))
(signal-info (object-class-find-signal-info object-class cname)))
(if signal-info
(build-callable-desc signal-info)
(error "~a is not signal name" cname))))
(defclass interface-desc ()
((info :initarg :info :reader info-of)))
(defmethod find-build-method ((object-class interface-desc) cname)
(let ((func-info (interface-info-find-method
(info-of object-class) cname)))
(and func-info (build-function func-info))))
(defmethod print-object ((interface-desc interface-desc) s)
(format s "I<~a>" (info-get-name (info-of interface-desc))))
(defun list-interfaces-desc (object-class)
(iter (for intf-info :in (interface-infos-of object-class))
(collect (make-instance 'interface-desc :info intf-info))))
(defmethod list-properties-desc ((interface-desc interface-desc))
(let ((info (info-of interface-desc)))
(iter (for prop-info :in (interface-info-get-properties info))
(collect (build-variable-desc (info-get-name prop-info)
(property-info-get-type prop-info))))))
(defmethod list-methods-desc ((interface-desc interface-desc))
(let ((info (info-of interface-desc)))
(iter (for method-info :in (interface-info-get-methods info))
(when (method? (function-info-get-flags method-info))
(collect (build-callable-desc method-info))))))
(defmethod list-signals-desc ((interface-desc interface-desc))
(let ((info (info-of interface-desc)))
(iter (for signal-info :in (interface-info-get-signals info))
(collect (build-callable-desc signal-info)))))
| null |
https://raw.githubusercontent.com/andy128k/cl-gobject-introspection/ce7d470debf6e3e5e828430f69b190dfbb037c3e/src/object.lisp
|
lisp
|
when gtype is not in g-i
|
(in-package :gir)
(defgeneric field (object name))
(defgeneric set-field! (object name value))
(defun c-name (name)
(etypecase name
(string name)
(symbol (string-downcase (substitute #\_ #\- (symbol-name name))))))
(defclass object-instance ()
((class :initarg :class :reader gir-class-of)
(this :initarg :this :reader this-of)))
(defclass object-class ()
((parent :initarg :parent :reader parent-of)
(info :initarg :info :reader info-of)
(interface-infos :reader interface-infos-of)
(signals :reader signals-of)
(fields-dict :reader fields-dict-of)
(function-cache :reader function-cache-of)
(method-cache :reader method-cache-of)))
(defmethod print-object ((obj-cls object-class) s)
(format s "#O<~a>" (info-get-name (info-of obj-cls))))
(defmethod shared-initialize :after ((object-class object-class) slot-names
&key info)
(declare (ignore slot-names))
(with-slots ((object-info info) parent interface-infos signals
fields-dict function-cache method-cache)
object-class
(setf object-info info
parent (if-let ((parent-info (object-info-get-parent info)))
(find-build-interface parent-info)
nil)
interface-infos (object-info-get-interfaces info)
signals (list nil)
fields-dict (iter (for field-info :in (object-info-get-fields info))
(collect (cons (info-get-name field-info) field-info)))
function-cache (make-hash-table :test #'equal)
method-cache (make-hash-table :test #'equal))))
(defmethod build-interface ((info object-info))
(make-instance 'object-class :info info))
(defmethod build-interface ((info interface-info))
(make-instance 'interface-desc :info info))
(defun object-class-get-constructor-class-function-info (object-class cname)
(let* ((info (info-of object-class))
(function-info (object-info-find-method info cname))
flags)
(if function-info
(setf flags (function-info-get-flags function-info))
(error "Bad FFI constructor/function name ~a" cname))
(cond
((constructor? flags)
(values function-info info))
((class-function? flags)
(values function-info nil))
(t
(error "~a is not constructor or class function" cname)))))
(defun object-class-build-constructor-class-function (object-class cname)
(multiple-value-bind (function-info return-interface)
(object-class-get-constructor-class-function-info object-class cname)
(build-function function-info :return-interface return-interface)))
(defun object-class-find-function-info (object-class cname)
(with-accessors ((info info-of) (interface-infos interface-infos-of))
object-class
(or (object-info-find-method info cname)
(iter (for intf :in interface-infos)
(if-let ((func (interface-info-find-method intf cname)))
(return func))))))
(defun object-class-find-method-function-info (object-class cname)
(if-let ((function-info (object-class-find-function-info object-class cname)))
(when (method? (function-info-get-flags function-info))
function-info)
(if-let ((parent (parent-of object-class)))
(object-class-find-method-function-info parent cname))))
(defun object-class-build-method (object-class cname)
(if-let ((func-info (object-class-find-method-function-info object-class cname)))
(and func-info (build-function func-info))))
(defun object-class-find-build-method (object-class cname)
(with-accessors ((method-cache method-cache-of))
object-class
(ensure-gethash-unless-null cname method-cache
(object-class-build-method object-class cname)
(error "Bad FFI method name ~a" cname))))
(defun build-object-ptr (object-class this)
(make-instance 'object-instance :class object-class :this this))
(defun object-class-find-field (object-class name)
(with-accessors ((fields-dict fields-dict-of))
object-class
(cdr (or (assoc (c-name name) fields-dict :test #'string=)
(error "Bad FFI field name ~a" name)))))
(defmethod nsget ((object-class object-class) name)
(let ((cname (c-name name)))
(ensure-gethash-unless-null cname (function-cache-of object-class)
(object-class-build-constructor-class-function object-class cname)
(error "Bad FFI constructor/class function name ~a" name))))
(defmethod field ((object object-instance) name)
(let* ((object-class (gir-class-of object))
(field-info (object-class-find-field object-class name)))
(gir.field:get (this-of object) field-info)))
(defmethod set-field! ((object object-instance) name value)
(let* ((object-class (gir-class-of object))
(field-info (object-class-find-field object-class name)))
(gir.field:set (this-of object) field-info value)))
(defun property (object name)
(get-properties (this-of object) (list name)))
(defun (setf property) (value object name)
(set-properties! (this-of object) (list name value)))
(cffi:defcfun g-object-is-floating :boolean (obj :pointer))
(cffi:defcfun g-object-ref-sink :pointer (obj :pointer))
(cffi:defcfun g-object-ref :pointer (obj :pointer))
(cffi:defcfun g-object-unref :void (obj :pointer))
(defun object-setup-gc (object transfer)
(let* ((this (this-of object))
(floating? (g-object-is-floating this))
(a (cffi:pointer-address this)))
(if (eq transfer :everything)
(if floating? (g-object-ref-sink this))
(g-object-ref this))
(tg:finalize this (lambda () (g-object-unref (cffi:make-pointer a)))))
object)
(defgeneric find-build-method (object-class cname))
(defmethod find-build-method ((object-class object-class) cname)
(object-class-find-build-method object-class cname))
(defmethod nsget ((object object-instance) name)
(let* ((object-class (gir-class-of object))
(cname (c-name name))
(method (find-build-method object-class cname))
(this (this-of object)))
(lambda (&rest args)
(apply method (cons this args)))))
(defclass fake-object-class ()
((name :initarg :name)
(gtype :initarg :gtype)))
(defmethod print-object ((self fake-object-class) s)
(with-slots (name gtype) self
(let ((interface-p (= (g-type-fundamental gtype) 8)))
(format s "#~C<fake.~a>" (if interface-p #\I #\O)
name))))
(defvar *fake-object-classes* (make-hash-table))
(let ((fundamental (g-type-fundamental gtype)))
(when (or (= fundamental 8) (= fundamental 80))
(assert (/= gtype 80))
(or (gethash gtype *fake-object-classes*)
(setf (gethash gtype *fake-object-classes*)
(make-instance 'fake-object-class
:gtype gtype
:name (cffi:foreign-funcall "g_type_name"
:ulong gtype :string)))))))
(defun gobject (gtype ptr)
(let* ((info (repository-find-by-gtype nil gtype))
(info-type (and info (info-get-type info)))
(object-class (if (null info) (find-fake-object-class gtype))))
(when object-class
(return-from gobject (build-object-ptr object-class ptr)))
(if (member info-type '(:object :struct))
(let ((object-class (find-build-interface info)))
(if (eq info-type :object)
(build-object-ptr object-class ptr)
(build-struct-ptr object-class ptr)))
(error "gtype ~a not found in GI. Found ~a"
gtype info-type))))
(cffi:define-foreign-type pobject ()
()
(:documentation "pointer to GObject")
(:actual-type :pointer)
(:simple-parser pobject))
(defmethod cffi:translate-to-foreign (object (type pobject))
(this-of object))
(defmethod cffi:translate-from-foreign (pointer (type pobject))
(if (cffi:null-pointer-p pointer)
nil
(gobject (gtype pointer) pointer)))
(defmethod nsget-desc ((object-class object-class) name)
(multiple-value-bind (function-info return-interface)
(object-class-get-constructor-class-function-info object-class (c-name name))
(build-callable-desc function-info :return-interface return-interface)))
(defmethod list-fields-desc ((object-class object-class))
(let ((fields-dict (fields-dict-of object-class)))
(iter (for (name . field-info) :in fields-dict)
(collect (build-variable-desc name (field-info-get-type field-info))))))
(defmethod get-field-desc ((object-class object-class) name)
(let* ((cname (c-name name))
(field-info (object-class-find-field object-class cname)))
(build-variable-desc cname (field-info-get-type field-info))))
(defmethod list-properties-desc ((object-class object-class))
(let ((info (info-of object-class)))
(iter (for prop-info :in (object-info-get-properties info))
(collect (build-variable-desc (info-get-name prop-info)
(property-info-get-type prop-info))))))
(defmethod get-property-desc ((object-class object-class) name)
(let ((cname (c-name name))
(props-desc (list-properties-desc object-class)))
(iter (for prop-desc :in props-desc)
(when (equal cname (name-of prop-desc))
(return prop-desc)))
(error "~a is not property name" cname)))
(defmethod list-methods-desc ((object-class object-class))
(let ((info (info-of object-class)))
(iter (for method-info :in (object-info-get-methods info))
(when (method? (function-info-get-flags method-info))
(collect (build-callable-desc method-info))))))
(defmethod get-method-desc ((object-class object-class) name)
(let* ((cname (c-name name))
(func-info (object-class-find-method-function-info object-class cname)))
(if func-info
(build-callable-desc func-info)
(error "~a is not method name" cname))))
(defmethod list-class-functions-desc ((object-class object-class))
(let ((info (info-of object-class)))
(iter (for method-info :in (object-info-get-methods info))
(when (class-function? (function-info-get-flags method-info))
(collect (build-callable-desc method-info))))))
(defmethod list-constructors-desc ((object-class object-class))
(let ((info (info-of object-class)))
(iter (for method-info :in (object-info-get-methods info))
(when (constructor? (function-info-get-flags method-info))
(collect (build-callable-desc method-info :return-interface info))))))
(defmethod list-signals-desc ((object-class object-class))
(let ((info (info-of object-class)))
(iter (for signal-info :in (object-info-get-signals info))
(collect (build-callable-desc signal-info)))))
(defun object-class-find-signal-info (object-class cname)
(let ((object-info (info-of object-class)))
(or (object-info-find-signal object-info cname)
(iter (for intf-info :in (object-info-get-interfaces object-info))
(when-let ((signal-info (interface-info-find-signal intf-info cname)))
(return signal-info)))
(when-let ((parent (parent-of object-class)))
(object-class-find-signal-info parent cname)))))
(defmethod get-signal-desc ((object-class object-class) name)
(let* ((cname (c-name name))
(signal-info (object-class-find-signal-info object-class cname)))
(if signal-info
(build-callable-desc signal-info)
(error "~a is not signal name" cname))))
(defclass interface-desc ()
((info :initarg :info :reader info-of)))
(defmethod find-build-method ((object-class interface-desc) cname)
(let ((func-info (interface-info-find-method
(info-of object-class) cname)))
(and func-info (build-function func-info))))
(defmethod print-object ((interface-desc interface-desc) s)
(format s "I<~a>" (info-get-name (info-of interface-desc))))
(defun list-interfaces-desc (object-class)
(iter (for intf-info :in (interface-infos-of object-class))
(collect (make-instance 'interface-desc :info intf-info))))
(defmethod list-properties-desc ((interface-desc interface-desc))
(let ((info (info-of interface-desc)))
(iter (for prop-info :in (interface-info-get-properties info))
(collect (build-variable-desc (info-get-name prop-info)
(property-info-get-type prop-info))))))
(defmethod list-methods-desc ((interface-desc interface-desc))
(let ((info (info-of interface-desc)))
(iter (for method-info :in (interface-info-get-methods info))
(when (method? (function-info-get-flags method-info))
(collect (build-callable-desc method-info))))))
(defmethod list-signals-desc ((interface-desc interface-desc))
(let ((info (info-of interface-desc)))
(iter (for signal-info :in (interface-info-get-signals info))
(collect (build-callable-desc signal-info)))))
|
5bd8fca5755702a91d9938973bb85734720f7f33c3948e16d1940c0b513a807b
|
cjohansen/gadget-inspector
|
diff_test.cljc
|
(ns gadget.diff-test
(:require [gadget.diff :as sut]
#?(:clj [clojure.test :refer [deftest testing is]]
:cljs [cljs.test :refer [deftest testing is]])))
(deftest diff-test
(testing "Reports added keys"
(is (= (sut/diff {} {:a 1 :b 2})
{:added #{:a :b}
:removed #{}
:changed {}})))
(testing "Reports removed keys"
(is (= (sut/diff {:a 1 :b 2} {})
{:removed #{:a :b}
:added #{}
:changed {}})))
(testing "Reports changed keys"
(is (= (sut/diff {:a 1 :b 2} {:a 2 :b 3})
{:removed #{}
:added #{}
:changed {:a {:old 1 :new 2}
:b {:old 2 :new 3}}})))
(testing "Recursively diffs changed keys"
(is (= (sut/diff {:a {:c 1}} {:a {:c 2}})
{:removed #{}
:added #{}
:changed {:a {:added #{}
:removed #{}
:changed {:c {:old 1
:new 2}}}}}))
(is (= (sut/diff {:a {:c 1}} {:a {:d 2}})
{:removed #{}
:added #{}
:changed {:a {:added #{:d}
:removed #{:c}
:changed {}}}})))
(testing "Diffs vectors"
(is (= (sut/diff [:a :b :c] [:a :b])
{:old [:a :b :c]
:new [:a :b]}))))
| null |
https://raw.githubusercontent.com/cjohansen/gadget-inspector/c7b8ed79fbba7218bb214955342ed19d5cc57bfd/lib/test/gadget/diff_test.cljc
|
clojure
|
(ns gadget.diff-test
(:require [gadget.diff :as sut]
#?(:clj [clojure.test :refer [deftest testing is]]
:cljs [cljs.test :refer [deftest testing is]])))
(deftest diff-test
(testing "Reports added keys"
(is (= (sut/diff {} {:a 1 :b 2})
{:added #{:a :b}
:removed #{}
:changed {}})))
(testing "Reports removed keys"
(is (= (sut/diff {:a 1 :b 2} {})
{:removed #{:a :b}
:added #{}
:changed {}})))
(testing "Reports changed keys"
(is (= (sut/diff {:a 1 :b 2} {:a 2 :b 3})
{:removed #{}
:added #{}
:changed {:a {:old 1 :new 2}
:b {:old 2 :new 3}}})))
(testing "Recursively diffs changed keys"
(is (= (sut/diff {:a {:c 1}} {:a {:c 2}})
{:removed #{}
:added #{}
:changed {:a {:added #{}
:removed #{}
:changed {:c {:old 1
:new 2}}}}}))
(is (= (sut/diff {:a {:c 1}} {:a {:d 2}})
{:removed #{}
:added #{}
:changed {:a {:added #{:d}
:removed #{:c}
:changed {}}}})))
(testing "Diffs vectors"
(is (= (sut/diff [:a :b :c] [:a :b])
{:old [:a :b :c]
:new [:a :b]}))))
|
|
d27b0fe0aff4af236e9fc752ec01a59b346553f089410d84033a0e0f1dea5f13
|
Gbury/archsat
|
sig.ml
|
This file is free software , part of Archsat . See file " LICENSE " for more details .
* { 2 Common signatures for modules }
(** Standard interface for modules defining a new type. *)
module type Std = sig
type t
val hash : t -> int
val equal : t -> t -> bool
val compare : t -> t -> int
end
(** Standard interface for printing *)
module type Print = sig
type t
val print : Format.formatter -> t -> unit
end
* Full interface for module defining a new type , incldues
the standard interface , plus printing functions .
the standard interface, plus printing functions. *)
module type Full = sig
include Std
include Print with type t := t
end
* { 2 Common signatures for parametrised modules }
(** Variant of the standard signature for parametric types. *)
module type PolyStd = sig
type 'a t
val hash : 'a t -> int
val equal : 'a t -> 'a t -> bool
val compare : 'a t -> 'a t -> int
end
(** Standard interface for printing polymorphic types *)
module type PolyPrint = sig
type 'a t
val print : Format.formatter -> 'a t -> unit
end
* Full interface for module defining a new type , incldues
the standard interface , plus printing functions .
the standard interface, plus printing functions. *)
module type PolyFull = sig
include PolyStd
include PolyPrint with type 'a t := 'a t
end
| null |
https://raw.githubusercontent.com/Gbury/archsat/322fbefa4a58023ddafb3fa1a51f8199c25cde3d/src/base/sig.ml
|
ocaml
|
* Standard interface for modules defining a new type.
* Standard interface for printing
* Variant of the standard signature for parametric types.
* Standard interface for printing polymorphic types
|
This file is free software , part of Archsat . See file " LICENSE " for more details .
* { 2 Common signatures for modules }
module type Std = sig
type t
val hash : t -> int
val equal : t -> t -> bool
val compare : t -> t -> int
end
module type Print = sig
type t
val print : Format.formatter -> t -> unit
end
* Full interface for module defining a new type , incldues
the standard interface , plus printing functions .
the standard interface, plus printing functions. *)
module type Full = sig
include Std
include Print with type t := t
end
* { 2 Common signatures for parametrised modules }
module type PolyStd = sig
type 'a t
val hash : 'a t -> int
val equal : 'a t -> 'a t -> bool
val compare : 'a t -> 'a t -> int
end
module type PolyPrint = sig
type 'a t
val print : Format.formatter -> 'a t -> unit
end
* Full interface for module defining a new type , incldues
the standard interface , plus printing functions .
the standard interface, plus printing functions. *)
module type PolyFull = sig
include PolyStd
include PolyPrint with type 'a t := 'a t
end
|
8434b1d1ee253a8ef4e9f072d37cdd20f2980604ecce9e9c090375f29d66ed76
|
scalaris-team/scalaris
|
dht_node_join_recover.erl
|
2007 - 2015 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 Join ring on recover.
%% @version $Id$
-module(dht_node_join_recover).
-author('').
-vsn('$Id$').
-include("scalaris.hrl").
-include("record_helpers.hrl").
-export([join/1, on/2]).
-spec join(Options::[tuple()]) ->
{'$gen_component', [{on_handler, Handler::gen_component:handler()},...],
[tuple()]}.
join(Options) ->
comm:send_local(self(), {recover_now}),
gen_component:change_handler(
Options,
fun ?MODULE:on/2).
-spec on(tuple(), [tuple()]) -> dht_node_state:state() |
{'$gen_component', [{on_handler, Handler::gen_component:handler()},...], [tuple()]}.
on({recover_now}, Options) ->
State = recover_state(Options),
gen_component:change_handler(
State,
fun dht_node:on/2);
on(Msg, Options) ->
comm:send_local(self(), Msg),
Options.
-spec recover_state(Options::[tuple()]) -> dht_node_state:state().
recover_state(Options) ->
1 . get old lease databases
LeaseDBs = [get_db(Options, erlang:list_to_atom("lease_db-" ++ erlang:integer_to_list(I))) || I <- lists:seq(1, config:read(replication_factor))],
2 . find old leases
LeaseList = lease_recover:recover(LeaseDBs),
3 . create state with old mnesias
MyId = l_on_cseq:get_id(lease_list:get_active_lease(LeaseList)),
Me = node:new(comm:this(), MyId, 0),
Neighbors = nodelist:new_neighborhood(Me), % needed for ?RT:empty_ext/1
EmptyRT = ?RT:empty_ext(Neighbors), % only for rt_chord
RMState = rm_loop:init(Me, Me, Me, null),
rm_loop:send_trigger(), % speed up RM
KV_DB = get_db(Options, kv_db),
io:format("recovered a kv_db of size ~p~n", [length(prbr:tab2list(KV_DB))]),
TXID_DBs = [get_db(Options, erlang:list_to_atom("tx_id-" ++ erlang:integer_to_list(I))) || I <- lists:seq(1, config:read(replication_factor))],
State = dht_node_state:new_on_recover(EmptyRT, RMState,
KV_DB, TXID_DBs, LeaseDBs, LeaseList),
3 . after the leases are known , we can start ring - maintenance and routing
4 . now we can try to refresh the local leases
msg_delay:send_trigger(1, {l_on_cseq, renew_leases}),
copied from dht_node_join
rt_loop:activate(Neighbors),
dc_clustering:activate(),
gossip:activate(Neighbors),
dht_node_reregister:activate(),
service_per_vm:register_dht_node(node:pidX(Me)),
State.
get_db(Options, DBName) ->
case lists:keyfind(DBName, 1, Options) of
false ->
log:log("error: Options:~p ~nDBName:~w", [Options, DBName]),
log:log("error in dht_node_join_recover:get_db/2. The mnesia database ~w was not found in the dht_node options (~w)", [DBName, Options]),
ok; % will fail in tab2list
{DBName, DB} ->
db_prbr:open(DB)
end.
| null |
https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/src/dht_node_join_recover.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 Join ring on recover.
@version $Id$
needed for ?RT:empty_ext/1
only for rt_chord
speed up RM
will fail in tab2list
|
2007 - 2015 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(dht_node_join_recover).
-author('').
-vsn('$Id$').
-include("scalaris.hrl").
-include("record_helpers.hrl").
-export([join/1, on/2]).
-spec join(Options::[tuple()]) ->
{'$gen_component', [{on_handler, Handler::gen_component:handler()},...],
[tuple()]}.
join(Options) ->
comm:send_local(self(), {recover_now}),
gen_component:change_handler(
Options,
fun ?MODULE:on/2).
-spec on(tuple(), [tuple()]) -> dht_node_state:state() |
{'$gen_component', [{on_handler, Handler::gen_component:handler()},...], [tuple()]}.
on({recover_now}, Options) ->
State = recover_state(Options),
gen_component:change_handler(
State,
fun dht_node:on/2);
on(Msg, Options) ->
comm:send_local(self(), Msg),
Options.
-spec recover_state(Options::[tuple()]) -> dht_node_state:state().
recover_state(Options) ->
1 . get old lease databases
LeaseDBs = [get_db(Options, erlang:list_to_atom("lease_db-" ++ erlang:integer_to_list(I))) || I <- lists:seq(1, config:read(replication_factor))],
2 . find old leases
LeaseList = lease_recover:recover(LeaseDBs),
3 . create state with old mnesias
MyId = l_on_cseq:get_id(lease_list:get_active_lease(LeaseList)),
Me = node:new(comm:this(), MyId, 0),
RMState = rm_loop:init(Me, Me, Me, null),
KV_DB = get_db(Options, kv_db),
io:format("recovered a kv_db of size ~p~n", [length(prbr:tab2list(KV_DB))]),
TXID_DBs = [get_db(Options, erlang:list_to_atom("tx_id-" ++ erlang:integer_to_list(I))) || I <- lists:seq(1, config:read(replication_factor))],
State = dht_node_state:new_on_recover(EmptyRT, RMState,
KV_DB, TXID_DBs, LeaseDBs, LeaseList),
3 . after the leases are known , we can start ring - maintenance and routing
4 . now we can try to refresh the local leases
msg_delay:send_trigger(1, {l_on_cseq, renew_leases}),
copied from dht_node_join
rt_loop:activate(Neighbors),
dc_clustering:activate(),
gossip:activate(Neighbors),
dht_node_reregister:activate(),
service_per_vm:register_dht_node(node:pidX(Me)),
State.
get_db(Options, DBName) ->
case lists:keyfind(DBName, 1, Options) of
false ->
log:log("error: Options:~p ~nDBName:~w", [Options, DBName]),
log:log("error in dht_node_join_recover:get_db/2. The mnesia database ~w was not found in the dht_node options (~w)", [DBName, Options]),
{DBName, DB} ->
db_prbr:open(DB)
end.
|
1eb3c7c115bc3b68be3c2b48ce522dd3b4d27055362c0c7c38ce4ad5eb7a107d
|
input-output-hk/ouroboros-network
|
Subscription.hs
|
{-# LANGUAGE DataKinds #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Cardano.Client.Subscription
( subscribe
, MuxMode (..)
, ClientCodecs
, ConnectionId
, LocalAddress
, NodeToClientProtocols (..)
, BlockNodeToClientVersion
, MuxPeer (..)
, MuxTrace
, RunMiniProtocol (..)
, WithMuxBearer
, ControlMessage (..)
, cChainSyncCodec
, cStateQueryCodec
, cTxSubmissionCodec
) where
import Control.Monad.Class.MonadST (MonadST)
import Control.Monad.Class.MonadSTM
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Map.Strict as Map
import Data.Proxy
import Data.Void (Void)
import Network.Mux.Trace (MuxTrace, WithMuxBearer)
import Ouroboros.Network.ControlMessage (ControlMessage (..))
import Ouroboros.Network.Magic (NetworkMagic)
import Ouroboros.Network.Mux (MuxMode (..), MuxPeer (..),
OuroborosApplication, RunMiniProtocol (..))
import Ouroboros.Network.NodeToClient (ClientSubscriptionParams (..),
ConnectionId, LocalAddress,
NetworkClientSubcriptionTracers,
NodeToClientProtocols (..), NodeToClientVersion,
NodeToClientVersionData (NodeToClientVersionData),
ncSubscriptionWorker, newNetworkMutableState,
versionedNodeToClientProtocols)
import Ouroboros.Network.Protocol.Handshake.Version (Versions,
foldMapVersions)
import qualified Ouroboros.Network.Snocket as Snocket
import Ouroboros.Consensus.Block (CodecConfig)
import Ouroboros.Consensus.Network.NodeToClient (ClientCodecs,
cChainSyncCodec, cStateQueryCodec, cTxSubmissionCodec,
clientCodecs)
import Ouroboros.Consensus.Node.NetworkProtocolVersion
(BlockNodeToClientVersion, supportedNodeToClientVersions)
import Ouroboros.Consensus.Node.Run (RunNode)
subscribe ::
RunNode blk
=> Snocket.LocalSnocket
-> CodecConfig blk
-> NetworkMagic
-> NetworkClientSubcriptionTracers
-> ClientSubscriptionParams ()
-> ( NodeToClientVersion
-> ClientCodecs blk IO
-> ConnectionId LocalAddress
-> NodeToClientProtocols 'InitiatorMode BSL.ByteString IO x y)
-> IO Void
subscribe snocket codecConfig networkMagic tracers subscriptionParams protocols = do
networkState <- newNetworkMutableState
ncSubscriptionWorker
snocket
tracers
networkState
subscriptionParams
(versionedProtocols codecConfig networkMagic
(\version codecs connectionId _ ->
protocols version codecs connectionId))
versionedProtocols ::
forall blk m appType bytes a b. (MonadST m, RunNode blk)
=> CodecConfig blk
-> NetworkMagic
-> ( NodeToClientVersion
-> ClientCodecs blk m
-> ConnectionId LocalAddress
-> STM m ControlMessage
-> NodeToClientProtocols appType bytes m a b)
^ callback which receives codecs , connection i d and STM action which
-- can be checked if the networking runtime system requests the protocols
-- to stop.
--
TODO : the ' RunOrStop ' might not be needed for - to - client@ , hence
-- it's not exposed in 'subscribe'. We should provide
' OuroborosClientApplication ' , which does not include it .
-> Versions
NodeToClientVersion
NodeToClientVersionData
(OuroborosApplication appType LocalAddress bytes m a b)
versionedProtocols codecConfig networkMagic callback =
foldMapVersions applyVersion $
Map.toList $ supportedNodeToClientVersions (Proxy @blk)
where
applyVersion ::
(NodeToClientVersion, BlockNodeToClientVersion blk)
-> Versions
NodeToClientVersion
NodeToClientVersionData
(OuroborosApplication appType LocalAddress bytes m a b)
applyVersion (version, blockVersion) =
versionedNodeToClientProtocols
version
(NodeToClientVersionData networkMagic)
(callback version (clientCodecs codecConfig blockVersion version))
| null |
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/2793b6993c8f6ed158f432055fa4ef581acdb661/cardano-client/src/Cardano/Client/Subscription.hs
|
haskell
|
# LANGUAGE DataKinds #
can be checked if the networking runtime system requests the protocols
to stop.
it's not exposed in 'subscribe'. We should provide
|
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Cardano.Client.Subscription
( subscribe
, MuxMode (..)
, ClientCodecs
, ConnectionId
, LocalAddress
, NodeToClientProtocols (..)
, BlockNodeToClientVersion
, MuxPeer (..)
, MuxTrace
, RunMiniProtocol (..)
, WithMuxBearer
, ControlMessage (..)
, cChainSyncCodec
, cStateQueryCodec
, cTxSubmissionCodec
) where
import Control.Monad.Class.MonadST (MonadST)
import Control.Monad.Class.MonadSTM
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Map.Strict as Map
import Data.Proxy
import Data.Void (Void)
import Network.Mux.Trace (MuxTrace, WithMuxBearer)
import Ouroboros.Network.ControlMessage (ControlMessage (..))
import Ouroboros.Network.Magic (NetworkMagic)
import Ouroboros.Network.Mux (MuxMode (..), MuxPeer (..),
OuroborosApplication, RunMiniProtocol (..))
import Ouroboros.Network.NodeToClient (ClientSubscriptionParams (..),
ConnectionId, LocalAddress,
NetworkClientSubcriptionTracers,
NodeToClientProtocols (..), NodeToClientVersion,
NodeToClientVersionData (NodeToClientVersionData),
ncSubscriptionWorker, newNetworkMutableState,
versionedNodeToClientProtocols)
import Ouroboros.Network.Protocol.Handshake.Version (Versions,
foldMapVersions)
import qualified Ouroboros.Network.Snocket as Snocket
import Ouroboros.Consensus.Block (CodecConfig)
import Ouroboros.Consensus.Network.NodeToClient (ClientCodecs,
cChainSyncCodec, cStateQueryCodec, cTxSubmissionCodec,
clientCodecs)
import Ouroboros.Consensus.Node.NetworkProtocolVersion
(BlockNodeToClientVersion, supportedNodeToClientVersions)
import Ouroboros.Consensus.Node.Run (RunNode)
subscribe ::
RunNode blk
=> Snocket.LocalSnocket
-> CodecConfig blk
-> NetworkMagic
-> NetworkClientSubcriptionTracers
-> ClientSubscriptionParams ()
-> ( NodeToClientVersion
-> ClientCodecs blk IO
-> ConnectionId LocalAddress
-> NodeToClientProtocols 'InitiatorMode BSL.ByteString IO x y)
-> IO Void
subscribe snocket codecConfig networkMagic tracers subscriptionParams protocols = do
networkState <- newNetworkMutableState
ncSubscriptionWorker
snocket
tracers
networkState
subscriptionParams
(versionedProtocols codecConfig networkMagic
(\version codecs connectionId _ ->
protocols version codecs connectionId))
versionedProtocols ::
forall blk m appType bytes a b. (MonadST m, RunNode blk)
=> CodecConfig blk
-> NetworkMagic
-> ( NodeToClientVersion
-> ClientCodecs blk m
-> ConnectionId LocalAddress
-> STM m ControlMessage
-> NodeToClientProtocols appType bytes m a b)
^ callback which receives codecs , connection i d and STM action which
TODO : the ' RunOrStop ' might not be needed for - to - client@ , hence
' OuroborosClientApplication ' , which does not include it .
-> Versions
NodeToClientVersion
NodeToClientVersionData
(OuroborosApplication appType LocalAddress bytes m a b)
versionedProtocols codecConfig networkMagic callback =
foldMapVersions applyVersion $
Map.toList $ supportedNodeToClientVersions (Proxy @blk)
where
applyVersion ::
(NodeToClientVersion, BlockNodeToClientVersion blk)
-> Versions
NodeToClientVersion
NodeToClientVersionData
(OuroborosApplication appType LocalAddress bytes m a b)
applyVersion (version, blockVersion) =
versionedNodeToClientProtocols
version
(NodeToClientVersionData networkMagic)
(callback version (clientCodecs codecConfig blockVersion version))
|
be1c2b168dd0a912410c5c82f32f483eac496535cc62cd8638261c97445a8e08
|
bozsahin/yalalr
|
sdd.lisp
|
this example generates Lisp code for CCG grammar using ccglab syntax
-cem bozsahin
;;; some auxiliary definitions needed by code generator
(defparameter *ccg-grammar* nil) ; current ccg grammar, as a list of Lisp-translated lex specs
unique keys for each entry ; from 1 to n
;; ==============================================
;; The lambda layer, whose syntax is given below.
;; ==============================================
;;
this is a direct import of Alessandro Cimatti 's ADT for Lambda - calculus .
;; Thanks for putting it on the web.
;; (minor addition for our purposes: singleton e can be symbol OR constant)
The ADT for expressions
;; e ::= v | l | a
;; v ::= symbolp | constantp
;; a ::= ( e e )
;; l :: = ( lam v e )
(defun mk-v (sym) sym)
(defun is-v (e) (cond ((consp e) nil)
((symbolp e) t)
((constantp e) t)
((special-operator-p e) t)
(t nil)))
(defun mk-l (v b) (list 'lam v b))
(defun is-l (e) (and (consp e) (= (length e) 3) (equal 'lam (first e)) (is-v (second e))))
(defun l-get-v (l) (second l))
(defun l-get-b (l) (third l))
(defun mk-a (f a) (list f a))
(defun is-a (e) (and (consp e) (= (length e) 2)))
(defun a-get-f (a) (first a))
(defun a-get-a (a) (second a))
(defun freshvar ()(gensym))
;; Recognizer. takes arbitrary s-exp in input
(defun is-e (e)
(cond ((is-v e) t)
((is-a e) (and
(is-e (a-get-f e))
(is-e (a-get-a e))))
((is-l e) (and
(is-e (l-get-v e))
(is-e (l-get-b e))))
(t nil)))
;; Return the free variables of an expression
(defun fv (e)
(cond
((is-v e) (list e))
((is-a e) (append
(fv (a-get-f e))
(fv (a-get-a e))))
((is-l e) (remove
(l-get-v e)
(fv (l-get-b e))))
(t (error "Unknown lambda term type"))))
(defun free-in (v e) (member v (fv e)))
;; equivalence up to alpha conversion
(defun alpha-equivalent1 (e1 e2 rpl1 rpl2)
(cond
((is-v e1)
(and (is-v e2)
(let ((new1 (cdr (assoc e1 rpl1)))
(new2 (cdr (assoc e2 rpl2))))
(if (and (null new1) (null new2))
(equal e1 e2)
(equal new1 new2)))))
((is-a e1)
(and (is-a e2)
(alpha-equivalent1 (a-get-f e1) (a-get-f e2) rpl1 rpl2)
(alpha-equivalent1 (a-get-a e1) (a-get-a e2) rpl1 rpl2)))
((is-l e1)
(and (is-l e2)
(let* ((new (freshvar))
(old1 (l-get-v e1))
(old2 (l-get-v e2))
(newrpl1 (cons (cons old1 new) rpl1))
(newrpl2 (cons (cons old2 new) rpl2)))
(alpha-equivalent1 (l-get-b e1) (l-get-b e2) newrpl1 newrpl2))))))
(defun alpha-equivalent (e1 e2) (alpha-equivalent1 e1 e2 nil nil))
;; substitution
(defun subst-with-in (x e1 exp)
(cond
((is-v exp)
(if (equal x exp) e1 exp))
((is-a exp)
(mk-a
(subst-with-in x e1 (a-get-f exp))
(subst-with-in x e1 (a-get-a exp))))
((is-l exp) ; say exp is (lam y e)
(let ((y (l-get-v exp)) (e (l-get-b exp)))
(cond
((equal x y) exp)
((not (free-in x e)) exp)
((and (free-in x e) (not (free-in y e1)))
(mk-l y (subst-with-in x e1 e)))
((and (free-in x e) (free-in y e1))
(let ((z (freshvar)))
(mk-l z (subst-with-in x e1 (subst-with-in y z e))))))))))
;; beta reduction
(defun is-rdx (e) (and (is-a e) (is-l (a-get-f e))))
(defun rdx-get-v (rdx) (l-get-v (a-get-f rdx)))
(defun rdx-get-b (rdx) (l-get-b (a-get-f rdx)))
(defun rdx-get-a (rdx) (a-get-a rdx))
;; Beta reduce: (a (l v e) e1) ==> [e1 / v] e
(defun beta-reduce (rdx)
(subst-with-in
(rdx-get-v rdx)
(rdx-get-a rdx)
(rdx-get-b rdx)))
;; Beta reduce if possible
(defun beta-reduce-if-redex (e)
(if (is-rdx e) (beta-reduce e) e))
;; Iterate beta reduction on outermost redex
(defun beta-reduce-outer (e &optional (lim 100))
(cond
((< lim 0) e)
((is-rdx e)
(beta-reduce-outer (beta-reduce e) (- lim 1)))
((is-v e) e)
((is-a e)
(mk-a
(beta-reduce-outer (a-get-f e))
(beta-reduce-outer (a-get-a e))))
((is-l e)
(mk-l
(l-get-v e)
(beta-reduce-outer (l-get-b e))))))
;; Iterate beta reduction on innermost redex
(defun beta-reduce-inner (e &optional (lim 100))
(cond
((< lim 0) e)
((is-v e) e)
((is-a e)
(beta-reduce-if-redex
(mk-a (beta-reduce-inner (a-get-f e) lim)
(beta-reduce-inner (a-get-a e) lim))))
((is-l e)
(mk-l
(l-get-v e)
(beta-reduce-inner (l-get-b e) lim)))))
;; Beta normalization
(defun beta-normalize-param (e fn &optional (lim 100))
(let* ((res (apply fn (list e lim)))
(use-alpha-equivalent t)
(stop (if use-alpha-equivalent
(alpha-equivalent res e)
(equal res e))))
(if stop
res ; fix point reached
(beta-normalize-param res fn))))
(defun beta-normalize-outer (e &optional (lim 100))
(beta-normalize-param e 'beta-reduce-outer lim))
(defun beta-normalize-inner (e &optional (lim 100))
(beta-normalize-param e 'beta-reduce-inner lim))
try with the two different strategies and compare results
(defun beta-normalize (e)
(let ((res-inner (beta-normalize-inner e 100))
(res-outer (beta-normalize-outer e 100)))
(if (alpha-equivalent res-outer res-inner)
(progn
(format t "Results are alpha equivalent~%")
(format t "Inner: ~A~%" res-inner)
(format t "Outer: ~A~2%" res-outer))
(progn
(format t "Results are NOT alpha-equivalent!")
(format t "Inner: ~A~%" res-inner)
(format t "Outer: ~A~2%" res-outer)))))
the LALR input
(defparameter grammar
'((gram --> start #'(lambda (start) (list 'defparameter '*ccg-grammar* `(quote ,start))))
(start --> start lex END #'(lambda (start lex END) (append start (list lex))))
(start --> lex END #'(lambda (lex END)(list lex)))
(lex --> ID mtag SPECOP cat #'(lambda (ID mtag SPECOP cat)(progn (incf *ccg-grammar-keys*)
(list (list 'KEY *ccg-grammar-keys*)
(list 'PHON (cadr ID))
mtag (first cat) (second cat) (list 'PARAM 1.0)))))
(lex --> lrule #'(lambda (lrule)(progn (incf *ccg-grammar-keys*)
(list (list 'KEY *ccg-grammar-keys*)
(list 'INSYN (second (first (rest (first lrule)))))
(list 'INSEM (second (second (rest (first lrule)))))
(list 'OUTSYN (second (second lrule)))
(list 'OUTSEM (second (third lrule)))
(list 'INDEX (second (first (first lrule)))) ; rule name
(list 'PARAM 1.0)))))
(lrule --> LP ID RP cat1
ARROW cat #'(lambda (LP ID RP cat1 ARROW cat)(cons (cons ID cat1) cat)))
(mtag --> ID #'(lambda (ID)(list 'MORPH (cadr ID))))
(cat1 --> cat #'(lambda (cat)(identity cat)))
(cat --> syns COLON lf #'(lambda (syns COLON lf)(cons (list 'SYN syns) (list (list 'SEM lf)))))
(syns --> basic #'(lambda (basic)(identity basic)))
(syns --> parentd #'(lambda (parentd)(identity parentd)))
(syns --> syns slash syn #'(lambda (syns slash syn)`(,syns ,@slash ,syn)))
(syn --> basic #'(lambda (basic)(identity basic)))
(syn --> parentd #'(lambda (parentd)(identity parentd)))
(basic --> ID feats #'(lambda (ID feats)(list (list 'BCAT (cadr ID)) (list 'FEATS feats))))
(parentd --> LP syns RP #'(lambda (LP syns RP) (identity syns)))
(slash --> vardir varmod #'(lambda (vardir varmod)(list vardir varmod)))
(slash --> vardouble #'(lambda (vardouble)(identity vardouble)))
(feats --> LB eqns RB #'(lambda (LB eqns RB) (identity eqns)))
(feats #'(lambda () nil))
(eqns --> eqns COMMA eqn #'(lambda (eqns COMMA eqn)(append eqns (list eqn))))
(eqns --> eqn #'(lambda (eqn)(list eqn)))
(eqn --> ID1 EQOP ID #'(lambda (ID1 EQOP ID)(list (cadr ID1) (cadr ID))))
(ID1 --> ID #'(lambda (ID) (identity ID)))
(vardouble --> VALFS2 VALFS #'(lambda (VALFS2 VALFS)(list (list 'DIR 'FS)(list 'MODAL 'STAR)(list 'LEX t))))
(vardouble --> VALBS2 VALBS #'(lambda (VALBS2 VALBS)(list (list 'DIR 'BS)(list 'MODAL 'STAR)(list 'LEX t))))
(VALFS2 --> VALFS #'(lambda (VALFS)(identity VALFS)))
(VALBS2 --> VALBS #'(lambda (VALBS)(identity VALBS)))
(vardir --> VALFS #'(lambda (VALFS)(list 'DIR 'FS)))
(vardir --> VALBS #'(lambda (VALBS)(list 'DIR 'BS )))
(varmod --> MODAL #'(lambda (MODAL)(cond ((equalp (cadr MODAL) '^) (list 'MODAL 'HARMONIC))
((equalp (cadr MODAL) '+) (list 'MODAL 'CROSS))
((equalp (cadr MODAL) '*) (list 'MODAL 'STAR))
(t (list 'MODAL '*UNKNOWN*)))))
(varmod --> VALDOT #'(lambda (VALDOT)(list 'MODAL 'ALL)))
(varmod --> #'(lambda ()(list 'MODAL 'ALL)))
(vardot --> VALDOT #'(lambda(VALDOT)(identity nil)))
(vardot --> #'(lambda()(identity nil)))
(lf --> bodys #'(lambda (bodys)(identity bodys)))
(lf --> lterm #'(lambda (lterm)(identity lterm)))
(lterm --> VALBS ID vardot
lbody #'(lambda (VALBS ID vardot lbody)(mk-l (mk-v (cadr ID)) lbody)))
(lbody --> lterm #'(lambda (lterm)(identity lterm))) ; lambda bindings are right-associative.
(lbody --> bodys #'(lambda (bodys)(identity bodys)))
(bodys --> bodys body #'(lambda (bodys body)(mk-a bodys body))) ; LF concatenation is left-associative.
(bodys --> body #'(lambda (body)(identity body)))
in lexical specs , we do n't expect inner lambdas in the LF body .
(body --> ID #'(lambda (ID)(cadr ID)))
))
(defparameter lexforms '(VALFS ID MODAL END VALBS
VALDOT SPECOP COLON ARROW
LP RP LB RB COMMA EQOP))
(defparameter lexicon '((|/| VALFS)
(\\ VALBS)
(\^ MODAL)
(\* MODAL)
(\+ MODAL)
(|.| VALDOT)
(|,| COMMA)
(\; END)
(|:=| SPECOP)
(|:| COLON)
(|-->| ARROW)
(|(| LP)
(|)| RP)
(|[| LB)
(|]| RB)
(|=| EQOP)
($ $) ; this is for lalrparser.lisp's end of input
))
;; if you change the end-marker, change its hardcopy above in lexicon above as well.
( because LALR parser does not evaluate its lexicon symbols --- sorry . )
(defparameter *ENDMARKER* '$)
| null |
https://raw.githubusercontent.com/bozsahin/yalalr/ebf7a3d388e889c101eb4bed9690acb7cb236cf7/examples/ex2/sdd.lisp
|
lisp
|
some auxiliary definitions needed by code generator
current ccg grammar, as a list of Lisp-translated lex specs
from 1 to n
==============================================
The lambda layer, whose syntax is given below.
==============================================
Thanks for putting it on the web.
(minor addition for our purposes: singleton e can be symbol OR constant)
e ::= v | l | a
v ::= symbolp | constantp
a ::= ( e e )
l :: = ( lam v e )
Recognizer. takes arbitrary s-exp in input
Return the free variables of an expression
equivalence up to alpha conversion
substitution
say exp is (lam y e)
beta reduction
Beta reduce: (a (l v e) e1) ==> [e1 / v] e
Beta reduce if possible
Iterate beta reduction on outermost redex
Iterate beta reduction on innermost redex
Beta normalization
fix point reached
rule name
lambda bindings are right-associative.
LF concatenation is left-associative.
END)
this is for lalrparser.lisp's end of input
if you change the end-marker, change its hardcopy above in lexicon above as well.
|
this example generates Lisp code for CCG grammar using ccglab syntax
-cem bozsahin
this is a direct import of Alessandro Cimatti 's ADT for Lambda - calculus .
The ADT for expressions
(defun mk-v (sym) sym)
(defun is-v (e) (cond ((consp e) nil)
((symbolp e) t)
((constantp e) t)
((special-operator-p e) t)
(t nil)))
(defun mk-l (v b) (list 'lam v b))
(defun is-l (e) (and (consp e) (= (length e) 3) (equal 'lam (first e)) (is-v (second e))))
(defun l-get-v (l) (second l))
(defun l-get-b (l) (third l))
(defun mk-a (f a) (list f a))
(defun is-a (e) (and (consp e) (= (length e) 2)))
(defun a-get-f (a) (first a))
(defun a-get-a (a) (second a))
(defun freshvar ()(gensym))
(defun is-e (e)
(cond ((is-v e) t)
((is-a e) (and
(is-e (a-get-f e))
(is-e (a-get-a e))))
((is-l e) (and
(is-e (l-get-v e))
(is-e (l-get-b e))))
(t nil)))
(defun fv (e)
(cond
((is-v e) (list e))
((is-a e) (append
(fv (a-get-f e))
(fv (a-get-a e))))
((is-l e) (remove
(l-get-v e)
(fv (l-get-b e))))
(t (error "Unknown lambda term type"))))
(defun free-in (v e) (member v (fv e)))
(defun alpha-equivalent1 (e1 e2 rpl1 rpl2)
(cond
((is-v e1)
(and (is-v e2)
(let ((new1 (cdr (assoc e1 rpl1)))
(new2 (cdr (assoc e2 rpl2))))
(if (and (null new1) (null new2))
(equal e1 e2)
(equal new1 new2)))))
((is-a e1)
(and (is-a e2)
(alpha-equivalent1 (a-get-f e1) (a-get-f e2) rpl1 rpl2)
(alpha-equivalent1 (a-get-a e1) (a-get-a e2) rpl1 rpl2)))
((is-l e1)
(and (is-l e2)
(let* ((new (freshvar))
(old1 (l-get-v e1))
(old2 (l-get-v e2))
(newrpl1 (cons (cons old1 new) rpl1))
(newrpl2 (cons (cons old2 new) rpl2)))
(alpha-equivalent1 (l-get-b e1) (l-get-b e2) newrpl1 newrpl2))))))
(defun alpha-equivalent (e1 e2) (alpha-equivalent1 e1 e2 nil nil))
(defun subst-with-in (x e1 exp)
(cond
((is-v exp)
(if (equal x exp) e1 exp))
((is-a exp)
(mk-a
(subst-with-in x e1 (a-get-f exp))
(subst-with-in x e1 (a-get-a exp))))
(let ((y (l-get-v exp)) (e (l-get-b exp)))
(cond
((equal x y) exp)
((not (free-in x e)) exp)
((and (free-in x e) (not (free-in y e1)))
(mk-l y (subst-with-in x e1 e)))
((and (free-in x e) (free-in y e1))
(let ((z (freshvar)))
(mk-l z (subst-with-in x e1 (subst-with-in y z e))))))))))
(defun is-rdx (e) (and (is-a e) (is-l (a-get-f e))))
(defun rdx-get-v (rdx) (l-get-v (a-get-f rdx)))
(defun rdx-get-b (rdx) (l-get-b (a-get-f rdx)))
(defun rdx-get-a (rdx) (a-get-a rdx))
(defun beta-reduce (rdx)
(subst-with-in
(rdx-get-v rdx)
(rdx-get-a rdx)
(rdx-get-b rdx)))
(defun beta-reduce-if-redex (e)
(if (is-rdx e) (beta-reduce e) e))
(defun beta-reduce-outer (e &optional (lim 100))
(cond
((< lim 0) e)
((is-rdx e)
(beta-reduce-outer (beta-reduce e) (- lim 1)))
((is-v e) e)
((is-a e)
(mk-a
(beta-reduce-outer (a-get-f e))
(beta-reduce-outer (a-get-a e))))
((is-l e)
(mk-l
(l-get-v e)
(beta-reduce-outer (l-get-b e))))))
(defun beta-reduce-inner (e &optional (lim 100))
(cond
((< lim 0) e)
((is-v e) e)
((is-a e)
(beta-reduce-if-redex
(mk-a (beta-reduce-inner (a-get-f e) lim)
(beta-reduce-inner (a-get-a e) lim))))
((is-l e)
(mk-l
(l-get-v e)
(beta-reduce-inner (l-get-b e) lim)))))
(defun beta-normalize-param (e fn &optional (lim 100))
(let* ((res (apply fn (list e lim)))
(use-alpha-equivalent t)
(stop (if use-alpha-equivalent
(alpha-equivalent res e)
(equal res e))))
(if stop
(beta-normalize-param res fn))))
(defun beta-normalize-outer (e &optional (lim 100))
(beta-normalize-param e 'beta-reduce-outer lim))
(defun beta-normalize-inner (e &optional (lim 100))
(beta-normalize-param e 'beta-reduce-inner lim))
try with the two different strategies and compare results
(defun beta-normalize (e)
(let ((res-inner (beta-normalize-inner e 100))
(res-outer (beta-normalize-outer e 100)))
(if (alpha-equivalent res-outer res-inner)
(progn
(format t "Results are alpha equivalent~%")
(format t "Inner: ~A~%" res-inner)
(format t "Outer: ~A~2%" res-outer))
(progn
(format t "Results are NOT alpha-equivalent!")
(format t "Inner: ~A~%" res-inner)
(format t "Outer: ~A~2%" res-outer)))))
the LALR input
(defparameter grammar
'((gram --> start #'(lambda (start) (list 'defparameter '*ccg-grammar* `(quote ,start))))
(start --> start lex END #'(lambda (start lex END) (append start (list lex))))
(start --> lex END #'(lambda (lex END)(list lex)))
(lex --> ID mtag SPECOP cat #'(lambda (ID mtag SPECOP cat)(progn (incf *ccg-grammar-keys*)
(list (list 'KEY *ccg-grammar-keys*)
(list 'PHON (cadr ID))
mtag (first cat) (second cat) (list 'PARAM 1.0)))))
(lex --> lrule #'(lambda (lrule)(progn (incf *ccg-grammar-keys*)
(list (list 'KEY *ccg-grammar-keys*)
(list 'INSYN (second (first (rest (first lrule)))))
(list 'INSEM (second (second (rest (first lrule)))))
(list 'OUTSYN (second (second lrule)))
(list 'OUTSEM (second (third lrule)))
(list 'PARAM 1.0)))))
(lrule --> LP ID RP cat1
ARROW cat #'(lambda (LP ID RP cat1 ARROW cat)(cons (cons ID cat1) cat)))
(mtag --> ID #'(lambda (ID)(list 'MORPH (cadr ID))))
(cat1 --> cat #'(lambda (cat)(identity cat)))
(cat --> syns COLON lf #'(lambda (syns COLON lf)(cons (list 'SYN syns) (list (list 'SEM lf)))))
(syns --> basic #'(lambda (basic)(identity basic)))
(syns --> parentd #'(lambda (parentd)(identity parentd)))
(syns --> syns slash syn #'(lambda (syns slash syn)`(,syns ,@slash ,syn)))
(syn --> basic #'(lambda (basic)(identity basic)))
(syn --> parentd #'(lambda (parentd)(identity parentd)))
(basic --> ID feats #'(lambda (ID feats)(list (list 'BCAT (cadr ID)) (list 'FEATS feats))))
(parentd --> LP syns RP #'(lambda (LP syns RP) (identity syns)))
(slash --> vardir varmod #'(lambda (vardir varmod)(list vardir varmod)))
(slash --> vardouble #'(lambda (vardouble)(identity vardouble)))
(feats --> LB eqns RB #'(lambda (LB eqns RB) (identity eqns)))
(feats #'(lambda () nil))
(eqns --> eqns COMMA eqn #'(lambda (eqns COMMA eqn)(append eqns (list eqn))))
(eqns --> eqn #'(lambda (eqn)(list eqn)))
(eqn --> ID1 EQOP ID #'(lambda (ID1 EQOP ID)(list (cadr ID1) (cadr ID))))
(ID1 --> ID #'(lambda (ID) (identity ID)))
(vardouble --> VALFS2 VALFS #'(lambda (VALFS2 VALFS)(list (list 'DIR 'FS)(list 'MODAL 'STAR)(list 'LEX t))))
(vardouble --> VALBS2 VALBS #'(lambda (VALBS2 VALBS)(list (list 'DIR 'BS)(list 'MODAL 'STAR)(list 'LEX t))))
(VALFS2 --> VALFS #'(lambda (VALFS)(identity VALFS)))
(VALBS2 --> VALBS #'(lambda (VALBS)(identity VALBS)))
(vardir --> VALFS #'(lambda (VALFS)(list 'DIR 'FS)))
(vardir --> VALBS #'(lambda (VALBS)(list 'DIR 'BS )))
(varmod --> MODAL #'(lambda (MODAL)(cond ((equalp (cadr MODAL) '^) (list 'MODAL 'HARMONIC))
((equalp (cadr MODAL) '+) (list 'MODAL 'CROSS))
((equalp (cadr MODAL) '*) (list 'MODAL 'STAR))
(t (list 'MODAL '*UNKNOWN*)))))
(varmod --> VALDOT #'(lambda (VALDOT)(list 'MODAL 'ALL)))
(varmod --> #'(lambda ()(list 'MODAL 'ALL)))
(vardot --> VALDOT #'(lambda(VALDOT)(identity nil)))
(vardot --> #'(lambda()(identity nil)))
(lf --> bodys #'(lambda (bodys)(identity bodys)))
(lf --> lterm #'(lambda (lterm)(identity lterm)))
(lterm --> VALBS ID vardot
lbody #'(lambda (VALBS ID vardot lbody)(mk-l (mk-v (cadr ID)) lbody)))
(lbody --> bodys #'(lambda (bodys)(identity bodys)))
(bodys --> body #'(lambda (body)(identity body)))
in lexical specs , we do n't expect inner lambdas in the LF body .
(body --> ID #'(lambda (ID)(cadr ID)))
))
(defparameter lexforms '(VALFS ID MODAL END VALBS
VALDOT SPECOP COLON ARROW
LP RP LB RB COMMA EQOP))
(defparameter lexicon '((|/| VALFS)
(\\ VALBS)
(\^ MODAL)
(\* MODAL)
(\+ MODAL)
(|.| VALDOT)
(|,| COMMA)
(|:=| SPECOP)
(|:| COLON)
(|-->| ARROW)
(|(| LP)
(|)| RP)
(|[| LB)
(|]| RB)
(|=| EQOP)
))
( because LALR parser does not evaluate its lexicon symbols --- sorry . )
(defparameter *ENDMARKER* '$)
|
a1a83f6f82cc3c64c0601eafb025dd0618e0f3597767346e234848bb12ed6df9
|
brunoV/throttler
|
project.clj
|
(defproject throttler "1.0.1"
:description "Control the throughput of function calls and core.async channels using the token bucket algorithm"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.0"]
[org.clojure/core.async "0.4.490"]]
:profiles {:dev {:dependencies [[midje "1.9.8"]
[criterium "0.4.5"]]
:plugins [[lein-midje "3.1.1"]]}})
| null |
https://raw.githubusercontent.com/brunoV/throttler/1e845d72fdd22cce6445d17624895fa2692b66e5/project.clj
|
clojure
|
(defproject throttler "1.0.1"
:description "Control the throughput of function calls and core.async channels using the token bucket algorithm"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.0"]
[org.clojure/core.async "0.4.490"]]
:profiles {:dev {:dependencies [[midje "1.9.8"]
[criterium "0.4.5"]]
:plugins [[lein-midje "3.1.1"]]}})
|
|
7a5080e40c168525fc34ff43aa09931efb3a0bb97d6fa66fe36253580dfb51c0
|
patricoferris/ocaml-multicore-monorepo
|
unit.ml
|
This file is part of Dream , released under the MIT license . See LICENSE.md
for details , or visit .
Copyright 2021
for details, or visit .
Copyright 2021 Anton Bachin *)
let () =
Alcotest.run "Dream" [
Request.tests;
Headers.tests;
]
| null |
https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/dream/test/unit/unit.ml
|
ocaml
|
This file is part of Dream , released under the MIT license . See LICENSE.md
for details , or visit .
Copyright 2021
for details, or visit .
Copyright 2021 Anton Bachin *)
let () =
Alcotest.run "Dream" [
Request.tests;
Headers.tests;
]
|
|
dcdcf6fcc29397d054e140b37488e8093bc735242cfa1e363f27c7d5f7fd1645
|
rtoy/cmucl
|
read-insert.lisp
|
(in-package :cl-haml)
(defun read-haml-insert-line (stream &optional (eof-error-p nil)
(eof-value +eof+))
(list +haml+
(read-contents stream
(read-options stream
eof-error-p
eof-value)
eof-error-p
eof-value)))
| null |
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/tests/resources/read-insert.lisp
|
lisp
|
(in-package :cl-haml)
(defun read-haml-insert-line (stream &optional (eof-error-p nil)
(eof-value +eof+))
(list +haml+
(read-contents stream
(read-options stream
eof-error-p
eof-value)
eof-error-p
eof-value)))
|
|
e67b8cd6ab846cc0a485de7bda75b498033414fcaca06f866c2155347a31761c
|
ucsd-progsys/nate
|
odoc_cross.mli
|
(***********************************************************************)
(* OCamldoc *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : odoc_cross.mli , v 1.3 2006/09/20 11:14:36 doligez Exp $
(** Cross-referencing. *)
val associate : Odoc_module.t_module list -> unit
val assoc_comments_info :
string -> Odoc_module.t_module list ->
Odoc_types.info -> Odoc_types.info
| null |
https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/ocamldoc/odoc_cross.mli
|
ocaml
|
*********************************************************************
OCamldoc
*********************************************************************
* Cross-referencing.
|
, projet Cristal , INRIA Rocquencourt
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : odoc_cross.mli , v 1.3 2006/09/20 11:14:36 doligez Exp $
val associate : Odoc_module.t_module list -> unit
val assoc_comments_info :
string -> Odoc_module.t_module list ->
Odoc_types.info -> Odoc_types.info
|
6acbaf0093f8df3b7fc90335eea2edbffe1913550fadbdc6fabaaa8205ceef3c
|
EFanZh/EOPL-Exercises
|
exercise-5.46.rkt
|
#lang eopl
Exercise 5.46 [ ★ ★ ] In the systemof exercise 5.45 , a thread may be placed on the ready queue either because its time
;; slot has been exhausted or because it chose to yield. In the latter case, it will be restarted with a full time
;; slice. Modify the system so that the ready queue keeps track of the remaining time slice (if any) of each thread, and
;; restarts the thread only with the time it has remaining.
;; Grammar.
(define the-lexical-spec
'([whitespace (whitespace) skip]
[comment ("%" (arbno (not #\newline))) skip]
[identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol]
[number (digit (arbno digit)) number]
[number ("-" digit (arbno digit)) number]))
(define the-grammar
'([program (expression) a-program]
[expression (number) const-exp]
[expression ("[" (separated-list number ",") "]") const-list-exp]
[expression (identifier) var-exp]
[expression ("-" "(" expression "," expression ")") diff-exp]
[expression ("if" expression "then" expression "else" expression) if-exp]
[expression ("proc" "(" identifier ")" expression) proc-exp]
[expression ("(" expression expression ")") call-exp]
[expression ("begin" expression (arbno ";" expression) "end") begin-exp]
[expression ("let" identifier "=" expression "in" expression) let-exp]
[expression ("letrec" (arbno identifier "(" identifier ")" "=" expression) "in" expression) letrec-exp]
[expression ("set" identifier "=" expression) set-exp]
[expression ("spawn" "(" expression ")") spawn-exp]
[expression ("yield" "(" ")") yield-exp]
[expression ("mutex" "(" ")") mutex-exp]
[expression ("wait" "(" expression ")") wait-exp]
[expression ("signal" "(" expression ")") signal-exp]
[expression (unop "(" expression ")") unop-exp]
[unop ("car") car-unop]
[unop ("cdr") cdr-unop]
[unop ("null?") null?-unop]
[unop ("zero?") zero?-unop]
[unop ("print") print-unop]))
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar))
;; Data structures.
;; References.
(define reference?
(lambda (v)
(integer? v)))
;; Store.
(define the-store 'uninitialized)
(define empty-store
(lambda ()
'()))
(define initialize-store!
(lambda ()
(set! the-store (empty-store))))
(define newref
(lambda (val)
(let ([next-ref (length the-store)])
(set! the-store (append the-store (list val)))
next-ref)))
(define deref
(lambda (ref)
(list-ref the-store ref)))
(define report-invalid-reference
(lambda (ref the-store)
(eopl:error 'setref "illegal reference ~s in store ~s" ref the-store)))
(define setref!
(lambda (ref val)
(set! the-store
(letrec ([setref-inner (lambda (store1 ref1)
(cond [(null? store1) (report-invalid-reference ref the-store)]
[(zero? ref1) (cons val (cdr store1))]
[else (cons (car store1) (setref-inner (cdr store1) (- ref1 1)))]))])
(setref-inner the-store ref)))))
;; Procedures.
(define-datatype proc proc?
[procedure [bvar symbol?]
[body expression?]
[env environment?]])
(define fresh-identifier
(let ([sn 0])
(lambda (identifier)
(set! sn (+ sn 1))
(string->symbol (string-append (symbol->string identifier) "%" (number->string sn))))))
;; Queue.
(define empty-queue
(lambda ()
'()))
(define empty? null?)
(define enqueue
(lambda (q val)
(append q (list val))))
(define dequeue
(lambda (q f)
(f (car q) (cdr q))))
;; Thread.
(define-datatype thread thread?
[a-thread [thunk procedure?]
[time-remaining integer?]])
;; Scheduler.
(define the-ready-queue 'uninitialized)
(define the-final-answer 'uninitialized)
(define the-max-time-slice 'uninitialized)
(define the-time-remaining 'uninitialized)
(define initialize-scheduler!
(lambda (ticks)
(set! the-ready-queue (empty-queue))
(set! the-final-answer 'uninitialized)
(set! the-max-time-slice ticks)
(set! the-time-remaining the-max-time-slice)))
(define place-on-ready-queue!
(lambda (th)
(set! the-ready-queue (enqueue the-ready-queue th))))
(define time-expired?
(lambda ()
(zero? the-time-remaining)))
(define decrement-timer!
(lambda ()
(set! the-time-remaining (- the-time-remaining 1))))
(define set-final-answer!
(lambda (val)
(set! the-final-answer val)))
(define run-next-thread
(lambda ()
(if (empty? the-ready-queue)
the-final-answer
(dequeue the-ready-queue
(lambda (first-ready-thread other-ready-threads)
(set! the-ready-queue other-ready-threads)
(cases thread first-ready-thread
[a-thread (thunk time-remaining)
(set! the-time-remaining time-remaining)
(thunk)]))))))
Mutexes .
(define-datatype mutex mutex?
[a-mutex [ref-to-closed? reference?]
[ref-to-wait-queue reference?]])
(define new-mutex
(lambda ()
(a-mutex (newref #f) (newref '()))))
(define wait-for-mutex
(lambda (m th)
(cases mutex m
[a-mutex (ref-to-closed? ref-to-wait-queue)
(cond [(deref ref-to-closed?) (setref! ref-to-wait-queue
(enqueue (deref ref-to-wait-queue)
(a-thread th the-max-time-slice)))
(run-next-thread)]
[else (setref! ref-to-closed? #t)
(th)])])))
(define signal-mutex
(lambda (m th)
(cases mutex m
[a-mutex (ref-to-closed? ref-to-wait-queue) (let ([closed? (deref ref-to-closed?)]
[wait-queue (deref ref-to-wait-queue)])
(when closed?
(if (empty? wait-queue)
(setref! ref-to-closed? #f)
(dequeue wait-queue
(lambda (first-waiting-th other-waiting-ths)
(place-on-ready-queue! first-waiting-th)
(setref! ref-to-wait-queue other-waiting-ths)))))
(th))])))
;; Expressed values.
(define-datatype expval expval?
[num-val [value number?]]
[bool-val [boolean boolean?]]
[proc-val [proc proc?]]
[list-val [lst (list-of expval?)]]
[mutex-val [mutex mutex?]])
(define expval-extractor-error
(lambda (variant value)
(eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value)))
(define expval->num
(lambda (v)
(cases expval v
[num-val (num) num]
[else (expval-extractor-error 'num v)])))
(define expval->bool
(lambda (v)
(cases expval v
[bool-val (bool) bool]
[else (expval-extractor-error 'bool v)])))
(define expval->proc
(lambda (v)
(cases expval v
[proc-val (proc) proc]
[else (expval-extractor-error 'proc v)])))
(define expval->list
(lambda (v)
(cases expval v
[list-val (lst) lst]
[else (expval-extractor-error 'list v)])))
(define expval->mutex
(lambda (v)
(cases expval v
[mutex-val (l) l]
[else (expval-extractor-error 'mutex v)])))
;; Environment.
(define environment?
(list-of (lambda (p)
(and (pair? p) (or (symbol? (car p)) ((list-of symbol?) (car p)))))))
(define empty-env
(lambda ()
'()))
(define extend-env
(lambda (sym val old-env)
(cons (list sym val) old-env)))
(define extend-env-rec*
(lambda (p-names b-vars p-bodies saved-env)
(cons (list p-names b-vars p-bodies) saved-env)))
(define locate
(lambda (sym los)
(let loop ((pos 0) (los los))
(cond [(null? los) #f]
[(eqv? sym (car los)) pos]
[else (loop (+ pos 1) (cdr los))]))))
(define apply-env
(lambda (env search-sym)
(if (null? env)
(eopl:error 'apply-env "No binding for ~s" search-sym)
(let* ((binding (car env))
(saved-env (cdr env)))
(if (symbol? (car binding))
(if (eqv? search-sym (car binding))
(cadr binding)
(apply-env saved-env search-sym))
(let ([pos (locate search-sym (car binding))]
[b-vars (cadr binding)]
[p-bodies (caddr binding)])
(if pos
(newref (proc-val (procedure (list-ref b-vars pos) (list-ref p-bodies pos) env)))
(apply-env saved-env search-sym))))))))
;; Continuation.
(define-datatype continuation continuation?
[end-main-thread-cont]
[end-subthread-cont]
[diff1-cont [exp2 expression?]
[env environment?]
[cont continuation?]]
[diff2-cont [val1 expval?]
[cont continuation?]]
[if-test-cont [exp2 expression?]
[exp3 expression?]
[env environment?]
[cont continuation?]]
[rator-cont [rand expression?]
[env environment?]
[cont continuation?]]
[rand-cont [val1 expval?]
[cont continuation?]]
[set-rhs-cont [loc reference?]
[cont continuation?]]
[spawn-cont [saved-cont continuation?]]
[wait-cont [saved-cont continuation?]]
[signal-cont [saved-cont continuation?]]
[unop-arg-cont [unop1 unop?]
[cont continuation?]])
;; Interpreter.
(define apply-unop
(lambda (unop1 arg cont)
(cases unop unop1
[zero?-unop () (apply-cont cont (bool-val (zero? (expval->num arg))))]
[car-unop () (let ([lst (expval->list arg)])
(apply-cont cont (car lst)))]
[cdr-unop () (let ([lst (expval->list arg)])
(apply-cont cont (list-val (cdr lst))))]
[null?-unop () (apply-cont cont (bool-val (null? (expval->list arg))))]
[print-unop () (begin (eopl:printf "~a~%" (expval->num arg))
(apply-cont cont (num-val 1)))])))
(define apply-procedure
(lambda (proc1 arg cont)
(cases proc proc1
[procedure (var body saved-env) (value-of/k body (extend-env var (newref arg) saved-env) cont)])))
(define apply-cont
(lambda (cont val)
(if (time-expired?)
(begin (place-on-ready-queue! (a-thread (lambda ()
(apply-cont cont val))
the-max-time-slice))
(run-next-thread))
(begin (decrement-timer!)
(cases continuation cont
[end-main-thread-cont ()
(set-final-answer! val)
(run-next-thread)]
[end-subthread-cont () (run-next-thread)]
[diff1-cont (exp2 saved-env saved-cont) (value-of/k exp2 saved-env (diff2-cont val saved-cont))]
[diff2-cont (val1 saved-cont) (let ([n1 (expval->num val1)]
[n2 (expval->num val)])
(apply-cont saved-cont (num-val (- n1 n2))))]
[if-test-cont (exp2 exp3 env cont) (if (expval->bool val)
(value-of/k exp2 env cont)
(value-of/k exp3 env cont))]
[rator-cont (rand saved-env saved-cont) (value-of/k rand saved-env (rand-cont val saved-cont))]
[rand-cont (val1 saved-cont) (let ([proc (expval->proc val1)])
(apply-procedure proc val saved-cont))]
[set-rhs-cont (loc cont)
(setref! loc val)
(apply-cont cont (num-val 26))]
[spawn-cont (saved-cont) (let ([proc1 (expval->proc val)])
(place-on-ready-queue! (a-thread (lambda ()
(apply-procedure proc1
(num-val 28)
(end-subthread-cont)))
the-max-time-slice))
(apply-cont saved-cont (num-val 73)))]
[wait-cont (saved-cont) (wait-for-mutex (expval->mutex val)
(lambda ()
(apply-cont saved-cont (num-val 52))))]
[signal-cont (saved-cont) (signal-mutex (expval->mutex val)
(lambda ()
(apply-cont saved-cont (num-val 53))))]
[unop-arg-cont (unop1 cont) (apply-unop unop1 val cont)])))))
(define value-of/k
(lambda (exp env cont)
(cases expression exp
[const-exp (num) (apply-cont cont (num-val num))]
[const-list-exp (nums) (apply-cont cont (list-val (map num-val nums)))]
[var-exp (var) (apply-cont cont (deref (apply-env env var)))]
[diff-exp (exp1 exp2) (value-of/k exp1 env (diff1-cont exp2 env cont))]
[if-exp (exp1 exp2 exp3) (value-of/k exp1 env (if-test-cont exp2 exp3 env cont))]
[proc-exp (var body) (apply-cont cont (proc-val (procedure var body env)))]
[call-exp (rator rand) (value-of/k rator env (rator-cont rand env cont))]
[let-exp (var exp1 body) (value-of/k (call-exp (proc-exp var body) exp1) env cont)]
[begin-exp (exp exps) (if (null? exps)
(value-of/k exp env cont)
(value-of/k (call-exp (proc-exp (fresh-identifier 'dummy)
(begin-exp (car exps) (cdr exps)))
exp)
env
cont))]
[letrec-exp (p-names b-vars p-bodies letrec-body) (value-of/k letrec-body
(extend-env-rec* p-names b-vars p-bodies env)
cont)]
[set-exp (id exp) (value-of/k exp env (set-rhs-cont (apply-env env id) cont))]
[spawn-exp (exp) (value-of/k exp env (spawn-cont cont))]
[yield-exp ()
(place-on-ready-queue! (a-thread (lambda ()
(apply-cont cont (num-val 99)))
the-time-remaining))
(run-next-thread)]
[mutex-exp () (apply-cont cont (mutex-val (new-mutex)))]
[wait-exp (exp) (value-of/k exp env (wait-cont cont))]
[signal-exp (exp) (value-of/k exp env (signal-cont cont))]
[unop-exp (unop1 exp) (value-of/k exp env (unop-arg-cont unop1 cont))])))
(define value-of-program
(lambda (timeslice pgm)
(initialize-store!)
(initialize-scheduler! timeslice)
(cases program pgm
[a-program (exp1) (value-of/k exp1 (empty-env) (end-main-thread-cont))])))
Interface .
(define run
(lambda (string)
(value-of-program 50 (scan&parse string))))
(provide num-val bool-val list-val run)
| null |
https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/solutions/exercise-5.46.rkt
|
racket
|
slot has been exhausted or because it chose to yield. In the latter case, it will be restarted with a full time
slice. Modify the system so that the ready queue keeps track of the remaining time slice (if any) of each thread, and
restarts the thread only with the time it has remaining.
Grammar.
Data structures.
References.
Store.
Procedures.
Queue.
Thread.
Scheduler.
Expressed values.
Environment.
Continuation.
Interpreter.
|
#lang eopl
Exercise 5.46 [ ★ ★ ] In the systemof exercise 5.45 , a thread may be placed on the ready queue either because its time
(define the-lexical-spec
'([whitespace (whitespace) skip]
[comment ("%" (arbno (not #\newline))) skip]
[identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol]
[number (digit (arbno digit)) number]
[number ("-" digit (arbno digit)) number]))
(define the-grammar
'([program (expression) a-program]
[expression (number) const-exp]
[expression ("[" (separated-list number ",") "]") const-list-exp]
[expression (identifier) var-exp]
[expression ("-" "(" expression "," expression ")") diff-exp]
[expression ("if" expression "then" expression "else" expression) if-exp]
[expression ("proc" "(" identifier ")" expression) proc-exp]
[expression ("(" expression expression ")") call-exp]
[expression ("begin" expression (arbno ";" expression) "end") begin-exp]
[expression ("let" identifier "=" expression "in" expression) let-exp]
[expression ("letrec" (arbno identifier "(" identifier ")" "=" expression) "in" expression) letrec-exp]
[expression ("set" identifier "=" expression) set-exp]
[expression ("spawn" "(" expression ")") spawn-exp]
[expression ("yield" "(" ")") yield-exp]
[expression ("mutex" "(" ")") mutex-exp]
[expression ("wait" "(" expression ")") wait-exp]
[expression ("signal" "(" expression ")") signal-exp]
[expression (unop "(" expression ")") unop-exp]
[unop ("car") car-unop]
[unop ("cdr") cdr-unop]
[unop ("null?") null?-unop]
[unop ("zero?") zero?-unop]
[unop ("print") print-unop]))
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar))
(define reference?
(lambda (v)
(integer? v)))
(define the-store 'uninitialized)
(define empty-store
(lambda ()
'()))
(define initialize-store!
(lambda ()
(set! the-store (empty-store))))
(define newref
(lambda (val)
(let ([next-ref (length the-store)])
(set! the-store (append the-store (list val)))
next-ref)))
(define deref
(lambda (ref)
(list-ref the-store ref)))
(define report-invalid-reference
(lambda (ref the-store)
(eopl:error 'setref "illegal reference ~s in store ~s" ref the-store)))
(define setref!
(lambda (ref val)
(set! the-store
(letrec ([setref-inner (lambda (store1 ref1)
(cond [(null? store1) (report-invalid-reference ref the-store)]
[(zero? ref1) (cons val (cdr store1))]
[else (cons (car store1) (setref-inner (cdr store1) (- ref1 1)))]))])
(setref-inner the-store ref)))))
(define-datatype proc proc?
[procedure [bvar symbol?]
[body expression?]
[env environment?]])
(define fresh-identifier
(let ([sn 0])
(lambda (identifier)
(set! sn (+ sn 1))
(string->symbol (string-append (symbol->string identifier) "%" (number->string sn))))))
(define empty-queue
(lambda ()
'()))
(define empty? null?)
(define enqueue
(lambda (q val)
(append q (list val))))
(define dequeue
(lambda (q f)
(f (car q) (cdr q))))
(define-datatype thread thread?
[a-thread [thunk procedure?]
[time-remaining integer?]])
(define the-ready-queue 'uninitialized)
(define the-final-answer 'uninitialized)
(define the-max-time-slice 'uninitialized)
(define the-time-remaining 'uninitialized)
(define initialize-scheduler!
(lambda (ticks)
(set! the-ready-queue (empty-queue))
(set! the-final-answer 'uninitialized)
(set! the-max-time-slice ticks)
(set! the-time-remaining the-max-time-slice)))
(define place-on-ready-queue!
(lambda (th)
(set! the-ready-queue (enqueue the-ready-queue th))))
(define time-expired?
(lambda ()
(zero? the-time-remaining)))
(define decrement-timer!
(lambda ()
(set! the-time-remaining (- the-time-remaining 1))))
(define set-final-answer!
(lambda (val)
(set! the-final-answer val)))
(define run-next-thread
(lambda ()
(if (empty? the-ready-queue)
the-final-answer
(dequeue the-ready-queue
(lambda (first-ready-thread other-ready-threads)
(set! the-ready-queue other-ready-threads)
(cases thread first-ready-thread
[a-thread (thunk time-remaining)
(set! the-time-remaining time-remaining)
(thunk)]))))))
Mutexes .
(define-datatype mutex mutex?
[a-mutex [ref-to-closed? reference?]
[ref-to-wait-queue reference?]])
(define new-mutex
(lambda ()
(a-mutex (newref #f) (newref '()))))
(define wait-for-mutex
(lambda (m th)
(cases mutex m
[a-mutex (ref-to-closed? ref-to-wait-queue)
(cond [(deref ref-to-closed?) (setref! ref-to-wait-queue
(enqueue (deref ref-to-wait-queue)
(a-thread th the-max-time-slice)))
(run-next-thread)]
[else (setref! ref-to-closed? #t)
(th)])])))
(define signal-mutex
(lambda (m th)
(cases mutex m
[a-mutex (ref-to-closed? ref-to-wait-queue) (let ([closed? (deref ref-to-closed?)]
[wait-queue (deref ref-to-wait-queue)])
(when closed?
(if (empty? wait-queue)
(setref! ref-to-closed? #f)
(dequeue wait-queue
(lambda (first-waiting-th other-waiting-ths)
(place-on-ready-queue! first-waiting-th)
(setref! ref-to-wait-queue other-waiting-ths)))))
(th))])))
(define-datatype expval expval?
[num-val [value number?]]
[bool-val [boolean boolean?]]
[proc-val [proc proc?]]
[list-val [lst (list-of expval?)]]
[mutex-val [mutex mutex?]])
(define expval-extractor-error
(lambda (variant value)
(eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value)))
(define expval->num
(lambda (v)
(cases expval v
[num-val (num) num]
[else (expval-extractor-error 'num v)])))
(define expval->bool
(lambda (v)
(cases expval v
[bool-val (bool) bool]
[else (expval-extractor-error 'bool v)])))
(define expval->proc
(lambda (v)
(cases expval v
[proc-val (proc) proc]
[else (expval-extractor-error 'proc v)])))
(define expval->list
(lambda (v)
(cases expval v
[list-val (lst) lst]
[else (expval-extractor-error 'list v)])))
(define expval->mutex
(lambda (v)
(cases expval v
[mutex-val (l) l]
[else (expval-extractor-error 'mutex v)])))
(define environment?
(list-of (lambda (p)
(and (pair? p) (or (symbol? (car p)) ((list-of symbol?) (car p)))))))
(define empty-env
(lambda ()
'()))
(define extend-env
(lambda (sym val old-env)
(cons (list sym val) old-env)))
(define extend-env-rec*
(lambda (p-names b-vars p-bodies saved-env)
(cons (list p-names b-vars p-bodies) saved-env)))
(define locate
(lambda (sym los)
(let loop ((pos 0) (los los))
(cond [(null? los) #f]
[(eqv? sym (car los)) pos]
[else (loop (+ pos 1) (cdr los))]))))
(define apply-env
(lambda (env search-sym)
(if (null? env)
(eopl:error 'apply-env "No binding for ~s" search-sym)
(let* ((binding (car env))
(saved-env (cdr env)))
(if (symbol? (car binding))
(if (eqv? search-sym (car binding))
(cadr binding)
(apply-env saved-env search-sym))
(let ([pos (locate search-sym (car binding))]
[b-vars (cadr binding)]
[p-bodies (caddr binding)])
(if pos
(newref (proc-val (procedure (list-ref b-vars pos) (list-ref p-bodies pos) env)))
(apply-env saved-env search-sym))))))))
(define-datatype continuation continuation?
[end-main-thread-cont]
[end-subthread-cont]
[diff1-cont [exp2 expression?]
[env environment?]
[cont continuation?]]
[diff2-cont [val1 expval?]
[cont continuation?]]
[if-test-cont [exp2 expression?]
[exp3 expression?]
[env environment?]
[cont continuation?]]
[rator-cont [rand expression?]
[env environment?]
[cont continuation?]]
[rand-cont [val1 expval?]
[cont continuation?]]
[set-rhs-cont [loc reference?]
[cont continuation?]]
[spawn-cont [saved-cont continuation?]]
[wait-cont [saved-cont continuation?]]
[signal-cont [saved-cont continuation?]]
[unop-arg-cont [unop1 unop?]
[cont continuation?]])
(define apply-unop
(lambda (unop1 arg cont)
(cases unop unop1
[zero?-unop () (apply-cont cont (bool-val (zero? (expval->num arg))))]
[car-unop () (let ([lst (expval->list arg)])
(apply-cont cont (car lst)))]
[cdr-unop () (let ([lst (expval->list arg)])
(apply-cont cont (list-val (cdr lst))))]
[null?-unop () (apply-cont cont (bool-val (null? (expval->list arg))))]
[print-unop () (begin (eopl:printf "~a~%" (expval->num arg))
(apply-cont cont (num-val 1)))])))
(define apply-procedure
(lambda (proc1 arg cont)
(cases proc proc1
[procedure (var body saved-env) (value-of/k body (extend-env var (newref arg) saved-env) cont)])))
(define apply-cont
(lambda (cont val)
(if (time-expired?)
(begin (place-on-ready-queue! (a-thread (lambda ()
(apply-cont cont val))
the-max-time-slice))
(run-next-thread))
(begin (decrement-timer!)
(cases continuation cont
[end-main-thread-cont ()
(set-final-answer! val)
(run-next-thread)]
[end-subthread-cont () (run-next-thread)]
[diff1-cont (exp2 saved-env saved-cont) (value-of/k exp2 saved-env (diff2-cont val saved-cont))]
[diff2-cont (val1 saved-cont) (let ([n1 (expval->num val1)]
[n2 (expval->num val)])
(apply-cont saved-cont (num-val (- n1 n2))))]
[if-test-cont (exp2 exp3 env cont) (if (expval->bool val)
(value-of/k exp2 env cont)
(value-of/k exp3 env cont))]
[rator-cont (rand saved-env saved-cont) (value-of/k rand saved-env (rand-cont val saved-cont))]
[rand-cont (val1 saved-cont) (let ([proc (expval->proc val1)])
(apply-procedure proc val saved-cont))]
[set-rhs-cont (loc cont)
(setref! loc val)
(apply-cont cont (num-val 26))]
[spawn-cont (saved-cont) (let ([proc1 (expval->proc val)])
(place-on-ready-queue! (a-thread (lambda ()
(apply-procedure proc1
(num-val 28)
(end-subthread-cont)))
the-max-time-slice))
(apply-cont saved-cont (num-val 73)))]
[wait-cont (saved-cont) (wait-for-mutex (expval->mutex val)
(lambda ()
(apply-cont saved-cont (num-val 52))))]
[signal-cont (saved-cont) (signal-mutex (expval->mutex val)
(lambda ()
(apply-cont saved-cont (num-val 53))))]
[unop-arg-cont (unop1 cont) (apply-unop unop1 val cont)])))))
(define value-of/k
(lambda (exp env cont)
(cases expression exp
[const-exp (num) (apply-cont cont (num-val num))]
[const-list-exp (nums) (apply-cont cont (list-val (map num-val nums)))]
[var-exp (var) (apply-cont cont (deref (apply-env env var)))]
[diff-exp (exp1 exp2) (value-of/k exp1 env (diff1-cont exp2 env cont))]
[if-exp (exp1 exp2 exp3) (value-of/k exp1 env (if-test-cont exp2 exp3 env cont))]
[proc-exp (var body) (apply-cont cont (proc-val (procedure var body env)))]
[call-exp (rator rand) (value-of/k rator env (rator-cont rand env cont))]
[let-exp (var exp1 body) (value-of/k (call-exp (proc-exp var body) exp1) env cont)]
[begin-exp (exp exps) (if (null? exps)
(value-of/k exp env cont)
(value-of/k (call-exp (proc-exp (fresh-identifier 'dummy)
(begin-exp (car exps) (cdr exps)))
exp)
env
cont))]
[letrec-exp (p-names b-vars p-bodies letrec-body) (value-of/k letrec-body
(extend-env-rec* p-names b-vars p-bodies env)
cont)]
[set-exp (id exp) (value-of/k exp env (set-rhs-cont (apply-env env id) cont))]
[spawn-exp (exp) (value-of/k exp env (spawn-cont cont))]
[yield-exp ()
(place-on-ready-queue! (a-thread (lambda ()
(apply-cont cont (num-val 99)))
the-time-remaining))
(run-next-thread)]
[mutex-exp () (apply-cont cont (mutex-val (new-mutex)))]
[wait-exp (exp) (value-of/k exp env (wait-cont cont))]
[signal-exp (exp) (value-of/k exp env (signal-cont cont))]
[unop-exp (unop1 exp) (value-of/k exp env (unop-arg-cont unop1 cont))])))
(define value-of-program
(lambda (timeslice pgm)
(initialize-store!)
(initialize-scheduler! timeslice)
(cases program pgm
[a-program (exp1) (value-of/k exp1 (empty-env) (end-main-thread-cont))])))
Interface .
(define run
(lambda (string)
(value-of-program 50 (scan&parse string))))
(provide num-val bool-val list-val run)
|
7282badaa0f2ebdd985fbcccb264e5325e767b436a997b32a3244fb8ee0411ab
|
mistupv/cauder-core
|
child.erl
|
-module(child).
-export([main/0, child/0]).
main() ->
Child = spawn(?MODULE, child, []),
Child ! {self(), hello},
receive
hello2 -> ok
end.
child() ->
receive
{Parent, hello} -> Parent ! hello2
end,
main().
| null |
https://raw.githubusercontent.com/mistupv/cauder-core/b676fccd1bbd629eb63f3cb5259f7a9a8c6da899/examples/child.erl
|
erlang
|
-module(child).
-export([main/0, child/0]).
main() ->
Child = spawn(?MODULE, child, []),
Child ! {self(), hello},
receive
hello2 -> ok
end.
child() ->
receive
{Parent, hello} -> Parent ! hello2
end,
main().
|
|
3d53c59978d47334defbd0c77f006b2b8650383933311251236be3b6ad7134c1
|
input-output-hk/marlowe-cardano
|
Submit.hs
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
module Language.Marlowe.Runtime.Transaction.Submit
where
import Cardano.Api (BabbageEra, ScriptDataSupportedInEra(..), Tx)
import qualified Cardano.Api as C
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (race)
import Control.Concurrent.STM (STM, atomically, newTVar, readTVar, writeTVar)
import Data.Functor (($>))
import Data.Void (absurd)
import Language.Marlowe.Runtime.ChainSync.Api
import Language.Marlowe.Runtime.Transaction.Api (SubmitError(..), SubmitStatus(..))
import Network.Protocol.ChainSeek.Client
import Network.Protocol.Connection (SomeClientConnector)
import Network.Protocol.Driver (runSomeConnector)
import Network.Protocol.Job.Client (JobClient, liftCommand)
data SubmitJobStatus
= Running SubmitStatus
| Succeeded BlockHeader
| Failed SubmitError
data SubmitJobDependencies = SubmitJobDependencies
{ chainSyncConnector :: SomeClientConnector RuntimeChainSeekClient IO
, chainSyncJobConnector :: SomeClientConnector (JobClient ChainSyncCommand) IO
, submitConfirmationBlocks :: BlockNo
}
data SubmitJob = SubmitJob
{ submitJobStatus :: STM SubmitJobStatus
, runSubmitJob :: IO ()
}
mkSubmitJob
:: SubmitJobDependencies
-> Tx BabbageEra
-> STM SubmitJob
mkSubmitJob deps tx = do
statusVar <- newTVar $ Running Submitting
pure $ SubmitJob (readTVar statusVar) $ doSubmit deps (atomically . writeTVar statusVar) ScriptDataInBabbageEra tx
doSubmit
:: SubmitJobDependencies
-> (SubmitJobStatus -> IO ())
-> ScriptDataSupportedInEra era
-> Tx era
-> IO ()
doSubmit SubmitJobDependencies{..} tellStatus era tx= do
result <- runSomeConnector chainSyncJobConnector $ liftCommand $ SubmitTx era tx
case result of
Left msg -> tellStatus $ Failed $ SubmitFailed msg
Right _ -> do
tellStatus $ Running Accepted
tellStatus . either Succeeded (const $ Failed TxDiscarded) =<< race waitForTx timeout
where
txId = TxId $ C.serialiseToRawBytes $ C.getTxId $ C.getTxBody tx
timeout :: IO ()
10 minutes in microseconds
waitForTx :: IO BlockHeader
waitForTx = runSomeConnector chainSyncConnector client
where
client = ChainSeekClient $ pure clientInit
clientInit = SendMsgRequestHandshake moveSchema ClientStHandshake
{ recvMsgHandshakeRejected = \_ ->
error "marlowe-chain-sync schema version mismatch"
, recvMsgHandshakeConfirmed = pure clientIdleAwaitConfirmation
}
clientIdleAwaitConfirmation = SendMsgQueryNext (FindTx txId True) clientNextAwaitConfirmation
clientNextAwaitConfirmation = ClientStNext
{ recvMsgQueryRejected = \err _ ->
error $ "marlowe-chain-sync rejected query: " <> show err
, recvMsgRollBackward = \_ _ -> pure clientIdleAwaitConfirmation
, recvMsgRollForward = \_ point _ -> case point of
Genesis -> error "marlowe-chain-sync rolled forward to genesis"
At block -> pure $ clientIdleAwaitMaturity block
, recvMsgWait = threadDelay 100_000 $> SendMsgPoll clientNextAwaitConfirmation
}
clientIdleAwaitMaturity confirmationBlock
| submitConfirmationBlocks == 0 = SendMsgDone confirmationBlock
| otherwise = SendMsgQueryNext (AdvanceBlocks $ fromIntegral submitConfirmationBlocks)
$ clientNextAwaitMaturity confirmationBlock
clientNextAwaitMaturity confirmationBlock = ClientStNext
{ recvMsgQueryRejected = absurd
, recvMsgRollBackward = \_ _ -> pure clientIdleAwaitConfirmation
, recvMsgRollForward = \_ _ _ -> pure $ SendMsgDone confirmationBlock
, recvMsgWait = threadDelay 100_000 $> SendMsgPoll (clientNextAwaitMaturity confirmationBlock)
}
| null |
https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/bc9a0325f13b886e90ea05196ffb70a46c2ab095/marlowe-runtime/tx/Language/Marlowe/Runtime/Transaction/Submit.hs
|
haskell
|
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
|
module Language.Marlowe.Runtime.Transaction.Submit
where
import Cardano.Api (BabbageEra, ScriptDataSupportedInEra(..), Tx)
import qualified Cardano.Api as C
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (race)
import Control.Concurrent.STM (STM, atomically, newTVar, readTVar, writeTVar)
import Data.Functor (($>))
import Data.Void (absurd)
import Language.Marlowe.Runtime.ChainSync.Api
import Language.Marlowe.Runtime.Transaction.Api (SubmitError(..), SubmitStatus(..))
import Network.Protocol.ChainSeek.Client
import Network.Protocol.Connection (SomeClientConnector)
import Network.Protocol.Driver (runSomeConnector)
import Network.Protocol.Job.Client (JobClient, liftCommand)
data SubmitJobStatus
= Running SubmitStatus
| Succeeded BlockHeader
| Failed SubmitError
data SubmitJobDependencies = SubmitJobDependencies
{ chainSyncConnector :: SomeClientConnector RuntimeChainSeekClient IO
, chainSyncJobConnector :: SomeClientConnector (JobClient ChainSyncCommand) IO
, submitConfirmationBlocks :: BlockNo
}
data SubmitJob = SubmitJob
{ submitJobStatus :: STM SubmitJobStatus
, runSubmitJob :: IO ()
}
mkSubmitJob
:: SubmitJobDependencies
-> Tx BabbageEra
-> STM SubmitJob
mkSubmitJob deps tx = do
statusVar <- newTVar $ Running Submitting
pure $ SubmitJob (readTVar statusVar) $ doSubmit deps (atomically . writeTVar statusVar) ScriptDataInBabbageEra tx
doSubmit
:: SubmitJobDependencies
-> (SubmitJobStatus -> IO ())
-> ScriptDataSupportedInEra era
-> Tx era
-> IO ()
doSubmit SubmitJobDependencies{..} tellStatus era tx= do
result <- runSomeConnector chainSyncJobConnector $ liftCommand $ SubmitTx era tx
case result of
Left msg -> tellStatus $ Failed $ SubmitFailed msg
Right _ -> do
tellStatus $ Running Accepted
tellStatus . either Succeeded (const $ Failed TxDiscarded) =<< race waitForTx timeout
where
txId = TxId $ C.serialiseToRawBytes $ C.getTxId $ C.getTxBody tx
timeout :: IO ()
10 minutes in microseconds
waitForTx :: IO BlockHeader
waitForTx = runSomeConnector chainSyncConnector client
where
client = ChainSeekClient $ pure clientInit
clientInit = SendMsgRequestHandshake moveSchema ClientStHandshake
{ recvMsgHandshakeRejected = \_ ->
error "marlowe-chain-sync schema version mismatch"
, recvMsgHandshakeConfirmed = pure clientIdleAwaitConfirmation
}
clientIdleAwaitConfirmation = SendMsgQueryNext (FindTx txId True) clientNextAwaitConfirmation
clientNextAwaitConfirmation = ClientStNext
{ recvMsgQueryRejected = \err _ ->
error $ "marlowe-chain-sync rejected query: " <> show err
, recvMsgRollBackward = \_ _ -> pure clientIdleAwaitConfirmation
, recvMsgRollForward = \_ point _ -> case point of
Genesis -> error "marlowe-chain-sync rolled forward to genesis"
At block -> pure $ clientIdleAwaitMaturity block
, recvMsgWait = threadDelay 100_000 $> SendMsgPoll clientNextAwaitConfirmation
}
clientIdleAwaitMaturity confirmationBlock
| submitConfirmationBlocks == 0 = SendMsgDone confirmationBlock
| otherwise = SendMsgQueryNext (AdvanceBlocks $ fromIntegral submitConfirmationBlocks)
$ clientNextAwaitMaturity confirmationBlock
clientNextAwaitMaturity confirmationBlock = ClientStNext
{ recvMsgQueryRejected = absurd
, recvMsgRollBackward = \_ _ -> pure clientIdleAwaitConfirmation
, recvMsgRollForward = \_ _ _ -> pure $ SendMsgDone confirmationBlock
, recvMsgWait = threadDelay 100_000 $> SendMsgPoll (clientNextAwaitMaturity confirmationBlock)
}
|
f7042bbcd59a6dd1611ad1efca33ad10402c363fe3089756d5ead37f7caeef5f
|
Bodigrim/arithmoi
|
Approximate.hs
|
-- |
Module : Math . . Primes . Counting . Approximate
Copyright : ( c ) 2011
Licence : MIT
Maintainer : < >
--
-- Approximations to the number of primes below a limit and the
-- n-th prime.
--
module Math.NumberTheory.Primes.Counting.Approximate
( approxPrimeCount
, approxPrimeCountOverestimateLimit
, nthPrimeApprox
, nthPrimeApproxUnderestimateLimit
) where
For prime p = 3742914359 we have
approxPrimeCount p = 178317879
primeCount p = 178317880
-- | Following property holds:
--
> approxPrimeCount n > = primeCount n || n > = approxPrimeCountOverestimateLimit
approxPrimeCountOverestimateLimit :: Integral a => a
approxPrimeCountOverestimateLimit = 3742914359
| @'approxPrimeCount ' n@ gives an
-- approximation of the number of primes not exceeding
@n@. The approximation is fairly good for @n@ large enough .
approxPrimeCount :: Integral a => a -> a
approxPrimeCount = truncate . max 0 . appi . fromIntegral
-- | Following property holds:
--
-- > nthPrimeApprox n <= nthPrime n || n >= nthPrimeApproxUnderestimateLimit
nthPrimeApproxUnderestimateLimit :: Integer
nthPrimeApproxUnderestimateLimit = 1000000000000
-- | @'nthPrimeApprox' n@ gives an
-- approximation to the n-th prime. The approximation
is fairly good for @n@ large enough .
nthPrimeApprox :: Integer -> Integer
nthPrimeApprox = max 1 . truncate . nthApp . fromIntegral . max 3
-- Basically the approximation of the prime count by Li(x),
-- adjusted to give close but slightly too high estimates
-- in the interesting range. The constants are empirically
-- determined.
appi :: Double -> Double
appi x = y - y/300000 + 7*ll
where
y = x*l*(1+l*(1+l*h))
w = log x
l = 1/w
ll = log w
h | x < 10000000 = 2.5625
| x < 50000000 = 2.5
| x < 120000000 = 617/256
| otherwise = 2.0625 + l*(3+ll*l*(13.25+ll*l*57.75))
-- Basically an approximation to the inverse of Li(x), with
-- empirically determined constants to get close results
-- in the interesting range.
nthApp :: Double -> Double
nthApp x = a
where
l = log x
ll = log l
li = 1/l
l2 = ll*ll
a = x*(l+ll-1+li*(ll-2-li*(ll*(0.3+li*(1+0.02970812*l2*l2*l2*li))
+ 8.725*(ll-2.749)*(ll-3.892)*li))) + l*ll + 35
| null |
https://raw.githubusercontent.com/Bodigrim/arithmoi/df789d23341247e9cdb4f690595ea99c89836d09/Math/NumberTheory/Primes/Counting/Approximate.hs
|
haskell
|
|
Approximations to the number of primes below a limit and the
n-th prime.
| Following property holds:
approximation of the number of primes not exceeding
| Following property holds:
> nthPrimeApprox n <= nthPrime n || n >= nthPrimeApproxUnderestimateLimit
| @'nthPrimeApprox' n@ gives an
approximation to the n-th prime. The approximation
Basically the approximation of the prime count by Li(x),
adjusted to give close but slightly too high estimates
in the interesting range. The constants are empirically
determined.
Basically an approximation to the inverse of Li(x), with
empirically determined constants to get close results
in the interesting range.
|
Module : Math . . Primes . Counting . Approximate
Copyright : ( c ) 2011
Licence : MIT
Maintainer : < >
module Math.NumberTheory.Primes.Counting.Approximate
( approxPrimeCount
, approxPrimeCountOverestimateLimit
, nthPrimeApprox
, nthPrimeApproxUnderestimateLimit
) where
For prime p = 3742914359 we have
approxPrimeCount p = 178317879
primeCount p = 178317880
> approxPrimeCount n > = primeCount n || n > = approxPrimeCountOverestimateLimit
approxPrimeCountOverestimateLimit :: Integral a => a
approxPrimeCountOverestimateLimit = 3742914359
| @'approxPrimeCount ' n@ gives an
@n@. The approximation is fairly good for @n@ large enough .
approxPrimeCount :: Integral a => a -> a
approxPrimeCount = truncate . max 0 . appi . fromIntegral
nthPrimeApproxUnderestimateLimit :: Integer
nthPrimeApproxUnderestimateLimit = 1000000000000
is fairly good for @n@ large enough .
nthPrimeApprox :: Integer -> Integer
nthPrimeApprox = max 1 . truncate . nthApp . fromIntegral . max 3
appi :: Double -> Double
appi x = y - y/300000 + 7*ll
where
y = x*l*(1+l*(1+l*h))
w = log x
l = 1/w
ll = log w
h | x < 10000000 = 2.5625
| x < 50000000 = 2.5
| x < 120000000 = 617/256
| otherwise = 2.0625 + l*(3+ll*l*(13.25+ll*l*57.75))
nthApp :: Double -> Double
nthApp x = a
where
l = log x
ll = log l
li = 1/l
l2 = ll*ll
a = x*(l+ll-1+li*(ll-2-li*(ll*(0.3+li*(1+0.02970812*l2*l2*l2*li))
+ 8.725*(ll-2.749)*(ll-3.892)*li))) + l*ll + 35
|
06e88623fa33bc87759920c51c1e5e8d5fd4fdb5450bd7acc87481f750fc5da4
|
hanshuebner/vlm
|
clisp-support.lisp
|
-*- Mode : LISP ; Syntax : Common - Lisp ; Package : SYSTEM ; Base : 10 ; Lowercase : Yes -*-
;;;
( in - package " CCL " )
( ( name arglist & body body )
` ( progn
;; (declaim (inline ,name))
( defun , name , arglist , ) ) )
(defmacro defsubst (name arglist &body body)
`(progn
(declaim (inline ,name))
(defun ,name ,arglist ,@body)))
(defmacro stack-let (vars-and-vals &body body)
(let ((vars (loop for var-and-val in vars-and-vals
if (atom var-and-val)
collect var-and-val
else
collect (first var-and-val))))
`(let ,vars-and-vals
(declare (dynamic-extent ,@vars))
,@body)))
;; (declaim (inline circular-list))
;; (defun circular-list (&rest list)
;; (let ((list (copy-list list)))
( setf ( cdr ( last list ) ) list )
;; list))
;;;
(in-package "SYSTEM")
;;(defsubst %32-bit-difference (x y)
;; (- x y))
(defun %32-bit-difference (x y)
(- x y))
(export '(%logldb %logdpb %32-bit-difference))
( ccl::defsubst % logldb ( bytespec integer )
; (ldb bytespec integer))
( ccl::defsubst % ( value )
( let ( ( result ( dpb value ) ) )
( if ( zerop ( ldb ( byte 1 31 ) result ) )
;; result
( - ( ldb ( byte 31 0 ) ( 1 + ( lognot result ) ) ) ) ) ) )
;;(ccl::defsubst %32-bit-difference (x y)
;; (- x y))
;;;
(defmacro defsysconstant (name value)
`(progn
(defconstant ,name ,value)
(export ',name)))
(defmacro defenumerated (list-name code-list &optional (start 0) (increment 1) end)
(when (and end (not (= (length code-list) (/ (- end start) increment))))
(error "~s has ~s codes where ~s are required"
list-name (length code-list) (/ (- end start) increment)))
`(progn
(defsysconstant ,list-name ',code-list)
,@(loop for code in code-list and prev = 0 then code
as value from start by increment
unless (eq code prev) ;kludge for data-types
collect `(defsysconstant ,code ,value))))
(defmacro defsysbyte (name size position)
`(defsysconstant ,name (byte ,size ,position)))
;;;
The following definitions are from SYS : I - SYS;SYSDEF.LISP ...
;;;
;; --- most of the below is L-specific
;; To add a new data type, update the following (at least):
;; *DATA-TYPES* and *POINTER-DATA-TYPES* in this file
;; Patch *DATA-TYPE-NAME*, set up by from *DATA-TYPES* by the cold-load generator
type - map - for - transport , transporter - type - map - alist in : l - ucode ; uu.lisp
* storing - type - map * in : l - ucode ; uux.lisp and reload that whole file
;; It is important that the form near the end of that file that sets up the
;; no-trap type-map be executed before any other type maps are assigned.
simulate - transporter in sys : l - ucode ; simx.lisp
;; and recompile the whole microcode to get the type-maps updated
typep - alist and related stuff in sys : sys ; lcons.lisp
;; dbg:*good-data-types* if it is indeed a good data type
;; Send a message to the maintainer of the FEP-resident debugger.
(DEFENUMERATED *DATA-TYPES* (
;; Headers, special markers, and forwarding pointers.
DTP-NULL ;00 Unbound variable/function, uninitialized storage
DTP-MONITOR-FORWARD ;01 This cell being monitored
DTP-HEADER-P ;02 Structure header, with pointer field
DTP-HEADER-I ;03 Structure header, with immediate bits
DTP-EXTERNAL-VALUE-CELL-POINTER ;04 Invisible except for binding
DTP-ONE-Q-FORWARD ;05 Invisible pointer (forwards one cell)
06 Invisible pointer ( forwards whole structure )
DTP-ELEMENT-FORWARD ;07 Invisible pointer in element of structure
;; Numeric data types.
10 Small integer
11 Ratio with small numerator and denominator
12 Single - precision floating point
13 Double - precision floating point
14 Big integer
15 Ratio with big numerator or denominator
16 Complex number
17 A number to the hardware trap mechanism
;; Instance data types.
20 Ordinary instance
21 Instance that masquerades as a cons
22 Instance that masquerades as an array
23 Instance that masquerades as a string
;; Primitive data types.
24 The symbol NIL
25 A cons
26 An array that is not a string
27 A string
30 A symbol other than NIL
31 Locative pointer
32 Lexical closure of a function
33 Dynamic closure of a function
34 Compiled code
35 Generic function ( see later section )
36 Spare
37 Spare
40 Physical address
41 Spare
42 Deep bound marker
43 Common Lisp character object
44 Unbound logic variable marker
45 Object - moved flag for garbage collector
46 PC at first instruction in word
47 PC at second instruction in word
;; Full-word instructions.
50 Start call , address is compiled function
51 Start call , address is compiled function
52 Start call , address is function cell
53 Start call , address is generic function
54 Like above , but prefetching is desireable
55 Like above , but prefetching is desireable
56 Like above , but prefetching is desireable
57 Like above , but prefetching is desireable
Half - word ( packed ) instructions consume 4 bits of data type field ( opcodes 60 .. 77 ) .
DTP-PACKED-INSTRUCTION-60 DTP-PACKED-INSTRUCTION-61 DTP-PACKED-INSTRUCTION-62
DTP-PACKED-INSTRUCTION-63 DTP-PACKED-INSTRUCTION-64 DTP-PACKED-INSTRUCTION-65
DTP-PACKED-INSTRUCTION-66 DTP-PACKED-INSTRUCTION-67 DTP-PACKED-INSTRUCTION-70
DTP-PACKED-INSTRUCTION-71 DTP-PACKED-INSTRUCTION-72 DTP-PACKED-INSTRUCTION-73
DTP-PACKED-INSTRUCTION-74 DTP-PACKED-INSTRUCTION-75 DTP-PACKED-INSTRUCTION-76
DTP-PACKED-INSTRUCTION-77
)
0 1 #o100)
(DEFENUMERATED *ARRAY-ELEMENT-DATA-TYPES* (
ARRAY-ELEMENT-TYPE-FIXNUM
ARRAY-ELEMENT-TYPE-CHARACTER
ARRAY-ELEMENT-TYPE-BOOLEAN
ARRAY-ELEMENT-TYPE-OBJECT
))
Control register .
(DEFSYSBYTE %%CR.ARGUMENT-SIZE 8. 0) ;Number of spread arguments supplied by caller
1 If caller used APPLY , 0 otherwise
(DEFSYSBYTE %%CR.VALUE-DISPOSITION 2 18.) ;The value of this function
(DEFSYSBYTE %%CR.CLEANUP-BITS 3 24.) ;All the cleanup bits
(DEFSYSBYTE %%CR.CLEANUP-CATCH 1 26.) ;There are active catch blocks in the current frame
(DEFSYSBYTE %%CR.CLEANUP-BINDINGS 1 25.) ;There are active bindings in the current frame
(DEFSYSBYTE %%CR.TRAP-ON-EXIT-BIT 1 24.) ;Software trap before exiting this frame
1 If we are executing on the " extra stack "
;Extra stack inhibits sequence breaks and preemption
;It also allows the "overflow" part of the stack to
;be used without traps.
(DEFSYSBYTE %%CR.EXTRA-ARGUMENT 1 8.) ;The call instruction supplied an "extra" argument
The frame size of the Caller
(DEFSYSBYTE %%CR.CALL-STARTED 1 22.) ;Between start-call and finish-call.
(DEFSYSBYTE %%CR.CLEANUP-IN-PROGRESS 1 23.)
(DEFSYSBYTE %%CR.INSTRUCTION-TRACE 1 29.)
(DEFSYSBYTE %%CR.CALL-TRACE 1 28.)
(DEFSYSBYTE %%CR.TRACE-PENDING 1 27.)
(DEFSYSBYTE %%CR.TRACE-BITS 3 27.)
(DEFSYSBYTE %%CR.CLEANUP-AND-TRACE-BITS 6 24.)
(DEFENUMERATED *VALUE-DISPOSITIONS* (
VALUE-DISPOSITION-EFFECT ;The callers wants no return values
VALUE-DISPOSITION-VALUE ;The caller wants a single return value
VALUE-DISPOSITION-RETURN ;The caller wants to return whatever values are
;returned by this function
VALUE-DISPOSITION-MULTIPLE ;The callers wants multiple values
))
(DEFENUMERATED *TRAP-MODES* (
TRAP-MODE-EMULATOR
TRAP-MODE-EXTRA-STACK
TRAP-MODE-IO
TRAP-MODE-FEP))
(DEFENUMERATED *MEMORY-CYCLE-TYPES* (
%MEMORY-DATA-READ
%MEMORY-DATA-WRITE
%MEMORY-BIND-READ
%MEMORY-BIND-WRITE
%MEMORY-BIND-READ-NO-MONITOR
%MEMORY-BIND-WRITE-NO-MONITOR
%MEMORY-HEADER
%MEMORY-STRUCTURE-OFFSET
%MEMORY-SCAVENGE
%MEMORY-CDR
%MEMORY-GC-COPY
%MEMORY-RAW
%MEMORY-RAW-TRANSLATE
))
Internal register definitions
;;; %REGISTER-ALU-AND-ROTATE-CONTROL fields (DP-OP in hardware spec)
(DEFSYSBYTE %%ALU-BYTE-R 5 0.)
(DEFSYSBYTE %%ALU-BYTE-S 5 5.)
(DEFSYSBYTE %%ALU-FUNCTION 6 10.)
(DEFSYSBYTE %%ALU-FUNCTION-CLASS 2 14.)
(DEFSYSBYTE %%ALU-FUNCTION-BITS 4 10.)
(DEFSYSBYTE %%ALU-CONDITION 5 16.)
(DEFSYSBYTE %%ALU-CONDITION-SENSE 1 21.)
;; The following are implemented in Rev3 only.
;; Software forces them to the proper value for compatible operation in Rev1 and Rev2.
(DEFSYSBYTE %%ALU-OUTPUT-CONDITION 1 22.)
(DEFSYSBYTE %%ALU-ENABLE-CONDITION-EXCEPTION 1 23.)
(DEFSYSBYTE %%ALU-ENABLE-LOAD-CIN 1 24.)
(DEFENUMERATED *ALU-CONDITION-SENSES*
(%ALU-CONDITION-SENSE-TRUE
%ALU-CONDITION-SENSE-FALSE))
(DEFENUMERATED *ALU-CONDITIONS*
(%ALU-CONDITION-SIGNED-LESS-THAN-OR-EQUAL ;00
01
02
03
04
05
06
07
10
11
12
13
14
15
16
17
20
21
22
23
24
25
26
27
30
))
(DEFENUMERATED *ALU-FUNCTION-CLASSES*
(%ALU-FUNCTION-CLASS-BOOLEAN
%ALU-FUNCTION-CLASS-BYTE
%ALU-FUNCTION-CLASS-ADDER
%ALU-FUNCTION-CLASS-MULTIPLY-DIVIDE))
(DEFENUMERATED *ALU-FUNCTIONS*
(%ALU-FUNCTION-OP-BOOLEAN-0
%ALU-FUNCTION-OP-BOOLEAN-1
%ALU-FUNCTION-OP-DPB
%ALU-FUNCTION-OP-LDB
%ALU-FUNCTION-OP-ADD
%ALU-FUNCTION-OP-RESERVED
%ALU-FUNCTION-OP-MULTIPLY-STEP
%ALU-FUNCTION-OP-MULTIPLY-INVERT-STEP
%ALU-FUNCTION-OP-DIVIDE-STEP
%ALU-FUNCTION-OP-DIVIDE-INVERT-STEP))
(DEFENUMERATED *ALU-BYTE-BACKGROUNDS*
(%ALU-BYTE-BACKGROUND-OP1
%ALU-BYTE-BACKGROUND-ROTATE-LATCH
%ALU-BYTE-BACKGROUND-ZERO))
(DEFENUMERATED *ALU-BYTE-ROTATE-LATCH*
(%ALU-BYTE-HOLD-ROTATE-LATCH
%ALU-BYTE-SET-ROTATE-LATCH))
(DEFENUMERATED *ALU-ADD-OP2-ACTIONS*
(%ALU-ADD-OP2-PASS
%ALU-ADD-OP2-INVERT))
(DEFENUMERATED *ALU-ADDER-OPS*
(%ALU-ADD-OP2
%ALU-ADD-ZERO))
(defmacro %alu-function-dpb (background rotate-latch)
`(%logdpb %alu-function-op-dpb (byte 3 3)
(%logdpb ,rotate-latch (byte 1 2)
(%logdpb ,background (byte 2 0)
0))))
(export '%alu-function-dpb)
;;;
The following definitions are from SYS : I - SYS;SYSDF1.LISP ...
;;;
(DEFSYSCONSTANT %ARITHMETIC-INSTRUCTION-EXCEPTION-VECTOR #o0)
(DEFSYSCONSTANT %INSTRUCTION-EXCEPTION-VECTOR #o4000)
(DEFSYSCONSTANT %INTERPRETER-FUNCTION-VECTOR #o4400)
(DEFSYSCONSTANT %GENERIC-DISPATCH-VECTOR #o5000)
(DEFSYSCONSTANT %ERROR-TRAP-VECTOR #o5100)
(DEFSYSCONSTANT %RESET-TRAP-VECTOR #o5101)
(DEFSYSCONSTANT %PULL-APPLY-ARGS-TRAP-VECTOR #o5102)
(DEFSYSCONSTANT %STACK-OVERFLOW-TRAP-VECTOR #o5103)
(DEFSYSCONSTANT %TRACE-TRAP-VECTOR #o5104)
(DEFSYSCONSTANT %PREEMPT-REQUEST-TRAP-VECTOR #o5105)
(DEFSYSCONSTANT %TRANSPORT-TRAP-VECTOR #o5106)
(DEFSYSCONSTANT %FEP-MODE-TRAP-VECTOR #o5107)
(DEFSYSCONSTANT %LOW-PRIORITY-SEQUENCE-BREAK-TRAP-VECTOR #o5110)
(DEFSYSCONSTANT %HIGH-PRIORITY-SEQUENCE-BREAK-TRAP-VECTOR #o5111)
(DEFSYSCONSTANT %MONITOR-TRAP-VECTOR #o5112)
5113 reserved for future use
(DEFSYSCONSTANT %GENERIC-DISPATCH-TRAP-VECTOR #o5114)
5115 reserved for a fence word
(DEFSYSCONSTANT %MESSAGE-DISPATCH-TRAP-VECTOR #o5116)
;;; 5117 reserved for a fence word
(DEFSYSCONSTANT %PAGE-NOT-RESIDENT-TRAP-VECTOR #o5120)
(DEFSYSCONSTANT %PAGE-FAULT-REQUEST-TRAP-VECTOR #o5121)
(DEFSYSCONSTANT %PAGE-WRITE-FAULT-TRAP-VECTOR #o5122)
(DEFSYSCONSTANT %UNCORRECTABLE-MEMORY-ERROR-TRAP-VECTOR #o5123)
(DEFSYSCONSTANT %MEMORY-BUS-ERROR-TRAP-VECTOR #o5124)
(DEFSYSCONSTANT %DB-CACHE-MISS-TRAP-VECTOR #o5125)
(DEFSYSCONSTANT %DB-UNWIND-FRAME-TRAP-VECTOR #o5126)
(DEFSYSCONSTANT %DB-UNWIND-CATCH-TRAP-VECTOR 5127)
5130 through 5177 reserved for future use
;;;
The following definitions are from SYS : I - SYS;OPSDEF.LISP ...
;;;
(in-package "I-LISP-COMPILER")
(DEFCONSTANT *FINISH-CALL-N-OPCODE* #o134)
| null |
https://raw.githubusercontent.com/hanshuebner/vlm/20510ddc98b52252a406012a50a4d3bbd1b75dd0/support/clisp-support.lisp
|
lisp
|
Syntax : Common - Lisp ; Package : SYSTEM ; Base : 10 ; Lowercase : Yes -*-
(declaim (inline ,name))
(declaim (inline circular-list))
(defun circular-list (&rest list)
(let ((list (copy-list list)))
list))
(defsubst %32-bit-difference (x y)
(- x y))
(ldb bytespec integer))
result
(ccl::defsubst %32-bit-difference (x y)
(- x y))
kludge for data-types
SYSDEF.LISP ...
--- most of the below is L-specific
To add a new data type, update the following (at least):
*DATA-TYPES* and *POINTER-DATA-TYPES* in this file
Patch *DATA-TYPE-NAME*, set up by from *DATA-TYPES* by the cold-load generator
uu.lisp
uux.lisp and reload that whole file
It is important that the form near the end of that file that sets up the
no-trap type-map be executed before any other type maps are assigned.
simx.lisp
and recompile the whole microcode to get the type-maps updated
lcons.lisp
dbg:*good-data-types* if it is indeed a good data type
Send a message to the maintainer of the FEP-resident debugger.
Headers, special markers, and forwarding pointers.
00 Unbound variable/function, uninitialized storage
01 This cell being monitored
02 Structure header, with pointer field
03 Structure header, with immediate bits
04 Invisible except for binding
05 Invisible pointer (forwards one cell)
07 Invisible pointer in element of structure
Numeric data types.
Instance data types.
Primitive data types.
Full-word instructions.
Number of spread arguments supplied by caller
The value of this function
All the cleanup bits
There are active catch blocks in the current frame
There are active bindings in the current frame
Software trap before exiting this frame
Extra stack inhibits sequence breaks and preemption
It also allows the "overflow" part of the stack to
be used without traps.
The call instruction supplied an "extra" argument
Between start-call and finish-call.
The callers wants no return values
The caller wants a single return value
The caller wants to return whatever values are
returned by this function
The callers wants multiple values
%REGISTER-ALU-AND-ROTATE-CONTROL fields (DP-OP in hardware spec)
The following are implemented in Rev3 only.
Software forces them to the proper value for compatible operation in Rev1 and Rev2.
00
SYSDF1.LISP ...
5117 reserved for a fence word
OPSDEF.LISP ...
|
( in - package " CCL " )
( ( name arglist & body body )
` ( progn
( defun , name , arglist , ) ) )
(defmacro defsubst (name arglist &body body)
`(progn
(declaim (inline ,name))
(defun ,name ,arglist ,@body)))
(defmacro stack-let (vars-and-vals &body body)
(let ((vars (loop for var-and-val in vars-and-vals
if (atom var-and-val)
collect var-and-val
else
collect (first var-and-val))))
`(let ,vars-and-vals
(declare (dynamic-extent ,@vars))
,@body)))
( setf ( cdr ( last list ) ) list )
(in-package "SYSTEM")
(defun %32-bit-difference (x y)
(- x y))
(export '(%logldb %logdpb %32-bit-difference))
( ccl::defsubst % logldb ( bytespec integer )
( ccl::defsubst % ( value )
( let ( ( result ( dpb value ) ) )
( if ( zerop ( ldb ( byte 1 31 ) result ) )
( - ( ldb ( byte 31 0 ) ( 1 + ( lognot result ) ) ) ) ) ) )
(defmacro defsysconstant (name value)
`(progn
(defconstant ,name ,value)
(export ',name)))
(defmacro defenumerated (list-name code-list &optional (start 0) (increment 1) end)
(when (and end (not (= (length code-list) (/ (- end start) increment))))
(error "~s has ~s codes where ~s are required"
list-name (length code-list) (/ (- end start) increment)))
`(progn
(defsysconstant ,list-name ',code-list)
,@(loop for code in code-list and prev = 0 then code
as value from start by increment
collect `(defsysconstant ,code ,value))))
(defmacro defsysbyte (name size position)
`(defsysconstant ,name (byte ,size ,position)))
(DEFENUMERATED *DATA-TYPES* (
06 Invisible pointer ( forwards whole structure )
10 Small integer
11 Ratio with small numerator and denominator
12 Single - precision floating point
13 Double - precision floating point
14 Big integer
15 Ratio with big numerator or denominator
16 Complex number
17 A number to the hardware trap mechanism
20 Ordinary instance
21 Instance that masquerades as a cons
22 Instance that masquerades as an array
23 Instance that masquerades as a string
24 The symbol NIL
25 A cons
26 An array that is not a string
27 A string
30 A symbol other than NIL
31 Locative pointer
32 Lexical closure of a function
33 Dynamic closure of a function
34 Compiled code
35 Generic function ( see later section )
36 Spare
37 Spare
40 Physical address
41 Spare
42 Deep bound marker
43 Common Lisp character object
44 Unbound logic variable marker
45 Object - moved flag for garbage collector
46 PC at first instruction in word
47 PC at second instruction in word
50 Start call , address is compiled function
51 Start call , address is compiled function
52 Start call , address is function cell
53 Start call , address is generic function
54 Like above , but prefetching is desireable
55 Like above , but prefetching is desireable
56 Like above , but prefetching is desireable
57 Like above , but prefetching is desireable
Half - word ( packed ) instructions consume 4 bits of data type field ( opcodes 60 .. 77 ) .
DTP-PACKED-INSTRUCTION-60 DTP-PACKED-INSTRUCTION-61 DTP-PACKED-INSTRUCTION-62
DTP-PACKED-INSTRUCTION-63 DTP-PACKED-INSTRUCTION-64 DTP-PACKED-INSTRUCTION-65
DTP-PACKED-INSTRUCTION-66 DTP-PACKED-INSTRUCTION-67 DTP-PACKED-INSTRUCTION-70
DTP-PACKED-INSTRUCTION-71 DTP-PACKED-INSTRUCTION-72 DTP-PACKED-INSTRUCTION-73
DTP-PACKED-INSTRUCTION-74 DTP-PACKED-INSTRUCTION-75 DTP-PACKED-INSTRUCTION-76
DTP-PACKED-INSTRUCTION-77
)
0 1 #o100)
(DEFENUMERATED *ARRAY-ELEMENT-DATA-TYPES* (
ARRAY-ELEMENT-TYPE-FIXNUM
ARRAY-ELEMENT-TYPE-CHARACTER
ARRAY-ELEMENT-TYPE-BOOLEAN
ARRAY-ELEMENT-TYPE-OBJECT
))
Control register .
1 If caller used APPLY , 0 otherwise
1 If we are executing on the " extra stack "
The frame size of the Caller
(DEFSYSBYTE %%CR.CLEANUP-IN-PROGRESS 1 23.)
(DEFSYSBYTE %%CR.INSTRUCTION-TRACE 1 29.)
(DEFSYSBYTE %%CR.CALL-TRACE 1 28.)
(DEFSYSBYTE %%CR.TRACE-PENDING 1 27.)
(DEFSYSBYTE %%CR.TRACE-BITS 3 27.)
(DEFSYSBYTE %%CR.CLEANUP-AND-TRACE-BITS 6 24.)
(DEFENUMERATED *VALUE-DISPOSITIONS* (
))
(DEFENUMERATED *TRAP-MODES* (
TRAP-MODE-EMULATOR
TRAP-MODE-EXTRA-STACK
TRAP-MODE-IO
TRAP-MODE-FEP))
(DEFENUMERATED *MEMORY-CYCLE-TYPES* (
%MEMORY-DATA-READ
%MEMORY-DATA-WRITE
%MEMORY-BIND-READ
%MEMORY-BIND-WRITE
%MEMORY-BIND-READ-NO-MONITOR
%MEMORY-BIND-WRITE-NO-MONITOR
%MEMORY-HEADER
%MEMORY-STRUCTURE-OFFSET
%MEMORY-SCAVENGE
%MEMORY-CDR
%MEMORY-GC-COPY
%MEMORY-RAW
%MEMORY-RAW-TRANSLATE
))
Internal register definitions
(DEFSYSBYTE %%ALU-BYTE-R 5 0.)
(DEFSYSBYTE %%ALU-BYTE-S 5 5.)
(DEFSYSBYTE %%ALU-FUNCTION 6 10.)
(DEFSYSBYTE %%ALU-FUNCTION-CLASS 2 14.)
(DEFSYSBYTE %%ALU-FUNCTION-BITS 4 10.)
(DEFSYSBYTE %%ALU-CONDITION 5 16.)
(DEFSYSBYTE %%ALU-CONDITION-SENSE 1 21.)
(DEFSYSBYTE %%ALU-OUTPUT-CONDITION 1 22.)
(DEFSYSBYTE %%ALU-ENABLE-CONDITION-EXCEPTION 1 23.)
(DEFSYSBYTE %%ALU-ENABLE-LOAD-CIN 1 24.)
(DEFENUMERATED *ALU-CONDITION-SENSES*
(%ALU-CONDITION-SENSE-TRUE
%ALU-CONDITION-SENSE-FALSE))
(DEFENUMERATED *ALU-CONDITIONS*
01
02
03
04
05
06
07
10
11
12
13
14
15
16
17
20
21
22
23
24
25
26
27
30
))
(DEFENUMERATED *ALU-FUNCTION-CLASSES*
(%ALU-FUNCTION-CLASS-BOOLEAN
%ALU-FUNCTION-CLASS-BYTE
%ALU-FUNCTION-CLASS-ADDER
%ALU-FUNCTION-CLASS-MULTIPLY-DIVIDE))
(DEFENUMERATED *ALU-FUNCTIONS*
(%ALU-FUNCTION-OP-BOOLEAN-0
%ALU-FUNCTION-OP-BOOLEAN-1
%ALU-FUNCTION-OP-DPB
%ALU-FUNCTION-OP-LDB
%ALU-FUNCTION-OP-ADD
%ALU-FUNCTION-OP-RESERVED
%ALU-FUNCTION-OP-MULTIPLY-STEP
%ALU-FUNCTION-OP-MULTIPLY-INVERT-STEP
%ALU-FUNCTION-OP-DIVIDE-STEP
%ALU-FUNCTION-OP-DIVIDE-INVERT-STEP))
(DEFENUMERATED *ALU-BYTE-BACKGROUNDS*
(%ALU-BYTE-BACKGROUND-OP1
%ALU-BYTE-BACKGROUND-ROTATE-LATCH
%ALU-BYTE-BACKGROUND-ZERO))
(DEFENUMERATED *ALU-BYTE-ROTATE-LATCH*
(%ALU-BYTE-HOLD-ROTATE-LATCH
%ALU-BYTE-SET-ROTATE-LATCH))
(DEFENUMERATED *ALU-ADD-OP2-ACTIONS*
(%ALU-ADD-OP2-PASS
%ALU-ADD-OP2-INVERT))
(DEFENUMERATED *ALU-ADDER-OPS*
(%ALU-ADD-OP2
%ALU-ADD-ZERO))
(defmacro %alu-function-dpb (background rotate-latch)
`(%logdpb %alu-function-op-dpb (byte 3 3)
(%logdpb ,rotate-latch (byte 1 2)
(%logdpb ,background (byte 2 0)
0))))
(export '%alu-function-dpb)
(DEFSYSCONSTANT %ARITHMETIC-INSTRUCTION-EXCEPTION-VECTOR #o0)
(DEFSYSCONSTANT %INSTRUCTION-EXCEPTION-VECTOR #o4000)
(DEFSYSCONSTANT %INTERPRETER-FUNCTION-VECTOR #o4400)
(DEFSYSCONSTANT %GENERIC-DISPATCH-VECTOR #o5000)
(DEFSYSCONSTANT %ERROR-TRAP-VECTOR #o5100)
(DEFSYSCONSTANT %RESET-TRAP-VECTOR #o5101)
(DEFSYSCONSTANT %PULL-APPLY-ARGS-TRAP-VECTOR #o5102)
(DEFSYSCONSTANT %STACK-OVERFLOW-TRAP-VECTOR #o5103)
(DEFSYSCONSTANT %TRACE-TRAP-VECTOR #o5104)
(DEFSYSCONSTANT %PREEMPT-REQUEST-TRAP-VECTOR #o5105)
(DEFSYSCONSTANT %TRANSPORT-TRAP-VECTOR #o5106)
(DEFSYSCONSTANT %FEP-MODE-TRAP-VECTOR #o5107)
(DEFSYSCONSTANT %LOW-PRIORITY-SEQUENCE-BREAK-TRAP-VECTOR #o5110)
(DEFSYSCONSTANT %HIGH-PRIORITY-SEQUENCE-BREAK-TRAP-VECTOR #o5111)
(DEFSYSCONSTANT %MONITOR-TRAP-VECTOR #o5112)
5113 reserved for future use
(DEFSYSCONSTANT %GENERIC-DISPATCH-TRAP-VECTOR #o5114)
5115 reserved for a fence word
(DEFSYSCONSTANT %MESSAGE-DISPATCH-TRAP-VECTOR #o5116)
(DEFSYSCONSTANT %PAGE-NOT-RESIDENT-TRAP-VECTOR #o5120)
(DEFSYSCONSTANT %PAGE-FAULT-REQUEST-TRAP-VECTOR #o5121)
(DEFSYSCONSTANT %PAGE-WRITE-FAULT-TRAP-VECTOR #o5122)
(DEFSYSCONSTANT %UNCORRECTABLE-MEMORY-ERROR-TRAP-VECTOR #o5123)
(DEFSYSCONSTANT %MEMORY-BUS-ERROR-TRAP-VECTOR #o5124)
(DEFSYSCONSTANT %DB-CACHE-MISS-TRAP-VECTOR #o5125)
(DEFSYSCONSTANT %DB-UNWIND-FRAME-TRAP-VECTOR #o5126)
(DEFSYSCONSTANT %DB-UNWIND-CATCH-TRAP-VECTOR 5127)
5130 through 5177 reserved for future use
(in-package "I-LISP-COMPILER")
(DEFCONSTANT *FINISH-CALL-N-OPCODE* #o134)
|
6460c448a5154eaac4877ac4e90b92531cbc14517a04e18008b8c8f79feefdd2
|
basho/basho_bench
|
basho_bench_driver_ets.erl
|
-module(basho_bench_driver_ets).
-export([new/1,
run/4]).
new(_Id) ->
EtsTable = ets:new(basho_bench, [ordered_set]),
{ok, EtsTable}.
run(get, KeyGen, _ValueGen, EtsTable) ->
Start = KeyGen(),
case ets:lookup(EtsTable, Start) of
[] ->
{ok, EtsTable};
[{_Key, _Val}] ->
{ok, EtsTable};
Error ->
{error, Error, EtsTable}
end;
run(put, KeyGen, ValueGen, EtsTable) ->
Object = {KeyGen(), ValueGen()},
ets:insert(EtsTable, Object),
{ok, EtsTable};
run(delete, KeyGen, _ValueGen, EtsTable) ->
Start = KeyGen(),
ets:delete(EtsTable, Start),
{ok, EtsTable}.
| null |
https://raw.githubusercontent.com/basho/basho_bench/aa66398bb6a91645dbb97e91a236f3cdcd1f188f/src/basho_bench_driver_ets.erl
|
erlang
|
-module(basho_bench_driver_ets).
-export([new/1,
run/4]).
new(_Id) ->
EtsTable = ets:new(basho_bench, [ordered_set]),
{ok, EtsTable}.
run(get, KeyGen, _ValueGen, EtsTable) ->
Start = KeyGen(),
case ets:lookup(EtsTable, Start) of
[] ->
{ok, EtsTable};
[{_Key, _Val}] ->
{ok, EtsTable};
Error ->
{error, Error, EtsTable}
end;
run(put, KeyGen, ValueGen, EtsTable) ->
Object = {KeyGen(), ValueGen()},
ets:insert(EtsTable, Object),
{ok, EtsTable};
run(delete, KeyGen, _ValueGen, EtsTable) ->
Start = KeyGen(),
ets:delete(EtsTable, Start),
{ok, EtsTable}.
|
|
e8539978721dfabcc73224d5d9af59b1ddb126c93908b194267cf1e5f481c045
|
realark/vert
|
object-manager.lisp
|
(in-package :recurse.vert)
@export-class
(defclass object-manager (game-object)
()
(:documentation "A game object which manages other game objects."))
@export
(defgeneric get-managed-objects (object-manager)
(:method ((object-manager object-manager)) '()))
(defmethod remove-from-scene :after ((scene game-scene) (object-manager object-manager))
(loop :for managed-obj :in (get-managed-objects object-manager) :do
(remove-from-scene scene managed-obj)))
(defmethod add-to-scene :after ((scene game-scene) (object-manager object-manager))
(loop :for managed-obj :in (get-managed-objects object-manager) :do
(add-to-scene scene managed-obj)))
| null |
https://raw.githubusercontent.com/realark/vert/4cb88545abc60f1fba4a8604ce85e70cbd4764a2/src/scene/object-manager.lisp
|
lisp
|
(in-package :recurse.vert)
@export-class
(defclass object-manager (game-object)
()
(:documentation "A game object which manages other game objects."))
@export
(defgeneric get-managed-objects (object-manager)
(:method ((object-manager object-manager)) '()))
(defmethod remove-from-scene :after ((scene game-scene) (object-manager object-manager))
(loop :for managed-obj :in (get-managed-objects object-manager) :do
(remove-from-scene scene managed-obj)))
(defmethod add-to-scene :after ((scene game-scene) (object-manager object-manager))
(loop :for managed-obj :in (get-managed-objects object-manager) :do
(add-to-scene scene managed-obj)))
|
|
3d107a29f6e1711abf042beaa1cd279a4401b3098a4196717db1fc894d3fa8a0
|
facebook/pyre-check
|
jsonParsing.ml
|
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(* TODO(T132410158) Add a module-level doc comment. *)
open Yojson.Safe.Util
let with_default ~extract ~extract_optional ?default json =
match default with
| None -> extract json
| Some default -> extract_optional json |> Option.value ~default
let to_bool_with_default = with_default ~extract:to_bool ~extract_optional:to_bool_option
let to_int_with_default = with_default ~extract:to_int ~extract_optional:to_int_option
let to_string_with_default = with_default ~extract:to_string ~extract_optional:to_string_option
let to_path json = to_string json |> PyrePath.create_absolute
(* The absent of explicit `~default` parameter means that the corresponding JSON field is
mandantory. *)
let bool_member ?default name json = member name json |> to_bool_with_default ?default
let int_member ?default name json = member name json |> to_int_with_default ?default
let string_member ?default name json = member name json |> to_string_with_default ?default
let optional_member ~f name json =
member name json
|> function
| `Null -> None
| _ as element -> Some (f element)
let optional_string_member = optional_member ~f:to_string
let optional_int_member = optional_member ~f:to_int
let path_member name json = member name json |> to_path
let optional_path_member = optional_member ~f:to_path
let list_member ?default ~f name json =
member name json
|> fun element ->
match element, default with
| `Null, Some default -> default
| _, _ -> convert_each f element
let optional_list_member ~f name json =
member name json
|> function
| `Null -> None
| element -> Some (convert_each f element)
let string_list_member = list_member ~f:to_string
let path_list_member = list_member ~f:to_path
| null |
https://raw.githubusercontent.com/facebook/pyre-check/98b8362ffa5c715c708676c1a37a52647ce79fe0/source/jsonParsing.ml
|
ocaml
|
TODO(T132410158) Add a module-level doc comment.
The absent of explicit `~default` parameter means that the corresponding JSON field is
mandantory.
|
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Yojson.Safe.Util
let with_default ~extract ~extract_optional ?default json =
match default with
| None -> extract json
| Some default -> extract_optional json |> Option.value ~default
let to_bool_with_default = with_default ~extract:to_bool ~extract_optional:to_bool_option
let to_int_with_default = with_default ~extract:to_int ~extract_optional:to_int_option
let to_string_with_default = with_default ~extract:to_string ~extract_optional:to_string_option
let to_path json = to_string json |> PyrePath.create_absolute
let bool_member ?default name json = member name json |> to_bool_with_default ?default
let int_member ?default name json = member name json |> to_int_with_default ?default
let string_member ?default name json = member name json |> to_string_with_default ?default
let optional_member ~f name json =
member name json
|> function
| `Null -> None
| _ as element -> Some (f element)
let optional_string_member = optional_member ~f:to_string
let optional_int_member = optional_member ~f:to_int
let path_member name json = member name json |> to_path
let optional_path_member = optional_member ~f:to_path
let list_member ?default ~f name json =
member name json
|> fun element ->
match element, default with
| `Null, Some default -> default
| _, _ -> convert_each f element
let optional_list_member ~f name json =
member name json
|> function
| `Null -> None
| element -> Some (convert_each f element)
let string_list_member = list_member ~f:to_string
let path_list_member = list_member ~f:to_path
|
08154d741049c1c3a5101cf7809cdc0aad01977d36e99ced57ae0bfc5c6eb5a2
|
lambdaisland/gaiwan_co
|
team.cljc
|
(ns co.gaiwan.site.components.team)
(defn item [{:keys [title subtitle link image description] :as member}]
[:li
[:div
{:class "space-y-4 sm:grid sm:grid-cols-3 sm:gap-6 sm:space-y-0 lg:gap-8"}
[:div {:class "h-0 aspect-w-3 aspect-h-2 sm:aspect-w-3 sm:aspect-h-4"}
[:img
{:alt "",
:class "object-cover shadow-lg rounded-lg",
:src
(if image
image
"-1517365830460-955ce3ccd263?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=8&w=1024&h=1024&q=80")}]]
[:div {:class "sm:col-span-2"}
[:div {:class "space-y-4"}
[:div {:class "text-lg leading-6 font-medium space-y-1"}
[:h3 title]
[:p {:class "text-indigo-600"}
[:a {:href link :target "_blank"} subtitle]]]
[:div {:class "text-sm"}
(into
[:div {:class "text-gray-700 flex flex-col gap-y-1"}]
description)]]]]])
(defn section [members]
[:div#team {:class "bg-white"}
[:div {:class "mx-auto py-12 px-4 max-w-7xl sm:px-6 lg:px-8"}
[:div {:class "space-y-12"}
[:h2 {:class "text-3xl font-extrabold tracking-tight sm:text-4xl"}
"Meet the Gaiwan team"]
[:ul
{:class
"space-y-12 lg:grid lg:grid-cols-2 lg:items-start lg:gap-x-8 lg:gap-y-12 lg:space-y-0"}
(map item (into [(first members)] (shuffle (rest members))))
]]]])
| null |
https://raw.githubusercontent.com/lambdaisland/gaiwan_co/05ac04356ac2701442a6dfadd12b482485545921/src/co/gaiwan/site/components/team.cljc
|
clojure
|
(ns co.gaiwan.site.components.team)
(defn item [{:keys [title subtitle link image description] :as member}]
[:li
[:div
{:class "space-y-4 sm:grid sm:grid-cols-3 sm:gap-6 sm:space-y-0 lg:gap-8"}
[:div {:class "h-0 aspect-w-3 aspect-h-2 sm:aspect-w-3 sm:aspect-h-4"}
[:img
{:alt "",
:class "object-cover shadow-lg rounded-lg",
:src
(if image
image
"-1517365830460-955ce3ccd263?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=8&w=1024&h=1024&q=80")}]]
[:div {:class "sm:col-span-2"}
[:div {:class "space-y-4"}
[:div {:class "text-lg leading-6 font-medium space-y-1"}
[:h3 title]
[:p {:class "text-indigo-600"}
[:a {:href link :target "_blank"} subtitle]]]
[:div {:class "text-sm"}
(into
[:div {:class "text-gray-700 flex flex-col gap-y-1"}]
description)]]]]])
(defn section [members]
[:div#team {:class "bg-white"}
[:div {:class "mx-auto py-12 px-4 max-w-7xl sm:px-6 lg:px-8"}
[:div {:class "space-y-12"}
[:h2 {:class "text-3xl font-extrabold tracking-tight sm:text-4xl"}
"Meet the Gaiwan team"]
[:ul
{:class
"space-y-12 lg:grid lg:grid-cols-2 lg:items-start lg:gap-x-8 lg:gap-y-12 lg:space-y-0"}
(map item (into [(first members)] (shuffle (rest members))))
]]]])
|
|
7925730bd75223de83f939b4b63a3eae8fa7a1a2bf10e4ade0f6bd96538bfdff
|
runtimeverification/haskell-backend
|
ErrorBottomTotalFunction.hs
|
# LANGUAGE NoStrict #
# LANGUAGE NoStrictData #
|
Copyright : ( c ) Runtime Verification , 2020 - 2021
License : BSD-3 - Clause
Copyright : (c) Runtime Verification, 2020-2021
License : BSD-3-Clause
-}
module Kore.Log.ErrorBottomTotalFunction (
ErrorBottomTotalFunction (..),
errorBottomTotalFunction,
) where
import Control.Monad.Catch (
Exception (..),
MonadThrow,
throwM,
)
import GHC.Generics qualified as GHC
import Generics.SOP qualified as SOP
import Kore.Internal.TermLike
import Kore.Unparser (
unparse,
)
import Log
import Prelude.Kore
import Pretty (
Pretty,
)
import Pretty qualified
import SQL qualified
newtype ErrorBottomTotalFunction = ErrorBottomTotalFunction
{ term :: TermLike VariableName
}
deriving stock (Show)
deriving stock (GHC.Generic)
instance SOP.Generic ErrorBottomTotalFunction
instance SOP.HasDatatypeInfo ErrorBottomTotalFunction
instance Pretty ErrorBottomTotalFunction where
pretty ErrorBottomTotalFunction{term} =
Pretty.vsep
[ "Evaluating total function"
, Pretty.indent 4 (unparse term)
, "has resulted in \\bottom."
]
instance Exception ErrorBottomTotalFunction where
toException = toException . SomeEntry []
fromException exn =
fromException exn >>= fromEntry
instance Entry ErrorBottomTotalFunction where
entrySeverity _ = Error
oneLineDoc _ = "ErrorBottomTotalFunction"
helpDoc _ = "errors raised when a total function is undefined"
instance SQL.Table ErrorBottomTotalFunction
errorBottomTotalFunction ::
MonadThrow logger =>
InternalVariable variable =>
TermLike variable ->
logger ()
errorBottomTotalFunction (mapVariables (pure toVariableName) -> term) =
throwM ErrorBottomTotalFunction{term}
| null |
https://raw.githubusercontent.com/runtimeverification/haskell-backend/de44aad602e76f45baaa4dabac2b8088f22c3415/kore/src/Kore/Log/ErrorBottomTotalFunction.hs
|
haskell
|
# LANGUAGE NoStrict #
# LANGUAGE NoStrictData #
|
Copyright : ( c ) Runtime Verification , 2020 - 2021
License : BSD-3 - Clause
Copyright : (c) Runtime Verification, 2020-2021
License : BSD-3-Clause
-}
module Kore.Log.ErrorBottomTotalFunction (
ErrorBottomTotalFunction (..),
errorBottomTotalFunction,
) where
import Control.Monad.Catch (
Exception (..),
MonadThrow,
throwM,
)
import GHC.Generics qualified as GHC
import Generics.SOP qualified as SOP
import Kore.Internal.TermLike
import Kore.Unparser (
unparse,
)
import Log
import Prelude.Kore
import Pretty (
Pretty,
)
import Pretty qualified
import SQL qualified
newtype ErrorBottomTotalFunction = ErrorBottomTotalFunction
{ term :: TermLike VariableName
}
deriving stock (Show)
deriving stock (GHC.Generic)
instance SOP.Generic ErrorBottomTotalFunction
instance SOP.HasDatatypeInfo ErrorBottomTotalFunction
instance Pretty ErrorBottomTotalFunction where
pretty ErrorBottomTotalFunction{term} =
Pretty.vsep
[ "Evaluating total function"
, Pretty.indent 4 (unparse term)
, "has resulted in \\bottom."
]
instance Exception ErrorBottomTotalFunction where
toException = toException . SomeEntry []
fromException exn =
fromException exn >>= fromEntry
instance Entry ErrorBottomTotalFunction where
entrySeverity _ = Error
oneLineDoc _ = "ErrorBottomTotalFunction"
helpDoc _ = "errors raised when a total function is undefined"
instance SQL.Table ErrorBottomTotalFunction
errorBottomTotalFunction ::
MonadThrow logger =>
InternalVariable variable =>
TermLike variable ->
logger ()
errorBottomTotalFunction (mapVariables (pure toVariableName) -> term) =
throwM ErrorBottomTotalFunction{term}
|
|
9cded051ff3a45993699598003537cc79097d316f7d47a09fd0bedc441608d1f
|
jhidding/chez-glfw
|
features.scm
|
(library (glfw parse-api features)
(export get-features
feature? feature-name feature-number
feature-require-enums feature-require-commands
feature-remove-enums feature-remove-commands
extend-commands extend-enums)
(import (rnrs base (6))
(rnrs lists (6))
(rnrs sorting (6))
(rnrs records syntactic (6))
(lyonesse parsing xml)
(lyonesse functional))
(define-record-type feature
(fields name number require-enums require-commands
remove-enums remove-commands)
(protocol
(lambda (new)
(lambda (registry f)
(let ([name (xml:get-attr f 'name)]
[number (string->number (xml:get-attr f 'number))]
[req-enums (map ($ xml:get-attr <> 'name)
(xml:list* registry '(registry) f '(require) '(enum)))]
[req-commands (map ($ xml:get-attr <> 'name)
(xml:list* registry '(registry) f '(require) '(command)))]
[rem-enums (map ($ xml:get-attr <> 'name)
(xml:list* registry '(registry) f '(remove) '(enum)))]
[rem-commands (map ($ xml:get-attr <> 'name)
(xml:list* registry '(registry) f '(remove) '(command)))])
(new name number req-enums req-commands rem-enums rem-commands))))))
(define (extend-commands commands feature)
((compose ($ unique-sorted string=? <>) ($ list-sort string<? <>) append)
(remp ($ member <> (feature-remove-commands feature)) commands)
(feature-require-commands feature)))
(define (extend-enums enums feature)
((compose ($ unique-sorted string=? <>) ($ list-sort string<? <>) append)
(remp ($ member <> (feature-remove-enums feature)) enums)
(feature-require-enums feature)))
(define (list-features features n)
(let* ([check-version (lambda (f) (<= (feature-number f) n))]
[commands (fold-left extend-commands '()
(filter check-version features))]
[enums (fold-left extend-enums '()
(filter check-version features))])
(values commands enums)))
(define (get-features registry)
(let ([features (xml:list registry '(registry) '(feature (api . "gl")))])
(map ($ make-feature registry <>) features)))
)
| null |
https://raw.githubusercontent.com/jhidding/chez-glfw/fe53b5d8915c1c0b9f6a07446a0399a430d09851/glfw/parse-api/features.scm
|
scheme
|
(library (glfw parse-api features)
(export get-features
feature? feature-name feature-number
feature-require-enums feature-require-commands
feature-remove-enums feature-remove-commands
extend-commands extend-enums)
(import (rnrs base (6))
(rnrs lists (6))
(rnrs sorting (6))
(rnrs records syntactic (6))
(lyonesse parsing xml)
(lyonesse functional))
(define-record-type feature
(fields name number require-enums require-commands
remove-enums remove-commands)
(protocol
(lambda (new)
(lambda (registry f)
(let ([name (xml:get-attr f 'name)]
[number (string->number (xml:get-attr f 'number))]
[req-enums (map ($ xml:get-attr <> 'name)
(xml:list* registry '(registry) f '(require) '(enum)))]
[req-commands (map ($ xml:get-attr <> 'name)
(xml:list* registry '(registry) f '(require) '(command)))]
[rem-enums (map ($ xml:get-attr <> 'name)
(xml:list* registry '(registry) f '(remove) '(enum)))]
[rem-commands (map ($ xml:get-attr <> 'name)
(xml:list* registry '(registry) f '(remove) '(command)))])
(new name number req-enums req-commands rem-enums rem-commands))))))
(define (extend-commands commands feature)
((compose ($ unique-sorted string=? <>) ($ list-sort string<? <>) append)
(remp ($ member <> (feature-remove-commands feature)) commands)
(feature-require-commands feature)))
(define (extend-enums enums feature)
((compose ($ unique-sorted string=? <>) ($ list-sort string<? <>) append)
(remp ($ member <> (feature-remove-enums feature)) enums)
(feature-require-enums feature)))
(define (list-features features n)
(let* ([check-version (lambda (f) (<= (feature-number f) n))]
[commands (fold-left extend-commands '()
(filter check-version features))]
[enums (fold-left extend-enums '()
(filter check-version features))])
(values commands enums)))
(define (get-features registry)
(let ([features (xml:list registry '(registry) '(feature (api . "gl")))])
(map ($ make-feature registry <>) features)))
)
|
|
d3199ade8e4cc9ebd0beea219631775c920599673139b9fcffe7b0f3d8956352
|
d-cent/objective8
|
marks.clj
|
(ns objective8.integration.db.marks
(:require [midje.sweet :refer :all]
[objective8.integration.integration-helpers :as ih]
[objective8.integration.storage-helpers :as sh]
[objective8.back-end.domain.marks :as marks]))
(facts "about storing marks"
(against-background
[(before :contents (do (ih/db-connection)
(ih/truncate-tables)))
(after :facts (ih/truncate-tables))]
(facts "a mark can be stored for a question"
(let [{objective-id :_id :as objective} (sh/store-an-objective)
{question-id :_id} (sh/store-a-question {:objective objective})
{user-id :user-id} (sh/store-a-writer {:invitation (sh/store-an-invitation {:objective objective})})
question-uri (str "/objectives/" objective-id "/questions/" question-id)
created-by-uri (str "/users/" user-id)
mark-data {:question-uri question-uri
:created-by-uri created-by-uri
:active true}]
(marks/store-mark! mark-data) => (contains {:entity :mark
:uri (contains "/meta/marks/")
:question-uri question-uri
:created-by-uri created-by-uri
:active true
:_created_at anything})))))
(facts "about getting marks for questions"
(against-background
[(before :contents (do (ih/db-connection)
(ih/truncate-tables)))
(after :facts (ih/truncate-tables))]
(fact "the most recently created mark is returned"
(let [{objective-id :objective-id question-id :_id :as question} (sh/store-a-question)
mark (sh/store-a-mark {:question question})
new-mark (sh/store-a-mark {:question question :active false})
question-uri (str "/objectives/" objective-id "/questions/" question-id)
created-by-uri (str "/users/" (:created-by-id new-mark))
new-mark-uri (str "/meta/marks/" (:_id new-mark))]
(marks/get-mark-for-question question-uri) => {:uri new-mark-uri
:question-uri question-uri
:created-by-uri created-by-uri
:active false
:_created_at (:_created_at new-mark)
:entity :mark}))))
| null |
https://raw.githubusercontent.com/d-cent/objective8/db8344ba4425ca0b38a31c99a3b282d7c8ddaef0/test/objective8/integration/db/marks.clj
|
clojure
|
(ns objective8.integration.db.marks
(:require [midje.sweet :refer :all]
[objective8.integration.integration-helpers :as ih]
[objective8.integration.storage-helpers :as sh]
[objective8.back-end.domain.marks :as marks]))
(facts "about storing marks"
(against-background
[(before :contents (do (ih/db-connection)
(ih/truncate-tables)))
(after :facts (ih/truncate-tables))]
(facts "a mark can be stored for a question"
(let [{objective-id :_id :as objective} (sh/store-an-objective)
{question-id :_id} (sh/store-a-question {:objective objective})
{user-id :user-id} (sh/store-a-writer {:invitation (sh/store-an-invitation {:objective objective})})
question-uri (str "/objectives/" objective-id "/questions/" question-id)
created-by-uri (str "/users/" user-id)
mark-data {:question-uri question-uri
:created-by-uri created-by-uri
:active true}]
(marks/store-mark! mark-data) => (contains {:entity :mark
:uri (contains "/meta/marks/")
:question-uri question-uri
:created-by-uri created-by-uri
:active true
:_created_at anything})))))
(facts "about getting marks for questions"
(against-background
[(before :contents (do (ih/db-connection)
(ih/truncate-tables)))
(after :facts (ih/truncate-tables))]
(fact "the most recently created mark is returned"
(let [{objective-id :objective-id question-id :_id :as question} (sh/store-a-question)
mark (sh/store-a-mark {:question question})
new-mark (sh/store-a-mark {:question question :active false})
question-uri (str "/objectives/" objective-id "/questions/" question-id)
created-by-uri (str "/users/" (:created-by-id new-mark))
new-mark-uri (str "/meta/marks/" (:_id new-mark))]
(marks/get-mark-for-question question-uri) => {:uri new-mark-uri
:question-uri question-uri
:created-by-uri created-by-uri
:active false
:_created_at (:_created_at new-mark)
:entity :mark}))))
|
|
2c3c6c48ccab13358547516ea821a6efac8ab8b3532344d96f816cac3fb1c07f
|
rixed/ramen
|
RamenFieldOrder.ml
|
open Batteries
module DT = DessserTypes
module N = RamenName
let rec_field_cmp (n1, _) (n2, _) =
String.compare n1 n2
let rec order_rec_fields mn =
let rec order_value_type = function
| DT.TRec mns ->
let mns = Array.copy mns in
Array.fast_sort rec_field_cmp mns ;
DT.TRec (Array.map (fun (name, mn) -> name, order_rec_fields mn) mns)
| TTup mns ->
DT.TTup (Array.map order_rec_fields mns)
| TVec (dim, mn) ->
DT.TVec (dim, order_rec_fields mn)
| TArr mn ->
DT.TArr (order_rec_fields mn)
| TSum mns ->
DT.TSum (Array.map (fun (name, mn) -> name, order_rec_fields mn) mns)
| TUsr ut ->
DT.TUsr { ut with def = order_value_type ut.def }
| mn -> mn in
{ mn with typ = order_value_type mn.typ }
let rec are_rec_fields_ordered mn =
let rec aux = function
| DT.TRec mns ->
DessserTools.array_for_alli (fun i (_, mn) ->
are_rec_fields_ordered mn &&
(i = 0 || rec_field_cmp mns.(i-1) mns.(i)< 0)
) mns
| TTup mns ->
Array.for_all are_rec_fields_ordered mns
| TVec (_, mn) | TArr mn ->
are_rec_fields_ordered mn
| TSum mns ->
Array.for_all (fun (_, mn) -> are_rec_fields_ordered mn) mns
| TUsr ut ->
aux ut.def
| _ ->
true in
aux mn.DT.typ
let check_rec_fields_ordered mn =
if not (are_rec_fields_ordered mn) then
Printf.sprintf2
"RingBuffer can only serialize/deserialize records which \
fields are sorted (had: %a)"
DT.print_mn mn |>
failwith
let order_tuple tup =
let cmp ft1 ft2 =
rec_field_cmp ((ft1.RamenTuple.name :> string), ())
((ft2.RamenTuple.name :> string), ()) in
List.map (fun ft ->
RamenTuple.{ ft with typ = order_rec_fields ft.typ }
) tup |>
List.fast_sort cmp
| null |
https://raw.githubusercontent.com/rixed/ramen/9606882b5a62d4f89a944d6579cd9daf25ebfaa7/src/RamenFieldOrder.ml
|
ocaml
|
open Batteries
module DT = DessserTypes
module N = RamenName
let rec_field_cmp (n1, _) (n2, _) =
String.compare n1 n2
let rec order_rec_fields mn =
let rec order_value_type = function
| DT.TRec mns ->
let mns = Array.copy mns in
Array.fast_sort rec_field_cmp mns ;
DT.TRec (Array.map (fun (name, mn) -> name, order_rec_fields mn) mns)
| TTup mns ->
DT.TTup (Array.map order_rec_fields mns)
| TVec (dim, mn) ->
DT.TVec (dim, order_rec_fields mn)
| TArr mn ->
DT.TArr (order_rec_fields mn)
| TSum mns ->
DT.TSum (Array.map (fun (name, mn) -> name, order_rec_fields mn) mns)
| TUsr ut ->
DT.TUsr { ut with def = order_value_type ut.def }
| mn -> mn in
{ mn with typ = order_value_type mn.typ }
let rec are_rec_fields_ordered mn =
let rec aux = function
| DT.TRec mns ->
DessserTools.array_for_alli (fun i (_, mn) ->
are_rec_fields_ordered mn &&
(i = 0 || rec_field_cmp mns.(i-1) mns.(i)< 0)
) mns
| TTup mns ->
Array.for_all are_rec_fields_ordered mns
| TVec (_, mn) | TArr mn ->
are_rec_fields_ordered mn
| TSum mns ->
Array.for_all (fun (_, mn) -> are_rec_fields_ordered mn) mns
| TUsr ut ->
aux ut.def
| _ ->
true in
aux mn.DT.typ
let check_rec_fields_ordered mn =
if not (are_rec_fields_ordered mn) then
Printf.sprintf2
"RingBuffer can only serialize/deserialize records which \
fields are sorted (had: %a)"
DT.print_mn mn |>
failwith
let order_tuple tup =
let cmp ft1 ft2 =
rec_field_cmp ((ft1.RamenTuple.name :> string), ())
((ft2.RamenTuple.name :> string), ()) in
List.map (fun ft ->
RamenTuple.{ ft with typ = order_rec_fields ft.typ }
) tup |>
List.fast_sort cmp
|
|
39eb71578bde97660a2f6e8093063854b9c4bb218db6b37557095b32439b6a5d
|
tfausak/strive
|
Kudos.hs
|
-- | </>
module Strive.Actions.Kudos
( getActivityKudoers,
)
where
import Network.HTTP.Types (toQuery)
import Strive.Aliases (ActivityId, Result)
import Strive.Client (Client)
import Strive.Internal.HTTP (get)
import Strive.Options (GetActivityKudoersOptions)
import Strive.Types (AthleteSummary)
-- | </#list>
getActivityKudoers ::
Client ->
ActivityId ->
GetActivityKudoersOptions ->
IO (Result [AthleteSummary])
getActivityKudoers client activityId options = get client resource query
where
resource = "api/v3/activities/" <> show activityId <> "/kudos"
query = toQuery options
| null |
https://raw.githubusercontent.com/tfausak/strive/8bd61df4b2723301273b11589c5f237b42e934dc/source/library/Strive/Actions/Kudos.hs
|
haskell
|
| </>
| </#list>
|
module Strive.Actions.Kudos
( getActivityKudoers,
)
where
import Network.HTTP.Types (toQuery)
import Strive.Aliases (ActivityId, Result)
import Strive.Client (Client)
import Strive.Internal.HTTP (get)
import Strive.Options (GetActivityKudoersOptions)
import Strive.Types (AthleteSummary)
getActivityKudoers ::
Client ->
ActivityId ->
GetActivityKudoersOptions ->
IO (Result [AthleteSummary])
getActivityKudoers client activityId options = get client resource query
where
resource = "api/v3/activities/" <> show activityId <> "/kudos"
query = toQuery options
|
ebe2ba550abf5ef78b31f5966239cfbf36abd3e86b704086236c49ea14cf0d93
|
sbcl/sbcl
|
barrier.lisp
|
;;;; Support for memory barriers required for multithreaded operation
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB-THREAD")
;;; If no memory barrier vops exist, then the %{mumble}-BARRIER function is an inline
;;; function that does nothing. If the vops exist, then the same function
is always translated with a vop , and the DEFUN is merely an interpreter stub .
(eval-when (:compile-toplevel)
(sb-xc:defmacro def-barrier (name)
(if (sb-c::vop-existsp :named sb-vm:%memory-barrier)
`(defun ,name () (,name))
`(progn (declaim (inline ,name)) (defun ,name () (values))))))
(def-barrier sb-vm:%compiler-barrier)
(def-barrier sb-vm:%memory-barrier)
(def-barrier sb-vm:%read-barrier)
(def-barrier sb-vm:%write-barrier)
(def-barrier sb-vm:%data-dependency-barrier)
;;;; The actual barrier macro and support
(defconstant-eqx +barrier-kind-functions+
'(:compiler sb-vm:%compiler-barrier :memory sb-vm:%memory-barrier
:read sb-vm:%read-barrier :write sb-vm:%write-barrier
:data-dependency sb-vm:%data-dependency-barrier)
#'equal)
(defmacro barrier ((kind) &body forms)
"Insert a barrier in the code stream, preventing some sort of
reordering.
KIND should be one of:
:COMPILER
Prevent the compiler from reordering memory access across the
barrier.
:MEMORY
Prevent the cpu from reordering any memory access across the
barrier.
:READ
Prevent the cpu from reordering any read access across the
barrier.
:WRITE
Prevent the cpu from reordering any write access across the
barrier.
:DATA-DEPENDENCY
Prevent the cpu from reordering dependent memory reads across the
barrier (requiring reads before the barrier to complete before any
reads after the barrier that depend on them). This is a weaker
form of the :READ barrier.
FORMS is an implicit PROGN, evaluated before the barrier. BARRIER
returns the values of the last form in FORMS.
The file \"memory-barriers.txt\" in the Linux kernel documentation is
highly recommended reading for anyone programming at this level."
`(multiple-value-prog1
(progn ,@forms)
(,(or (getf +barrier-kind-functions+ kind)
(error "Unknown barrier kind ~S" kind)))))
| null |
https://raw.githubusercontent.com/sbcl/sbcl/8911276f69a6f3e11f81e6da7c6b84c6302a4f35/src/code/barrier.lisp
|
lisp
|
Support for memory barriers required for multithreaded operation
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
If no memory barrier vops exist, then the %{mumble}-BARRIER function is an inline
function that does nothing. If the vops exist, then the same function
The actual barrier macro and support
|
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB-THREAD")
is always translated with a vop , and the DEFUN is merely an interpreter stub .
(eval-when (:compile-toplevel)
(sb-xc:defmacro def-barrier (name)
(if (sb-c::vop-existsp :named sb-vm:%memory-barrier)
`(defun ,name () (,name))
`(progn (declaim (inline ,name)) (defun ,name () (values))))))
(def-barrier sb-vm:%compiler-barrier)
(def-barrier sb-vm:%memory-barrier)
(def-barrier sb-vm:%read-barrier)
(def-barrier sb-vm:%write-barrier)
(def-barrier sb-vm:%data-dependency-barrier)
(defconstant-eqx +barrier-kind-functions+
'(:compiler sb-vm:%compiler-barrier :memory sb-vm:%memory-barrier
:read sb-vm:%read-barrier :write sb-vm:%write-barrier
:data-dependency sb-vm:%data-dependency-barrier)
#'equal)
(defmacro barrier ((kind) &body forms)
"Insert a barrier in the code stream, preventing some sort of
reordering.
KIND should be one of:
:COMPILER
Prevent the compiler from reordering memory access across the
barrier.
:MEMORY
Prevent the cpu from reordering any memory access across the
barrier.
:READ
Prevent the cpu from reordering any read access across the
barrier.
:WRITE
Prevent the cpu from reordering any write access across the
barrier.
:DATA-DEPENDENCY
Prevent the cpu from reordering dependent memory reads across the
barrier (requiring reads before the barrier to complete before any
reads after the barrier that depend on them). This is a weaker
form of the :READ barrier.
FORMS is an implicit PROGN, evaluated before the barrier. BARRIER
returns the values of the last form in FORMS.
The file \"memory-barriers.txt\" in the Linux kernel documentation is
highly recommended reading for anyone programming at this level."
`(multiple-value-prog1
(progn ,@forms)
(,(or (getf +barrier-kind-functions+ kind)
(error "Unknown barrier kind ~S" kind)))))
|
cd8d1abfa626720177039eecb3b5f5b2c54240b3465695bd3340bcf3cbe8652b
|
thierry-martinez/stdcompat
|
lexing.mli
|
type position =
{
pos_fname: string ;
pos_lnum: int ;
pos_bol: int ;
pos_cnum: int }
val dummy_pos : position
type lexbuf =
{
refill_buff: lexbuf -> unit ;
mutable lex_buffer: string ;
mutable lex_buffer_len: int ;
mutable lex_abs_pos: int ;
mutable lex_start_pos: int ;
mutable lex_curr_pos: int ;
mutable lex_last_pos: int ;
mutable lex_last_action: int ;
mutable lex_eof_reached: bool ;
mutable lex_mem: int array ;
mutable lex_start_p: position ;
mutable lex_curr_p: position }
val from_channel : in_channel -> lexbuf
val from_string : string -> lexbuf
val from_function : (string -> int -> int) -> lexbuf
val lexeme : lexbuf -> string
val lexeme_char : lexbuf -> int -> char
val lexeme_start : lexbuf -> int
val lexeme_end : lexbuf -> int
val lexeme_start_p : lexbuf -> position
val lexeme_end_p : lexbuf -> position
val new_line : lexbuf -> unit
val flush_input : lexbuf -> unit
val sub_lexeme : lexbuf -> int -> int -> string
val sub_lexeme_opt : lexbuf -> int -> int -> string option
val sub_lexeme_char : lexbuf -> int -> char
val sub_lexeme_char_opt : lexbuf -> int -> char option
type lex_tables =
{
lex_base: string ;
lex_backtrk: string ;
lex_default: string ;
lex_trans: string ;
lex_check: string ;
lex_base_code: string ;
lex_backtrk_code: string ;
lex_default_code: string ;
lex_trans_code: string ;
lex_check_code: string ;
lex_code: string }
val engine : lex_tables -> int -> lexbuf -> int
val new_engine : lex_tables -> int -> lexbuf -> int
| null |
https://raw.githubusercontent.com/thierry-martinez/stdcompat/83d786cdb17fae0caadf5c342e283c3dcfee2279/interfaces/3.11/lexing.mli
|
ocaml
|
type position =
{
pos_fname: string ;
pos_lnum: int ;
pos_bol: int ;
pos_cnum: int }
val dummy_pos : position
type lexbuf =
{
refill_buff: lexbuf -> unit ;
mutable lex_buffer: string ;
mutable lex_buffer_len: int ;
mutable lex_abs_pos: int ;
mutable lex_start_pos: int ;
mutable lex_curr_pos: int ;
mutable lex_last_pos: int ;
mutable lex_last_action: int ;
mutable lex_eof_reached: bool ;
mutable lex_mem: int array ;
mutable lex_start_p: position ;
mutable lex_curr_p: position }
val from_channel : in_channel -> lexbuf
val from_string : string -> lexbuf
val from_function : (string -> int -> int) -> lexbuf
val lexeme : lexbuf -> string
val lexeme_char : lexbuf -> int -> char
val lexeme_start : lexbuf -> int
val lexeme_end : lexbuf -> int
val lexeme_start_p : lexbuf -> position
val lexeme_end_p : lexbuf -> position
val new_line : lexbuf -> unit
val flush_input : lexbuf -> unit
val sub_lexeme : lexbuf -> int -> int -> string
val sub_lexeme_opt : lexbuf -> int -> int -> string option
val sub_lexeme_char : lexbuf -> int -> char
val sub_lexeme_char_opt : lexbuf -> int -> char option
type lex_tables =
{
lex_base: string ;
lex_backtrk: string ;
lex_default: string ;
lex_trans: string ;
lex_check: string ;
lex_base_code: string ;
lex_backtrk_code: string ;
lex_default_code: string ;
lex_trans_code: string ;
lex_check_code: string ;
lex_code: string }
val engine : lex_tables -> int -> lexbuf -> int
val new_engine : lex_tables -> int -> lexbuf -> int
|
|
a9151adef9e6f9ce1c564baf9b90c5baac18446f0bdddc1eb934bdad5f266adb
|
shiguredo/swidden
|
swidden_dispatch.erl
|
-module(swidden_dispatch).
-export([get_dispatches/0]).
-export([lookup/3]).
-export([start/1]).
-export_type([service/0, operation/0, version/0, id/0]).
-include("swidden.hrl").
-include("swidden_dispatch.hrl").
-type service() :: binary().
-type operation() :: binary().
-type version() :: binary().
-type id() :: {service(), version(), operation()}.
-define(TABLE, swidden_dispatch_table).
-spec get_dispatches() -> [#swidden_dispatch{}].
get_dispatches() ->
ets:tab2list(?TABLE).
-spec lookup(service(), version(), operation()) -> not_found | {module(), atom()}.
lookup(Service, Version, Operation) ->
case ets:lookup(?TABLE, {Service, Version, Operation}) of
[] ->
not_found;
[#swidden_dispatch{module = Module, schema = Schema}] ->
%% Schema == Function
{Module, Schema}
end.
-spec start(atom()) -> ok.
start(Name) when is_atom(Name) ->
case ets:info(?TABLE) of
undefined ->
_Tid = ets:new(?TABLE, [set, public, named_table, {keypos, #swidden_dispatch.id}]),
case load_dispatch_conf(Name) of
ok ->
ok;
{error, Reason} ->
error(Reason)
end;
_Info ->
ok
end.
%% INTERNAL
load_dispatch_conf(Name) ->
case code:priv_dir(Name) of
{error, Reason} ->
{error, Reason};
PrivPath ->
< application>/priv / swidden / dispatch.conf
Path = filename:join([PrivPath, "swidden", "dispatch.conf"]),
case file:consult(Path) of
{ok, Dispatch} ->
ok = load_services(Dispatch);
{error, Reason} ->
{error, Reason}
end
end.
load_services([]) ->
ok;
load_services([{Service, Versions}|Rest]) when is_binary(Service) ->
%% TODO(nakai): Service が [a-zA-Z]+ かどうかチェックすること
ok = load_versions(Service, Versions),
load_services(Rest).
load_versions(_Service, []) ->
ok;
load_versions(Service, [{Version, Operations}|Rest]) when is_binary(Version) ->
%% TODO(nakai): Version が YYYYMMDD かどうかをチェックすること
ok = load_operations(Service, Version, Operations),
load_versions(Service, Rest).
load_operations(_Service, _Version, []) ->
ok;
load_operations(Service, Version, [{Operation, Module}|Rest])
when is_binary(Operation), is_atom(Module) ->
TODO(nakai ): Operation が CamelCase かチェックする
%% atom 生成しているが、起動時の一回だけなので問題ない
FIXME(nakai ): ここで pascal2snake のエラーを探し出す
Schema = binary_to_atom(swidden_misc:pascal2snake(Operation), utf8),
true = ets:insert(?TABLE, #swidden_dispatch{id = {Service, Version, Operation},
module = Module, schema = Schema}),
load_operations(Service, Version, Rest).
| null |
https://raw.githubusercontent.com/shiguredo/swidden/faec93ae6b6c9e59840f0df22c5f72e381b54c02/src/swidden_dispatch.erl
|
erlang
|
Schema == Function
INTERNAL
TODO(nakai): Service が [a-zA-Z]+ かどうかチェックすること
TODO(nakai): Version が YYYYMMDD かどうかをチェックすること
atom 生成しているが、起動時の一回だけなので問題ない
|
-module(swidden_dispatch).
-export([get_dispatches/0]).
-export([lookup/3]).
-export([start/1]).
-export_type([service/0, operation/0, version/0, id/0]).
-include("swidden.hrl").
-include("swidden_dispatch.hrl").
-type service() :: binary().
-type operation() :: binary().
-type version() :: binary().
-type id() :: {service(), version(), operation()}.
-define(TABLE, swidden_dispatch_table).
-spec get_dispatches() -> [#swidden_dispatch{}].
get_dispatches() ->
ets:tab2list(?TABLE).
-spec lookup(service(), version(), operation()) -> not_found | {module(), atom()}.
lookup(Service, Version, Operation) ->
case ets:lookup(?TABLE, {Service, Version, Operation}) of
[] ->
not_found;
[#swidden_dispatch{module = Module, schema = Schema}] ->
{Module, Schema}
end.
-spec start(atom()) -> ok.
start(Name) when is_atom(Name) ->
case ets:info(?TABLE) of
undefined ->
_Tid = ets:new(?TABLE, [set, public, named_table, {keypos, #swidden_dispatch.id}]),
case load_dispatch_conf(Name) of
ok ->
ok;
{error, Reason} ->
error(Reason)
end;
_Info ->
ok
end.
load_dispatch_conf(Name) ->
case code:priv_dir(Name) of
{error, Reason} ->
{error, Reason};
PrivPath ->
< application>/priv / swidden / dispatch.conf
Path = filename:join([PrivPath, "swidden", "dispatch.conf"]),
case file:consult(Path) of
{ok, Dispatch} ->
ok = load_services(Dispatch);
{error, Reason} ->
{error, Reason}
end
end.
load_services([]) ->
ok;
load_services([{Service, Versions}|Rest]) when is_binary(Service) ->
ok = load_versions(Service, Versions),
load_services(Rest).
load_versions(_Service, []) ->
ok;
load_versions(Service, [{Version, Operations}|Rest]) when is_binary(Version) ->
ok = load_operations(Service, Version, Operations),
load_versions(Service, Rest).
load_operations(_Service, _Version, []) ->
ok;
load_operations(Service, Version, [{Operation, Module}|Rest])
when is_binary(Operation), is_atom(Module) ->
TODO(nakai ): Operation が CamelCase かチェックする
FIXME(nakai ): ここで pascal2snake のエラーを探し出す
Schema = binary_to_atom(swidden_misc:pascal2snake(Operation), utf8),
true = ets:insert(?TABLE, #swidden_dispatch{id = {Service, Version, Operation},
module = Module, schema = Schema}),
load_operations(Service, Version, Rest).
|
69f2f4c057f9e8086646cc3d2dd9dcd33b438bf524c0753699b34f008310fe49
|
cjdev/cloud-seeder
|
Provision.hs
|
module Network.CloudSeeder.Commands.Provision
( provisionCommand
) where
import Control.Applicative.Lift (Errors, failure, runErrors)
import Control.Arrow (second)
import Control.Lens (Getting, Prism', (^.), (^..), (^?), _1, _2, _Wrapped, anyOf, aside, each, filtered, folded, has, to)
import Control.Monad (unless, when)
import Control.Monad.Error.Lens (throwing)
import Control.Monad.Except (MonadError(..), runExceptT)
import Control.Monad.Logger (MonadLogger, logInfoN)
import Control.Monad.Reader (runReaderT)
import Control.Monad.State (execStateT)
import Data.Coerce (coerce)
import Data.Function (on)
import Data.List (groupBy, sort)
import Data.Text.Encoding (encodeUtf8)
import Data.Semigroup (Endo, (<>))
import Data.Yaml (decodeEither)
import Prelude hiding (readFile)
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.Set as S
import qualified Network.CloudSeeder.CommandLine as CL
import Network.CloudSeeder.Commands.Shared
import Network.CloudSeeder.DSL
import Network.CloudSeeder.Error
import Network.CloudSeeder.Monads.AWS
import Network.CloudSeeder.Monads.Environment
import Network.CloudSeeder.Monads.FileSystem
import Network.CloudSeeder.Template
import Network.CloudSeeder.Types
provisionCommand :: (AsCliError e, MonadCloud e m, MonadFileSystem e m, MonadEnvironment m, MonadLogger m)
=> m (DeploymentConfiguration m) -> T.Text -> T.Text -> [String] -> m ()
provisionCommand mConfig nameToProvision env input = do
config <- mConfig
stackToProvision <- getStackFromConfig config nameToProvision
let dependencies = takeWhile (\stak -> (stak ^. name) /= nameToProvision) (config ^.. stacks.each)
appName = config ^. name
fullStackName = mkFullStackName env appName nameToProvision
(StackName fullStackNameText) = fullStackName
paramSources = (config ^. parameterSources) <> (stackToProvision ^. parameterSources)
isGlobalStack = stackToProvision ^. globalStack
assertMatchingGlobalness env nameToProvision isGlobalStack
templateBody <- readFile $ nameToProvision <> ".yaml"
paramSpecs <- parseTemplate templateBody
newStackOrPreviousValues <- getStackProvisionType fullStackName
allTags <- getTags config stackToProvision env appName
(doNotWaitOption, allParams) <- getParameters newStackOrPreviousValues config stackToProvision paramSources paramSpecs dependencies env appName input
logInfoN ("computing change set for stack " <> fullStackNameText <> "...")
csId' <- computeChangeset fullStackName newStackOrPreviousValues templateBody allParams allTags
csInfo <- describeChangeSet csId'
logInfoN =<< toYamlText csInfo "Change Set"
logInfoN ("executing change set for stack " <> fullStackNameText <> "...")
_ <- runChangeSet csId'
unless doNotWaitOption $ do
waitOnStack fullStackName
provisionedStack <- describeStack fullStackName
stackInfo <- maybe
(throwing _CliCloudError (CloudErrorInternal "stack did not exist after wait"))
pure
provisionedStack
logInfoN =<< toYamlText stackInfo "Stack"
let maybePolicyPath = stackToProvision ^. stackPolicyPath
case maybePolicyPath of
Just policyPath -> setStackPolicy fullStackName =<< readFile policyPath
_ -> pure ()
assertMatchingGlobalness :: (AsCliError e, MonadError e m) => T.Text -> T.Text -> Bool -> m ()
assertMatchingGlobalness env nameToProvision isGlobalStack = do
when (env == "global" && not isGlobalStack) $
throwing _CliStackNotGlobal nameToProvision
when (env /= "global" && isGlobalStack) $
throwing _CliGlobalStackMustProvisionToGlobal nameToProvision
getStackProvisionType :: (MonadCloud e m) => StackName -> m ProvisionType
getStackProvisionType stackName = do
maybeStack <- describeStack stackName
pure $ case maybeStack of
Nothing -> CreateStack
Just s -> UpdateStack (s ^. parameters)
parseTemplate :: (AsCliError e, MonadError e m) => T.Text -> m (S.Set ParameterSpec)
parseTemplate templateBody = do
let decodeOrFailure = decodeEither (encodeUtf8 templateBody) :: Either String Template
template <- either (throwing _CliTemplateDecodeFail) return decodeOrFailure
pure $ template ^. parameterSpecs._Wrapped
getTags
:: (MonadError e m, AsCliError e)
=> DeploymentConfiguration m -> StackConfiguration m -> T.Text -> T.Text -> m (M.Map T.Text T.Text)
getTags config stackToProvision env appName =
assertUnique _CliDuplicateTagValues (baseTags <> globalTags <> localTags)
where
baseTags :: S.Set (T.Text, T.Text)
baseTags = [("cj:environment", env), ("cj:application", appName)]
globalTags = config ^. tagSet
localTags = stackToProvision ^. tagSet
-- | Fetches parameter values for all param sources, handling potential errors
-- and misconfigurations.
getParameters
:: forall e m. (AsCliError e, MonadError e m, MonadEnvironment m, MonadCloud e m)
=> ProvisionType
-> DeploymentConfiguration m
-> StackConfiguration m
-> S.Set (T.Text, ParameterSource) -- ^ parameter sources to fetch values for
-> S.Set ParameterSpec -- ^ parameter specs from the template currently being deployed
-> [StackConfiguration m] -- ^ stack dependencies
-> T.Text -- ^ name of environment being deployed to
-> T.Text -- ^ name of application being deployed
-> [String] -- ^ command line input
-> m (Bool, M.Map T.Text ParameterValue)
getParameters provisionType config stackToProvision paramSources allParamSpecs dependencies env appName input = do
let paramSpecs = setRequiredSpecsWithPreviousValuesToOptional allParamSpecs
constants = paramSources ^..* folded.aside _Constant.to (second Value)
(doNotWaitOption, flags' :: S.Set (T.Text, ParameterValue)) <- options paramSpecs
outputs' <- stackOutputs
envVars' <- envVars
let fetchedParams = S.unions [envVars', flags', S.map (second Value) outputs']
initialParams = replaceUsePreviousValuesWherePossible $ S.insert ("Env", Value env) (constants <> fetchedParams)
validInitialParams <- validateParameters paramSpecs initialParams
postHookParams <- if provisionType == CreateStack
then runCreateHooks validInitialParams outputs'
else return validInitialParams
assertNoMissingRequiredParameters postHookParams paramSpecs
pure (doNotWaitOption, postHookParams)
where
-- | Sets `Required` parameter specs to `Optional` where previous values
-- exist.
setRequiredSpecsWithPreviousValuesToOptional :: S.Set ParameterSpec -> S.Set ParameterSpec
setRequiredSpecsWithPreviousValuesToOptional pSpecs = do
let previousParamKeys = provisionType ^. _UpdateStack
requiredParamSpecs = pSpecs ^..* folded._Required
optionalParamSpecs = pSpecs ^..* folded._Optional
mkOptionalIfPreviousValue key = if key `S.member` previousParamKeys
then Optional key UsePreviousValue
else Required key
tupleToOptional (key, val) = Optional key val
(mkOptionalIfPreviousValue `S.map` requiredParamSpecs) `S.union` (tupleToOptional `S.map` optionalParamSpecs)
envVars :: m (S.Set (T.Text, ParameterValue))
envVars = do
let requiredEnvVars = paramSources ^.. folded.filtered (has (_2._Env))._1
maybeEnvValues <- mapM (\envVarKey -> (envVarKey,) <$> getEnv envVarKey) requiredEnvVars
let envVarsOrFailure = runErrors $ traverse (extractResult (,)) maybeEnvValues
either (throwing _CliMissingEnvVars . sort) (return . S.fromList . fmap (second Value)) envVarsOrFailure
options :: S.Set ParameterSpec -> m (Bool, S.Set (T.Text, ParameterValue))
options paramSpecs = do
let paramFlags = paramSources ^..* folded.filtered (has (_2._Flag))._1
flaggedParamSpecs = paramSpecs ^..* folded.filtered (anyOf parameterKey (`elem` paramFlags))
paramSpecNames = paramSpecs ^..* folded.parameterKey
paramFlagsNotInTemplate = paramFlags ^..* folded.filtered (`notElem` paramSpecNames)
unless (S.null paramFlagsNotInTemplate) $
throwing _CliExtraParameterFlags paramFlagsNotInTemplate
options' <- parseOpts flaggedParamSpecs input
let doNotWaitOption = options' ^. CL.doNotWait
params = options' ^. CL.parameters
pure (doNotWaitOption, S.fromList $ M.toList params)
stackOutputs :: m (S.Set (T.Text, T.Text))
stackOutputs = do
maybeLocalOutputs <- getOutputs (\s -> not (s ^. globalStack)) env
maybeGlobalOutputs <- getOutputs (^. globalStack) "global"
let maybeOutputs = maybeLocalOutputs <> maybeGlobalOutputs
outputsOrFailure = runErrors $ traverse (extractResult (flip const)) maybeOutputs
either (throwing _CliMissingDependencyStacks) (return . S.fromList . concatMap M.toList) outputsOrFailure
where
getOutputs :: (StackConfiguration m -> Bool) -> T.Text -> m [(T.Text, Maybe (M.Map T.Text T.Text))]
getOutputs predicate envName = do
let filteredDependencies = dependencies ^.. folded.filtered predicate
filteredDependencyNames = filteredDependencies ^.. each.name
filteredDependencyStacks :: [(T.Text, Maybe Stack)] <- mapM (\stackName -> (stackName,) <$> describeStack (mkFullStackName envName appName stackName)) filteredDependencyNames
let maybeStackToMaybeOutputs :: Maybe Stack -> Maybe (M.Map T.Text T.Text)
maybeStackToMaybeOutputs maybeStack = case maybeStack of
Just s -> s ^? outputs
Nothing -> Nothing
let filteredDependencyOutputs :: [(T.Text, Maybe (M.Map T.Text T.Text))]
= second maybeStackToMaybeOutputs <$> filteredDependencyStacks
pure filteredDependencyOutputs
-- | Removes parameters sourced from previous values where provided values
-- exist, to avoid spurious duplicate parameter errors.
replaceUsePreviousValuesWherePossible :: S.Set (T.Text, ParameterValue) -> S.Set (T.Text, ParameterValue)
replaceUsePreviousValuesWherePossible params =
let previousParams = params ^..* folded.filtered (has $ _2._UsePreviousValue)
providedParams = S.difference params previousParams
previousValuesToKeep = S.filter
(\(key, _) -> not $ key `S.member` S.map fst providedParams)
previousParams
in S.union previousValuesToKeep providedParams
validateParameters :: S.Set ParameterSpec -> S.Set (T.Text, ParameterValue) -> m (M.Map T.Text ParameterValue)
validateParameters paramSpecs params = do
uniqueParams <- assertUnique _CliDuplicateParameterValues params
let allowedParamNames = paramSpecs ^..* folded.parameterKey
let previousParams = M.fromList $ S.toAscList $ paramSpecs ^..* folded._Optional.filtered (has $ _2._UsePreviousValue)
let allUniqueParams = M.union uniqueParams previousParams
return $ allUniqueParams `M.intersection` M.fromSet (const ()) allowedParamNames
runCreateHooks :: M.Map T.Text ParameterValue -> S.Set (T.Text, T.Text) -> m (M.Map T.Text ParameterValue)
runCreateHooks params outputs' = do
let createHooks = coerce <$> (stackToProvision ^. hooksCreate)
initialParamValues = M.mapMaybe (^? _Value) params
let hookContext = HookContext outputs' config stackToProvision
createHookParamsOrFailure <- runReaderT (runExceptT $ execStateT (sequence createHooks) initialParamValues) hookContext
createHookParams <- either (throwing _CliError) return createHookParamsOrFailure
return $ M.map Value createHookParams `M.union` params
assertNoMissingRequiredParameters :: M.Map T.Text ParameterValue -> S.Set ParameterSpec -> m ()
assertNoMissingRequiredParameters params paramSpecs = do
let requiredParamNames = paramSpecs ^..* folded._Required
uniqueParams <- assertUnique _CliDuplicateParameterValues (S.fromList $ M.toAscList params)
let missingParamNames = requiredParamNames S.\\ M.keysSet uniqueParams
unless (S.null missingParamNames) $
throwing _CliMissingRequiredParameters missingParamNames
-- | Given a set of tuples that represent a mapping between keys and values,
-- assert the keys are all unique, and produce a map as a result. If any keys
-- are duplicated, the provided prism will be used to signal an error.
assertUnique
:: forall k v e m. (Ord k, MonadError e m)
=> Prism' e (M.Map k [v]) -> S.Set (k, v) -> m (M.Map k v)
assertUnique _Err paramSet = case duplicateParams of
[] -> return $ M.fromList paramList
_ -> throwing _Err duplicateParams
where
paramList = S.toAscList paramSet
paramsGrouped = tuplesToMap paramList
duplicateParams = M.filter ((> 1) . length) paramsGrouped
tuplesToMap :: [(k, v)] -> M.Map k [v]
tuplesToMap xs = M.fromList $ map concatGroup grouped
where
grouped = groupBy ((==) `on` fst) xs
concatGroup ys = (fst (head ys), map snd ys)
-- | Applies a function to the members of a tuple to produce a result, unless
-- the tuple contains 'Nothing', in which case this logs an error in the
-- 'Errors' applicative using the left side of the tuple as a label.
--
> > > runErrors $ extractResult ( , ) ( " foo " , Just True )
-- Right ("foo", True)
> > > runErrors $ extractResult ( , ) ( " foo " , Nothing )
-- Left ["foo"]
extractResult :: (a -> b -> c) -> (a, Maybe b) -> Errors [a] c
extractResult f (k, m) = do
v <- maybe (failure [k]) pure m
pure (f k v)
-- | Like '^..', but collects the result into a 'S.Set' instead of a list.
infixl 8 ^..*
(^..*) :: Ord a => s -> Getting (Endo [a]) s a -> S.Set a
x ^..* l = S.fromList (x ^.. l)
| null |
https://raw.githubusercontent.com/cjdev/cloud-seeder/242a3826a0cef58e1c390b51177e025781aecc66/library/Network/CloudSeeder/Commands/Provision.hs
|
haskell
|
| Fetches parameter values for all param sources, handling potential errors
and misconfigurations.
^ parameter sources to fetch values for
^ parameter specs from the template currently being deployed
^ stack dependencies
^ name of environment being deployed to
^ name of application being deployed
^ command line input
| Sets `Required` parameter specs to `Optional` where previous values
exist.
| Removes parameters sourced from previous values where provided values
exist, to avoid spurious duplicate parameter errors.
| Given a set of tuples that represent a mapping between keys and values,
assert the keys are all unique, and produce a map as a result. If any keys
are duplicated, the provided prism will be used to signal an error.
| Applies a function to the members of a tuple to produce a result, unless
the tuple contains 'Nothing', in which case this logs an error in the
'Errors' applicative using the left side of the tuple as a label.
Right ("foo", True)
Left ["foo"]
| Like '^..', but collects the result into a 'S.Set' instead of a list.
|
module Network.CloudSeeder.Commands.Provision
( provisionCommand
) where
import Control.Applicative.Lift (Errors, failure, runErrors)
import Control.Arrow (second)
import Control.Lens (Getting, Prism', (^.), (^..), (^?), _1, _2, _Wrapped, anyOf, aside, each, filtered, folded, has, to)
import Control.Monad (unless, when)
import Control.Monad.Error.Lens (throwing)
import Control.Monad.Except (MonadError(..), runExceptT)
import Control.Monad.Logger (MonadLogger, logInfoN)
import Control.Monad.Reader (runReaderT)
import Control.Monad.State (execStateT)
import Data.Coerce (coerce)
import Data.Function (on)
import Data.List (groupBy, sort)
import Data.Text.Encoding (encodeUtf8)
import Data.Semigroup (Endo, (<>))
import Data.Yaml (decodeEither)
import Prelude hiding (readFile)
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.Set as S
import qualified Network.CloudSeeder.CommandLine as CL
import Network.CloudSeeder.Commands.Shared
import Network.CloudSeeder.DSL
import Network.CloudSeeder.Error
import Network.CloudSeeder.Monads.AWS
import Network.CloudSeeder.Monads.Environment
import Network.CloudSeeder.Monads.FileSystem
import Network.CloudSeeder.Template
import Network.CloudSeeder.Types
provisionCommand :: (AsCliError e, MonadCloud e m, MonadFileSystem e m, MonadEnvironment m, MonadLogger m)
=> m (DeploymentConfiguration m) -> T.Text -> T.Text -> [String] -> m ()
provisionCommand mConfig nameToProvision env input = do
config <- mConfig
stackToProvision <- getStackFromConfig config nameToProvision
let dependencies = takeWhile (\stak -> (stak ^. name) /= nameToProvision) (config ^.. stacks.each)
appName = config ^. name
fullStackName = mkFullStackName env appName nameToProvision
(StackName fullStackNameText) = fullStackName
paramSources = (config ^. parameterSources) <> (stackToProvision ^. parameterSources)
isGlobalStack = stackToProvision ^. globalStack
assertMatchingGlobalness env nameToProvision isGlobalStack
templateBody <- readFile $ nameToProvision <> ".yaml"
paramSpecs <- parseTemplate templateBody
newStackOrPreviousValues <- getStackProvisionType fullStackName
allTags <- getTags config stackToProvision env appName
(doNotWaitOption, allParams) <- getParameters newStackOrPreviousValues config stackToProvision paramSources paramSpecs dependencies env appName input
logInfoN ("computing change set for stack " <> fullStackNameText <> "...")
csId' <- computeChangeset fullStackName newStackOrPreviousValues templateBody allParams allTags
csInfo <- describeChangeSet csId'
logInfoN =<< toYamlText csInfo "Change Set"
logInfoN ("executing change set for stack " <> fullStackNameText <> "...")
_ <- runChangeSet csId'
unless doNotWaitOption $ do
waitOnStack fullStackName
provisionedStack <- describeStack fullStackName
stackInfo <- maybe
(throwing _CliCloudError (CloudErrorInternal "stack did not exist after wait"))
pure
provisionedStack
logInfoN =<< toYamlText stackInfo "Stack"
let maybePolicyPath = stackToProvision ^. stackPolicyPath
case maybePolicyPath of
Just policyPath -> setStackPolicy fullStackName =<< readFile policyPath
_ -> pure ()
assertMatchingGlobalness :: (AsCliError e, MonadError e m) => T.Text -> T.Text -> Bool -> m ()
assertMatchingGlobalness env nameToProvision isGlobalStack = do
when (env == "global" && not isGlobalStack) $
throwing _CliStackNotGlobal nameToProvision
when (env /= "global" && isGlobalStack) $
throwing _CliGlobalStackMustProvisionToGlobal nameToProvision
getStackProvisionType :: (MonadCloud e m) => StackName -> m ProvisionType
getStackProvisionType stackName = do
maybeStack <- describeStack stackName
pure $ case maybeStack of
Nothing -> CreateStack
Just s -> UpdateStack (s ^. parameters)
parseTemplate :: (AsCliError e, MonadError e m) => T.Text -> m (S.Set ParameterSpec)
parseTemplate templateBody = do
let decodeOrFailure = decodeEither (encodeUtf8 templateBody) :: Either String Template
template <- either (throwing _CliTemplateDecodeFail) return decodeOrFailure
pure $ template ^. parameterSpecs._Wrapped
getTags
:: (MonadError e m, AsCliError e)
=> DeploymentConfiguration m -> StackConfiguration m -> T.Text -> T.Text -> m (M.Map T.Text T.Text)
getTags config stackToProvision env appName =
assertUnique _CliDuplicateTagValues (baseTags <> globalTags <> localTags)
where
baseTags :: S.Set (T.Text, T.Text)
baseTags = [("cj:environment", env), ("cj:application", appName)]
globalTags = config ^. tagSet
localTags = stackToProvision ^. tagSet
getParameters
:: forall e m. (AsCliError e, MonadError e m, MonadEnvironment m, MonadCloud e m)
=> ProvisionType
-> DeploymentConfiguration m
-> StackConfiguration m
-> m (Bool, M.Map T.Text ParameterValue)
getParameters provisionType config stackToProvision paramSources allParamSpecs dependencies env appName input = do
let paramSpecs = setRequiredSpecsWithPreviousValuesToOptional allParamSpecs
constants = paramSources ^..* folded.aside _Constant.to (second Value)
(doNotWaitOption, flags' :: S.Set (T.Text, ParameterValue)) <- options paramSpecs
outputs' <- stackOutputs
envVars' <- envVars
let fetchedParams = S.unions [envVars', flags', S.map (second Value) outputs']
initialParams = replaceUsePreviousValuesWherePossible $ S.insert ("Env", Value env) (constants <> fetchedParams)
validInitialParams <- validateParameters paramSpecs initialParams
postHookParams <- if provisionType == CreateStack
then runCreateHooks validInitialParams outputs'
else return validInitialParams
assertNoMissingRequiredParameters postHookParams paramSpecs
pure (doNotWaitOption, postHookParams)
where
setRequiredSpecsWithPreviousValuesToOptional :: S.Set ParameterSpec -> S.Set ParameterSpec
setRequiredSpecsWithPreviousValuesToOptional pSpecs = do
let previousParamKeys = provisionType ^. _UpdateStack
requiredParamSpecs = pSpecs ^..* folded._Required
optionalParamSpecs = pSpecs ^..* folded._Optional
mkOptionalIfPreviousValue key = if key `S.member` previousParamKeys
then Optional key UsePreviousValue
else Required key
tupleToOptional (key, val) = Optional key val
(mkOptionalIfPreviousValue `S.map` requiredParamSpecs) `S.union` (tupleToOptional `S.map` optionalParamSpecs)
envVars :: m (S.Set (T.Text, ParameterValue))
envVars = do
let requiredEnvVars = paramSources ^.. folded.filtered (has (_2._Env))._1
maybeEnvValues <- mapM (\envVarKey -> (envVarKey,) <$> getEnv envVarKey) requiredEnvVars
let envVarsOrFailure = runErrors $ traverse (extractResult (,)) maybeEnvValues
either (throwing _CliMissingEnvVars . sort) (return . S.fromList . fmap (second Value)) envVarsOrFailure
options :: S.Set ParameterSpec -> m (Bool, S.Set (T.Text, ParameterValue))
options paramSpecs = do
let paramFlags = paramSources ^..* folded.filtered (has (_2._Flag))._1
flaggedParamSpecs = paramSpecs ^..* folded.filtered (anyOf parameterKey (`elem` paramFlags))
paramSpecNames = paramSpecs ^..* folded.parameterKey
paramFlagsNotInTemplate = paramFlags ^..* folded.filtered (`notElem` paramSpecNames)
unless (S.null paramFlagsNotInTemplate) $
throwing _CliExtraParameterFlags paramFlagsNotInTemplate
options' <- parseOpts flaggedParamSpecs input
let doNotWaitOption = options' ^. CL.doNotWait
params = options' ^. CL.parameters
pure (doNotWaitOption, S.fromList $ M.toList params)
stackOutputs :: m (S.Set (T.Text, T.Text))
stackOutputs = do
maybeLocalOutputs <- getOutputs (\s -> not (s ^. globalStack)) env
maybeGlobalOutputs <- getOutputs (^. globalStack) "global"
let maybeOutputs = maybeLocalOutputs <> maybeGlobalOutputs
outputsOrFailure = runErrors $ traverse (extractResult (flip const)) maybeOutputs
either (throwing _CliMissingDependencyStacks) (return . S.fromList . concatMap M.toList) outputsOrFailure
where
getOutputs :: (StackConfiguration m -> Bool) -> T.Text -> m [(T.Text, Maybe (M.Map T.Text T.Text))]
getOutputs predicate envName = do
let filteredDependencies = dependencies ^.. folded.filtered predicate
filteredDependencyNames = filteredDependencies ^.. each.name
filteredDependencyStacks :: [(T.Text, Maybe Stack)] <- mapM (\stackName -> (stackName,) <$> describeStack (mkFullStackName envName appName stackName)) filteredDependencyNames
let maybeStackToMaybeOutputs :: Maybe Stack -> Maybe (M.Map T.Text T.Text)
maybeStackToMaybeOutputs maybeStack = case maybeStack of
Just s -> s ^? outputs
Nothing -> Nothing
let filteredDependencyOutputs :: [(T.Text, Maybe (M.Map T.Text T.Text))]
= second maybeStackToMaybeOutputs <$> filteredDependencyStacks
pure filteredDependencyOutputs
replaceUsePreviousValuesWherePossible :: S.Set (T.Text, ParameterValue) -> S.Set (T.Text, ParameterValue)
replaceUsePreviousValuesWherePossible params =
let previousParams = params ^..* folded.filtered (has $ _2._UsePreviousValue)
providedParams = S.difference params previousParams
previousValuesToKeep = S.filter
(\(key, _) -> not $ key `S.member` S.map fst providedParams)
previousParams
in S.union previousValuesToKeep providedParams
validateParameters :: S.Set ParameterSpec -> S.Set (T.Text, ParameterValue) -> m (M.Map T.Text ParameterValue)
validateParameters paramSpecs params = do
uniqueParams <- assertUnique _CliDuplicateParameterValues params
let allowedParamNames = paramSpecs ^..* folded.parameterKey
let previousParams = M.fromList $ S.toAscList $ paramSpecs ^..* folded._Optional.filtered (has $ _2._UsePreviousValue)
let allUniqueParams = M.union uniqueParams previousParams
return $ allUniqueParams `M.intersection` M.fromSet (const ()) allowedParamNames
runCreateHooks :: M.Map T.Text ParameterValue -> S.Set (T.Text, T.Text) -> m (M.Map T.Text ParameterValue)
runCreateHooks params outputs' = do
let createHooks = coerce <$> (stackToProvision ^. hooksCreate)
initialParamValues = M.mapMaybe (^? _Value) params
let hookContext = HookContext outputs' config stackToProvision
createHookParamsOrFailure <- runReaderT (runExceptT $ execStateT (sequence createHooks) initialParamValues) hookContext
createHookParams <- either (throwing _CliError) return createHookParamsOrFailure
return $ M.map Value createHookParams `M.union` params
assertNoMissingRequiredParameters :: M.Map T.Text ParameterValue -> S.Set ParameterSpec -> m ()
assertNoMissingRequiredParameters params paramSpecs = do
let requiredParamNames = paramSpecs ^..* folded._Required
uniqueParams <- assertUnique _CliDuplicateParameterValues (S.fromList $ M.toAscList params)
let missingParamNames = requiredParamNames S.\\ M.keysSet uniqueParams
unless (S.null missingParamNames) $
throwing _CliMissingRequiredParameters missingParamNames
assertUnique
:: forall k v e m. (Ord k, MonadError e m)
=> Prism' e (M.Map k [v]) -> S.Set (k, v) -> m (M.Map k v)
assertUnique _Err paramSet = case duplicateParams of
[] -> return $ M.fromList paramList
_ -> throwing _Err duplicateParams
where
paramList = S.toAscList paramSet
paramsGrouped = tuplesToMap paramList
duplicateParams = M.filter ((> 1) . length) paramsGrouped
tuplesToMap :: [(k, v)] -> M.Map k [v]
tuplesToMap xs = M.fromList $ map concatGroup grouped
where
grouped = groupBy ((==) `on` fst) xs
concatGroup ys = (fst (head ys), map snd ys)
> > > runErrors $ extractResult ( , ) ( " foo " , Just True )
> > > runErrors $ extractResult ( , ) ( " foo " , Nothing )
extractResult :: (a -> b -> c) -> (a, Maybe b) -> Errors [a] c
extractResult f (k, m) = do
v <- maybe (failure [k]) pure m
pure (f k v)
infixl 8 ^..*
(^..*) :: Ord a => s -> Getting (Endo [a]) s a -> S.Set a
x ^..* l = S.fromList (x ^.. l)
|
245d1bce0f2e5aa0ccb0cd7c828bf24f449555c0f9624a020ebb9f397ec961b1
|
rtoy/cmucl
|
run-program.lisp
|
;;; -*- Package: Extensions; Log: code.log -*-
;;;
;;; **********************************************************************
This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
;;;
(ext:file-comment
"$Header: src/code/run-program.lisp $")
;;;
;;; **********************************************************************
;;;
;;; RUN-PROGRAM and friends. Facility for running unix programs from inside
;;; a lisp.
;;;
Written by and , November 1987 , using an earlier
version written by .
;;;
Completely re - written by , July 1989 - January 1990 .
;;;
(in-package "EXTENSIONS")
(intl:textdomain "cmucl")
(export '(run-program process-status process-exit-code process-core-dumped
process-wait process-kill process-input process-output process-plist
process-pty process-error process-status-hook process-alive-p
process-close process-pid process-p))
(alien:def-alien-routine ("prog_status" c-prog-status) c-call:void
(pid c-call:int :out)
(what c-call:int :out)
(code c-call:int :out)
(corep c-call:int :out))
(defun prog-status ()
(multiple-value-bind (ret pid what code corep)
(c-prog-status)
(declare (ignore ret))
(when (plusp pid)
(values pid
(aref #(:signaled :stopped :continued :exited) what)
code
(not (zerop corep))))))
;;;; Process control stuff.
(defvar *active-processes* nil
"List of process structures for all active processes.")
(defstruct (process (:print-function %print-process))
pid ; PID of child process.
Either : RUNNING , : STOPPED , : EXITED , or : SIGNALED .
exit-code ; Either exit code or signal
core-dumped ; T if a core image was dumped.
pty ; Stream to child's pty or nil.
input ; Stream to child's input or nil.
output ; Stream from child's output or nil.
error ; Stream from child's error output or nil.
status-hook ; Closure to call when PROC changes status.
plist ; Place for clients to stash things.
cookie ; List of the number of pipes from the subproc.
)
(defun %print-process (proc stream depth)
(declare (ignore depth))
(print-unreadable-object (proc stream :type t :identity t)
(format stream "~D ~S ~S ~D"
(process-pid proc)
(process-status proc)
:exit-code
(process-exit-code proc))))
;;; PROCESS-STATUS -- Public.
;;;
(defun process-status (proc)
"Return the current status of process. The result is one of
:running,:stopped, :continued, :exited, :signaled."
(declare (type process proc))
(get-processes-status-changes)
(process-%status proc))
;;; PROCESS-WAIT -- Public.
;;;
(defun process-wait (proc &optional check-for-stopped)
"Wait for PROC to quit running for some reason. Returns PROC."
(declare (type process proc))
(loop
(case (process-status proc)
(:running)
(:stopped
(when check-for-stopped
(return)))
(t
(when (zerop (car (process-cookie proc)))
(return))))
(system:serve-all-events 1))
proc)
;;; Add docstrings for the other public PROCESS accessors.
(setf (documentation 'process-pid 'function)
_N"PID of child process.")
(setf (documentation 'process-exit-code 'function)
_N"Exit code for the process if it is :exited; the termination signal
if it is :signaled; 0 if it is :stopped. It is undefined in all
other cases.")
(setf (documentation 'process-core-dumped 'function)
_N"Non-NIL if the process was terminated and a core image was dumped.")
(setf (documentation 'process-pty 'function)
_N"The two-way stream connected to the child's Unix pty connection or NIL.")
(setf (documentation 'process-input 'function)
_N"Stream to child's input or NIL.")
(setf (documentation 'process-output 'function)
_N"Stream from child's output or NIL.")
(setf (documentation 'process-error 'function)
_N"Stream from child's error output or NIL.")
(setf (documentation 'process-status-hook 'function)
_N"The function to be called whenever process's changes status. This
function takes the process as a required argument. This is
setf'able.")
(setf (documentation 'process-plist 'function)
_N"Returns annotations supplibed by users; it is setf'able. This is
available for users to associcate information with the process
without having to build a-lists or hash tables of process
structures.")
#-hpux
;;; FIND-CURRENT-FOREGROUND-PROCESS -- internal
;;;
;;; Finds the current foreground process group id.
;;;
(defun find-current-foreground-process (proc)
(alien:with-alien ((result c-call:int))
(multiple-value-bind
(wonp error)
(unix:unix-ioctl (system:fd-stream-fd (ext:process-pty proc))
unix:TIOCGPGRP
(alien:alien-sap (alien:addr result)))
(unless wonp
(error (intl:gettext "TIOCPGRP ioctl failed: ~S")
(unix:get-unix-error-msg error)))
result))
(process-pid proc))
;;; PROCESS-KILL -- public
;;;
;;; Hand a process a signal.
;;;
(defun process-kill (proc signal &optional (whom :pid))
"Hand SIGNAL to PROC. If whom is :pid, use the kill Unix system call. If
whom is :process-group, use the killpg Unix system call. If whom is
:pty-process-group deliver the signal to whichever process group is currently
in the foreground."
(declare (type process proc))
(let ((pid (ecase whom
((:pid :process-group)
(process-pid proc))
(:pty-process-group
#-hpux
(find-current-foreground-process proc)))))
(multiple-value-bind
(okay errno)
(case whom
#+hpux
(:pty-process-group
(unix:unix-ioctl (system:fd-stream-fd (process-pty proc))
unix:TIOCSIGSEND
(system:int-sap
(unix:unix-signal-number signal))))
((:process-group #-hpux :pty-process-group)
(unix:unix-killpg pid signal))
(t
(unix:unix-kill pid signal)))
(cond ((not okay)
(values nil errno))
((and (eql pid (process-pid proc))
(= (unix:unix-signal-number signal) unix:sigcont))
(setf (process-%status proc) :running)
(setf (process-exit-code proc) nil)
(when (process-status-hook proc)
(funcall (process-status-hook proc) proc))
t)
(t
t)))))
;;; PROCESS-ALIVE-P -- public
;;;
;;; Returns T if the process is still alive, NIL otherwise.
;;;
(defun process-alive-p (proc)
"Returns T if the process is still alive, NIL otherwise."
(declare (type process proc))
(let ((status (process-status proc)))
(if (or (eq status :running)
(eq status :stopped)
(eq status :continued))
t
nil)))
;;; PROCESS-CLOSE -- public
;;;
;;; Close all the streams held open by PROC.
;;;
(defun process-close (proc)
"Close all streams connected to PROC and stop maintaining the status slot."
(declare (type process proc))
(macrolet ((frob (stream abort)
`(when ,stream (close ,stream :abort ,abort))))
(frob (process-pty proc) t) ; Don't FLUSH-OUTPUT to dead process.
'cause it will generate SIGPIPE .
(frob (process-output proc) nil)
(frob (process-error proc) nil))
(system:without-interrupts
(setf *active-processes* (delete proc *active-processes*)))
proc)
;;; SIGCHLD-HANDLER -- Internal.
;;;
This is the handler for sigchld signals that RUN - PROGRAM establishes .
;;;
(defun sigchld-handler (ignore1 ignore2 ignore3)
(declare (ignore ignore1 ignore2 ignore3))
(get-processes-status-changes))
;;; GET-PROCESSES-STATUS-CHANGES -- Internal.
;;;
(defun get-processes-status-changes ()
(loop
(multiple-value-bind (pid what code core)
(prog-status)
(unless pid
(return))
(let ((proc (find pid *active-processes* :key #'process-pid)))
(when proc
(setf (process-%status proc) what)
(setf (process-exit-code proc) code)
(setf (process-core-dumped proc) core)
(when (process-status-hook proc)
(funcall (process-status-hook proc) proc))
(when (or (eq what :exited)
(eq what :signaled))
(system:without-interrupts
(setf *active-processes*
(delete proc *active-processes*)))))))))
;;;; RUN-PROGRAM and close friends.
(defvar *close-on-error* nil
"List of file descriptors to close when RUN-PROGRAM exits due to an error.")
(defvar *close-in-parent* nil
"List of file descriptors to close when RUN-PROGRAM returns in the parent.")
(defvar *handlers-installed* nil
"List of handlers installed by RUN-PROGRAM.")
;;; FIND-A-PTY -- internal
;;;
Finds a pty that is not in use . Returns three values : the file descriptor
;;; for the master side of the pty, the file descriptor for the slave side of
;;; the pty, and the name of the tty device for the slave side.
;;;
#-irix
(defun find-a-pty ()
_N"Returns the master fd, the slave fd, and the name of the tty"
(multiple-value-bind (error master-fd slave-fd)
(unix:unix-openpty nil nil nil)
(when (zerop error)
#-glibc2
(alien:with-alien ((stuff (alien:struct unix:sgttyb)))
(let ((sap (alien:alien-sap stuff)))
(unix:unix-ioctl slave-fd unix:TIOCGETP sap)
(setf (alien:slot stuff 'unix:sg-flags) #o300) ; EVENP|ODDP
(unix:unix-ioctl slave-fd unix:TIOCSETP sap)
(unix:unix-ioctl master-fd unix:TIOCGETP sap)
(setf (alien:slot stuff 'unix:sg-flags)
(logand (alien:slot stuff 'unix:sg-flags)
(lognot 8))) ; ~ECHO
(unix:unix-ioctl master-fd unix:TIOCSETP sap)))
(return-from find-a-pty
(values master-fd
slave-fd
(unix:unix-ttyname slave-fd))))
(error (intl:gettext "Could not find a pty."))))
#+irix
(alien:def-alien-routine ("_getpty" c-getpty) c-call:c-string
(fildes c-call:int :out)
(oflag c-call:int)
(mode c-call:int)
(nofork c-call:int))
#+irix
(defun find-a-pty ()
_N"Returns the master fd, the slave fd, and the name of the tty"
(multiple-value-bind (line master-fd)
(c-getpty (logior unix:o_rdwr unix:o_ndelay) #o600 0)
(let* ((slave-name line)
(slave-fd (unix:unix-open slave-name unix:o_rdwr #o666)))
(when slave-fd
; Maybe put a vhangup here?
#-glibc2
(alien:with-alien ((stuff (alien:struct unix:sgttyb)))
(let ((sap (alien:alien-sap stuff)))
(unix:unix-ioctl slave-fd unix:TIOCGETP sap)
(setf (alien:slot stuff 'unix:sg-flags) #o300) ; EVENP|ODDP
(unix:unix-ioctl slave-fd unix:TIOCSETP sap)
(unix:unix-ioctl master-fd unix:TIOCGETP sap)
(setf (alien:slot stuff 'unix:sg-flags)
(logand (alien:slot stuff 'unix:sg-flags)
(lognot 8))) ; ~ECHO
(unix:unix-ioctl master-fd unix:TIOCSETP sap)))
(return-from find-a-pty
(values master-fd
slave-fd
slave-name))))
(unix:unix-close master-fd))
(error (intl:gettext "Could not find a pty.")))
;;; OPEN-PTY -- internal
;;;
(defun open-pty (pty cookie &optional (external-format :default))
(when pty
(multiple-value-bind
(master slave name)
(find-a-pty)
(push master *close-on-error*)
(push slave *close-in-parent*)
(when (streamp pty)
(multiple-value-bind (new-fd errno) (unix:unix-dup master)
(unless new-fd
(error (intl:gettext "Could not UNIX:UNIX-DUP ~D: ~A")
master (unix:get-unix-error-msg errno)))
(push new-fd *close-on-error*)
(copy-descriptor-to-stream new-fd pty cookie)))
(values name
(system:make-fd-stream master :input t :output t
:external-format external-format)))))
(defmacro round-bytes-to-words (n)
`(logand (the fixnum (+ (the fixnum ,n) 3)) (lognot 3)))
(defun string-list-to-c-strvec (string-list)
;;
;; Make a pass over string-list to calculate the amount of memory
;; needed to hold the strvec.
(let ((string-bytes 0)
;; We need an extra for the null, and an extra 'cause exect clobbers
;; argv[-1].
(vec-bytes (* #-alpha 4 #+alpha 8 (+ (length string-list) 2))))
(declare (fixnum string-bytes vec-bytes))
(dolist (s string-list)
(check-type s simple-string)
(incf string-bytes (round-bytes-to-words (1+ (length s)))))
;;
;; Now allocate the memory and fill it in.
(let* ((total-bytes (+ string-bytes vec-bytes))
(vec-sap (system:allocate-system-memory total-bytes))
(string-sap (sap+ vec-sap vec-bytes))
(i #-alpha 4 #+alpha 8))
(declare (type (and unsigned-byte fixnum) total-bytes i)
(type system:system-area-pointer vec-sap string-sap))
(dolist (s string-list)
(declare (simple-string s))
(let ((n (length s)))
;;
;; Blast the string into place
#-unicode
(kernel:copy-to-system-area (the simple-string s)
(* vm:vector-data-offset vm:word-bits)
string-sap 0
(* (1+ n) vm:byte-bits))
#+unicode
(progn
;; FIXME: Do we need to apply some kind of transformation
to convert Lisp unicode strings to C strings ? Utf-8 ?
(dotimes (k n)
(setf (sap-ref-8 string-sap k)
(logand #xff (char-code (aref s k)))))
(setf (sap-ref-8 string-sap n) 0))
;;
;; Blast the pointer to the string into place
(setf (sap-ref-sap vec-sap i) string-sap)
(setf string-sap (sap+ string-sap (round-bytes-to-words (1+ n))))
(incf i #-alpha 4 #+alpha 8)))
;; Blast in last null pointer
(setf (sap-ref-sap vec-sap i) (int-sap 0))
(values vec-sap (sap+ vec-sap #-alpha 4 #+alpha 8) total-bytes))))
(defmacro with-c-strvec ((var str-list) &body body)
(let ((sap (gensym "SAP-"))
(size (gensym "SIZE-")))
`(multiple-value-bind
(,sap ,var ,size)
(string-list-to-c-strvec ,str-list)
(unwind-protect
(progn
,@body)
(system:deallocate-system-memory ,sap ,size)))))
(alien:def-alien-routine spawn c-call:int
(program c-call:c-string)
(argv (* c-call:c-string))
(envp (* c-call:c-string))
(pty-name c-call:c-string)
(stdin c-call:int)
(stdout c-call:int)
(stderr c-call:int))
;;; RUN-PROGRAM -- public
;;;
;;; RUN-PROGRAM uses fork and execve to run a different program. Strange
;;; stuff happens to keep the unix state of the world coherent.
;;;
;;; The child process needs to get its input from somewhere, and send its
;;; output (both standard and error) to somewhere. We have to do different
;;; things depending on where these somewheres really are.
;;;
For input , there are five options :
;;; - T: Just leave fd 0 alone. Pretty simple.
;;; - "file": Read from the file. We need to open the file and pull the
;;; descriptor out of the stream. The parent should close this stream after
;;; the child is up and running to free any storage used in the parent.
;;; - NIL: Same as "file", but use "/dev/null" as the file.
- : STREAM : Use unix - pipe to create two descriptors . Use system : make - fd - stream
;;; to create the output stream on the writeable descriptor, and pass the
;;; readable descriptor to the child. The parent must close the readable
descriptor for EOF to be passed up correctly .
;;; - a stream: If it's a fd-stream, just pull the descriptor out of it.
;;; Otherwise make a pipe as in :STREAM, and copy everything across.
;;;
;;; For output, there are n options:
- T : Leave descriptor 1 alone .
;;; - "file": dump output to the file.
;;; - NIL: dump output to /dev/null.
;;; - :STREAM: return a stream that can be read from.
;;; - a stream: if it's a fd-stream, use the descriptor in it. Otherwise, copy
;;; stuff from output to stream.
;;;
;;; For error, there are all the same options as output plus:
;;; - :OUTPUT: redirect to the same place as output.
;;;
;;; RUN-PROGRAM returns a process struct for the process if the fork worked,
and NIL if it did not .
;;;
(defun run-program (program args
&key (env *environment-list*) (wait t) pty input
if-input-does-not-exist output (if-output-exists :error)
(error :output) (if-error-exists :error) status-hook
(external-format :default)
(element-type 'base-char))
"RUN-PROGRAM creates a new process and runs the unix program in the
file specified by the simple-string PROGRAM. ARGS are the standard
arguments that can be passed to a Unix program, for no arguments
use NIL (which means just the name of the program is passed as arg 0).
RUN-PROGRAM will either return NIL or a PROCESS structure. See the CMU
Common Lisp Users Manual for details about the PROCESS structure.
The keyword arguments have the following meanings:
:env -
An A-LIST mapping keyword environment variables to
simple-string values. This is the shell environment for
Program. Defaults to *environment-list*.
:wait -
If non-NIL (default), wait until the created process finishes. If
NIL, continue running Lisp until the program finishes.
:pty -
Either T, NIL, or a stream. Unless NIL, the subprocess is established
under a PTY. If :pty is a stream, all output to this pty is sent to
this stream, otherwise the PROCESS-PTY slot is filled in with a stream
connected to pty that can read output and write input.
:input -
Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
input for the current process is inherited. If NIL, /dev/null
is used. If a pathname, the file so specified is used. If a stream,
all the input is read from that stream and send to the subprocess. If
:STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
its output to the process. Defaults to NIL.
:if-input-does-not-exist (when :input is the name of a file) -
can be one of:
:error - generate an error.
:create - create an empty file.
nil (default) - return nil from run-program.
:output -
Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
output for the current process is inherited. If NIL, /dev/null
is used. If a pathname, the file so specified is used. If a stream,
all the output from the process is written to this stream. If
:STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
be read to get the output. Defaults to NIL.
:if-output-exists (when :output is the name of a file) -
can be one of:
:error (default) - generates an error if the file already exists.
:supersede - output from the program supersedes the file.
:append - output from the program is appended to the file.
nil - run-program returns nil without doing anything.
:error and :if-error-exists -
Same as :output and :if-output-exists, except that :error can also be
specified as :output in which case all error output is routed to the
same place as normal output.
:status-hook -
This is a function the system calls whenever the status of the
process changes. The function takes the process as an argument.
:external-format -
This is the external-format used for communication with the subprocess.
:element-type -
When a stream is created for :input or :output, the stream
uses this element-type instead of the default 'BASE-CHAR type.
"
;; Make sure the interrupt handler is installed.
(system:enable-interrupt unix:sigchld #'sigchld-handler)
;; Make sure all the args are okay.
(unless (every #'simple-string-p args)
(error (intl:gettext "All args to program must be simple strings -- ~S.") args))
;; Make sure program is a string that we can use with spawn.
(setf program
(if (pathnamep program)
(lisp::with-pathname (p program)
(or (unix::unix-namestring p)
(namestring p)))
(namestring program)))
(check-type program string)
;; Prepend the program to the argument list.
(push program args)
Clear random specials used by GET - DESCRIPTOR - FOR to communicate cleanup
;; info. Also, establish proc at this level so we can return it.
(let (*close-on-error* *close-in-parent* *handlers-installed* proc)
(unwind-protect
(let ((cookie (list 0)))
(multiple-value-bind
(stdin input-stream)
(get-descriptor-for input cookie :direction :input
:if-does-not-exist if-input-does-not-exist
:external-format external-format
:element-type element-type)
(multiple-value-bind
(stdout output-stream)
(get-descriptor-for output cookie :direction :output
:if-does-not-exist :create
:if-exists if-output-exists
:external-format external-format
:element-type element-type)
(multiple-value-bind
(stderr error-stream)
(if (eq error :output)
(values stdout output-stream)
(get-descriptor-for error cookie :direction :output
:if-does-not-exist :create
:if-exists if-error-exists
:external-format external-format
:element-type element-type))
(multiple-value-bind (pty-name pty-stream)
(open-pty pty cookie external-format)
;; Make sure we are not notified about the child death before
;; we have installed the process struct in *active-processes*
(system:without-interrupts
(with-c-strvec (argv args)
(with-c-strvec
(envp (mapcar #'(lambda (entry)
(concatenate
'string
(symbol-name (car entry))
"="
(cdr entry)))
env))
(let ((child-pid
(without-gcing
(spawn program
argv envp pty-name
stdin stdout stderr))))
(when (< child-pid 0)
(error (intl:gettext "Could not fork child process: ~A")
(unix:get-unix-error-msg)))
(setf proc (make-process :pid child-pid
:%status :running
:pty pty-stream
:input input-stream
:output output-stream
:error error-stream
:status-hook status-hook
:cookie cookie))
(push proc *active-processes*))))))))))
(dolist (fd *close-in-parent*)
(unix:unix-close fd))
(unless proc
(dolist (fd *close-on-error*)
(unix:unix-close fd))
(dolist (handler *handlers-installed*)
(system:remove-fd-handler handler))))
(when (and wait proc)
(process-wait proc))
proc))
;;; COPY-DESCRIPTOR-TO-STREAM -- internal
;;;
Installs a handler for any input that shows up on the file descriptor .
;;; The handler reads the data and writes it to the stream.
;;;
(defun copy-descriptor-to-stream (descriptor stream cookie)
(incf (car cookie))
(let ((string (make-string 256))
handler)
(setf handler
(system:add-fd-handler descriptor :input
#'(lambda (fd)
(declare (ignore fd))
(loop
(unless handler
(return))
(multiple-value-bind
(result readable/errno)
(unix:unix-select (1+ descriptor) (ash 1 descriptor)
0 0 0)
(cond ((null result)
(error (intl:gettext "Could not select on sub-process: ~A")
(unix:get-unix-error-msg readable/errno)))
((zerop result)
(return))))
(alien:with-alien ((buf (alien:array c-call:char 256)))
(multiple-value-bind
(count errno)
(unix:unix-read descriptor (alien-sap buf) 256)
(cond ((or (and (null count)
(eql errno unix:eio))
(eql count 0))
(system:remove-fd-handler handler)
(setf handler nil)
(decf (car cookie))
(unix:unix-close descriptor)
(return))
((null count)
(system:remove-fd-handler handler)
(setf handler nil)
(decf (car cookie))
(error (intl:gettext "Could not read input from sub-process: ~A")
(unix:get-unix-error-msg errno)))
(t
#-unicode
(kernel:copy-from-system-area
(alien-sap buf) 0
string (* vm:vector-data-offset vm:word-bits)
(* count vm:byte-bits))
#+unicode
(let ((sap (alien-sap buf)))
(dotimes (k count)
(setf (aref string k)
(code-char (sap-ref-8 sap k)))))
(write-string string stream
:end count)))))))))))
GET - DESCRIPTOR - FOR -- internal
;;;
;;; Find a file descriptor to use for object given the direction. Returns
;;; the descriptor. If object is :STREAM, returns the created stream as the
second value .
;;;
(defun get-descriptor-for (object cookie &rest keys &key direction
external-format
(element-type 'base-char)
&allow-other-keys)
(cond ((eq object t)
;; No new descriptor is needed.
(values -1 nil))
((eq object nil)
;; Use /dev/null.
(multiple-value-bind
(fd errno)
(unix:unix-open "/dev/null"
(case direction
(:input unix:o_rdonly)
(:output unix:o_wronly)
(t unix:o_rdwr))
#o666)
(unless fd
(error (intl:gettext "Could not open \"/dev/null\": ~A")
(unix:get-unix-error-msg errno)))
(push fd *close-in-parent*)
(values fd nil)))
((eq object :stream)
(multiple-value-bind
(read-fd write-fd)
(unix:unix-pipe)
(unless read-fd
(error (intl:gettext "Could not create pipe: ~A")
(unix:get-unix-error-msg write-fd)))
(case direction
(:input
(push read-fd *close-in-parent*)
(push write-fd *close-on-error*)
(let ((stream (system:make-fd-stream write-fd :output t
:external-format
external-format
:element-type
element-type)))
(values read-fd stream)))
(:output
(push read-fd *close-on-error*)
(push write-fd *close-in-parent*)
(let ((stream (system:make-fd-stream read-fd :input t
:external-format
external-format
:element-type
element-type)))
(values write-fd stream)))
(t
(unix:unix-close read-fd)
(unix:unix-close write-fd)
(error (intl:gettext "Direction must be either :INPUT or :OUTPUT, not ~S")
direction)))))
((or (pathnamep object) (stringp object))
(with-open-stream (file (apply #'open object keys))
(multiple-value-bind
(fd errno)
(unix:unix-dup (system:fd-stream-fd file))
(cond (fd
(push fd *close-in-parent*)
(values fd nil))
(t
(error (intl:gettext "Could not duplicate file descriptor: ~A")
(unix:get-unix-error-msg errno)))))))
((system:fd-stream-p object)
(values (system:fd-stream-fd object) nil))
((streamp object)
(ecase direction
(:input
(dotimes (count
256
(error (intl:gettext "Could not open a temporary file in /tmp")))
(let* ((name (format nil "/tmp/.run-program-~D" count))
(fd (unix:unix-open name
(logior unix:o_rdwr
unix:o_creat
unix:o_excl)
#o666)))
(unix:unix-unlink name)
(when fd
(let ((newline (make-array 1 :element-type '(unsigned-byte 8)
:initial-element (char-code #\Newline))))
(loop
(multiple-value-bind
(line no-cr)
(read-line object nil nil)
(unless line
(return))
Take just the low 8 bits of each char
;; (code) of the string and write that out to
;; the descriptor.
(let ((output (make-array (length line) :element-type '(unsigned-byte 8))))
(dotimes (k (length output))
(setf (aref output k) (ldb (byte 8 0) (char-code (aref line k)))))
(unix:unix-write fd output 0 (length output)))
(if no-cr
(return)
(unix:unix-write fd newline 0 1)))))
(unix:unix-lseek fd 0 unix:l_set)
(push fd *close-in-parent*)
(return (values fd nil))))))
(:output
(multiple-value-bind (read-fd write-fd)
(unix:unix-pipe)
(unless read-fd
(error (intl:gettext "Could not create pipe: ~A")
(unix:get-unix-error-msg write-fd)))
(copy-descriptor-to-stream read-fd object cookie)
(push read-fd *close-on-error*)
(push write-fd *close-in-parent*)
(values write-fd nil)))))
(t
(error (intl:gettext "Invalid option to run-program: ~S") object))))
| null |
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/code/run-program.lisp
|
lisp
|
-*- Package: Extensions; Log: code.log -*-
**********************************************************************
**********************************************************************
RUN-PROGRAM and friends. Facility for running unix programs from inside
a lisp.
Process control stuff.
PID of child process.
Either exit code or signal
T if a core image was dumped.
Stream to child's pty or nil.
Stream to child's input or nil.
Stream from child's output or nil.
Stream from child's error output or nil.
Closure to call when PROC changes status.
Place for clients to stash things.
List of the number of pipes from the subproc.
PROCESS-STATUS -- Public.
PROCESS-WAIT -- Public.
Add docstrings for the other public PROCESS accessors.
the termination signal
0 if it is :stopped. It is undefined in all
it is setf'able. This is
FIND-CURRENT-FOREGROUND-PROCESS -- internal
Finds the current foreground process group id.
PROCESS-KILL -- public
Hand a process a signal.
PROCESS-ALIVE-P -- public
Returns T if the process is still alive, NIL otherwise.
PROCESS-CLOSE -- public
Close all the streams held open by PROC.
Don't FLUSH-OUTPUT to dead process.
SIGCHLD-HANDLER -- Internal.
GET-PROCESSES-STATUS-CHANGES -- Internal.
RUN-PROGRAM and close friends.
FIND-A-PTY -- internal
for the master side of the pty, the file descriptor for the slave side of
the pty, and the name of the tty device for the slave side.
EVENP|ODDP
~ECHO
Maybe put a vhangup here?
EVENP|ODDP
~ECHO
OPEN-PTY -- internal
Make a pass over string-list to calculate the amount of memory
needed to hold the strvec.
We need an extra for the null, and an extra 'cause exect clobbers
argv[-1].
Now allocate the memory and fill it in.
Blast the string into place
FIXME: Do we need to apply some kind of transformation
Blast the pointer to the string into place
Blast in last null pointer
RUN-PROGRAM -- public
RUN-PROGRAM uses fork and execve to run a different program. Strange
stuff happens to keep the unix state of the world coherent.
The child process needs to get its input from somewhere, and send its
output (both standard and error) to somewhere. We have to do different
things depending on where these somewheres really are.
- T: Just leave fd 0 alone. Pretty simple.
- "file": Read from the file. We need to open the file and pull the
descriptor out of the stream. The parent should close this stream after
the child is up and running to free any storage used in the parent.
- NIL: Same as "file", but use "/dev/null" as the file.
to create the output stream on the writeable descriptor, and pass the
readable descriptor to the child. The parent must close the readable
- a stream: If it's a fd-stream, just pull the descriptor out of it.
Otherwise make a pipe as in :STREAM, and copy everything across.
For output, there are n options:
- "file": dump output to the file.
- NIL: dump output to /dev/null.
- :STREAM: return a stream that can be read from.
- a stream: if it's a fd-stream, use the descriptor in it. Otherwise, copy
stuff from output to stream.
For error, there are all the same options as output plus:
- :OUTPUT: redirect to the same place as output.
RUN-PROGRAM returns a process struct for the process if the fork worked,
Make sure the interrupt handler is installed.
Make sure all the args are okay.
Make sure program is a string that we can use with spawn.
Prepend the program to the argument list.
info. Also, establish proc at this level so we can return it.
Make sure we are not notified about the child death before
we have installed the process struct in *active-processes*
COPY-DESCRIPTOR-TO-STREAM -- internal
The handler reads the data and writes it to the stream.
Find a file descriptor to use for object given the direction. Returns
the descriptor. If object is :STREAM, returns the created stream as the
No new descriptor is needed.
Use /dev/null.
(code) of the string and write that out to
the descriptor.
|
This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
(ext:file-comment
"$Header: src/code/run-program.lisp $")
Written by and , November 1987 , using an earlier
version written by .
Completely re - written by , July 1989 - January 1990 .
(in-package "EXTENSIONS")
(intl:textdomain "cmucl")
(export '(run-program process-status process-exit-code process-core-dumped
process-wait process-kill process-input process-output process-plist
process-pty process-error process-status-hook process-alive-p
process-close process-pid process-p))
(alien:def-alien-routine ("prog_status" c-prog-status) c-call:void
(pid c-call:int :out)
(what c-call:int :out)
(code c-call:int :out)
(corep c-call:int :out))
(defun prog-status ()
(multiple-value-bind (ret pid what code corep)
(c-prog-status)
(declare (ignore ret))
(when (plusp pid)
(values pid
(aref #(:signaled :stopped :continued :exited) what)
code
(not (zerop corep))))))
(defvar *active-processes* nil
"List of process structures for all active processes.")
(defstruct (process (:print-function %print-process))
Either : RUNNING , : STOPPED , : EXITED , or : SIGNALED .
)
(defun %print-process (proc stream depth)
(declare (ignore depth))
(print-unreadable-object (proc stream :type t :identity t)
(format stream "~D ~S ~S ~D"
(process-pid proc)
(process-status proc)
:exit-code
(process-exit-code proc))))
(defun process-status (proc)
"Return the current status of process. The result is one of
:running,:stopped, :continued, :exited, :signaled."
(declare (type process proc))
(get-processes-status-changes)
(process-%status proc))
(defun process-wait (proc &optional check-for-stopped)
"Wait for PROC to quit running for some reason. Returns PROC."
(declare (type process proc))
(loop
(case (process-status proc)
(:running)
(:stopped
(when check-for-stopped
(return)))
(t
(when (zerop (car (process-cookie proc)))
(return))))
(system:serve-all-events 1))
proc)
(setf (documentation 'process-pid 'function)
_N"PID of child process.")
(setf (documentation 'process-exit-code 'function)
other cases.")
(setf (documentation 'process-core-dumped 'function)
_N"Non-NIL if the process was terminated and a core image was dumped.")
(setf (documentation 'process-pty 'function)
_N"The two-way stream connected to the child's Unix pty connection or NIL.")
(setf (documentation 'process-input 'function)
_N"Stream to child's input or NIL.")
(setf (documentation 'process-output 'function)
_N"Stream from child's output or NIL.")
(setf (documentation 'process-error 'function)
_N"Stream from child's error output or NIL.")
(setf (documentation 'process-status-hook 'function)
_N"The function to be called whenever process's changes status. This
function takes the process as a required argument. This is
setf'able.")
(setf (documentation 'process-plist 'function)
available for users to associcate information with the process
without having to build a-lists or hash tables of process
structures.")
#-hpux
(defun find-current-foreground-process (proc)
(alien:with-alien ((result c-call:int))
(multiple-value-bind
(wonp error)
(unix:unix-ioctl (system:fd-stream-fd (ext:process-pty proc))
unix:TIOCGPGRP
(alien:alien-sap (alien:addr result)))
(unless wonp
(error (intl:gettext "TIOCPGRP ioctl failed: ~S")
(unix:get-unix-error-msg error)))
result))
(process-pid proc))
(defun process-kill (proc signal &optional (whom :pid))
"Hand SIGNAL to PROC. If whom is :pid, use the kill Unix system call. If
whom is :process-group, use the killpg Unix system call. If whom is
:pty-process-group deliver the signal to whichever process group is currently
in the foreground."
(declare (type process proc))
(let ((pid (ecase whom
((:pid :process-group)
(process-pid proc))
(:pty-process-group
#-hpux
(find-current-foreground-process proc)))))
(multiple-value-bind
(okay errno)
(case whom
#+hpux
(:pty-process-group
(unix:unix-ioctl (system:fd-stream-fd (process-pty proc))
unix:TIOCSIGSEND
(system:int-sap
(unix:unix-signal-number signal))))
((:process-group #-hpux :pty-process-group)
(unix:unix-killpg pid signal))
(t
(unix:unix-kill pid signal)))
(cond ((not okay)
(values nil errno))
((and (eql pid (process-pid proc))
(= (unix:unix-signal-number signal) unix:sigcont))
(setf (process-%status proc) :running)
(setf (process-exit-code proc) nil)
(when (process-status-hook proc)
(funcall (process-status-hook proc) proc))
t)
(t
t)))))
(defun process-alive-p (proc)
"Returns T if the process is still alive, NIL otherwise."
(declare (type process proc))
(let ((status (process-status proc)))
(if (or (eq status :running)
(eq status :stopped)
(eq status :continued))
t
nil)))
(defun process-close (proc)
"Close all streams connected to PROC and stop maintaining the status slot."
(declare (type process proc))
(macrolet ((frob (stream abort)
`(when ,stream (close ,stream :abort ,abort))))
'cause it will generate SIGPIPE .
(frob (process-output proc) nil)
(frob (process-error proc) nil))
(system:without-interrupts
(setf *active-processes* (delete proc *active-processes*)))
proc)
This is the handler for sigchld signals that RUN - PROGRAM establishes .
(defun sigchld-handler (ignore1 ignore2 ignore3)
(declare (ignore ignore1 ignore2 ignore3))
(get-processes-status-changes))
(defun get-processes-status-changes ()
(loop
(multiple-value-bind (pid what code core)
(prog-status)
(unless pid
(return))
(let ((proc (find pid *active-processes* :key #'process-pid)))
(when proc
(setf (process-%status proc) what)
(setf (process-exit-code proc) code)
(setf (process-core-dumped proc) core)
(when (process-status-hook proc)
(funcall (process-status-hook proc) proc))
(when (or (eq what :exited)
(eq what :signaled))
(system:without-interrupts
(setf *active-processes*
(delete proc *active-processes*)))))))))
(defvar *close-on-error* nil
"List of file descriptors to close when RUN-PROGRAM exits due to an error.")
(defvar *close-in-parent* nil
"List of file descriptors to close when RUN-PROGRAM returns in the parent.")
(defvar *handlers-installed* nil
"List of handlers installed by RUN-PROGRAM.")
Finds a pty that is not in use . Returns three values : the file descriptor
#-irix
(defun find-a-pty ()
_N"Returns the master fd, the slave fd, and the name of the tty"
(multiple-value-bind (error master-fd slave-fd)
(unix:unix-openpty nil nil nil)
(when (zerop error)
#-glibc2
(alien:with-alien ((stuff (alien:struct unix:sgttyb)))
(let ((sap (alien:alien-sap stuff)))
(unix:unix-ioctl slave-fd unix:TIOCGETP sap)
(unix:unix-ioctl slave-fd unix:TIOCSETP sap)
(unix:unix-ioctl master-fd unix:TIOCGETP sap)
(setf (alien:slot stuff 'unix:sg-flags)
(logand (alien:slot stuff 'unix:sg-flags)
(unix:unix-ioctl master-fd unix:TIOCSETP sap)))
(return-from find-a-pty
(values master-fd
slave-fd
(unix:unix-ttyname slave-fd))))
(error (intl:gettext "Could not find a pty."))))
#+irix
(alien:def-alien-routine ("_getpty" c-getpty) c-call:c-string
(fildes c-call:int :out)
(oflag c-call:int)
(mode c-call:int)
(nofork c-call:int))
#+irix
(defun find-a-pty ()
_N"Returns the master fd, the slave fd, and the name of the tty"
(multiple-value-bind (line master-fd)
(c-getpty (logior unix:o_rdwr unix:o_ndelay) #o600 0)
(let* ((slave-name line)
(slave-fd (unix:unix-open slave-name unix:o_rdwr #o666)))
(when slave-fd
#-glibc2
(alien:with-alien ((stuff (alien:struct unix:sgttyb)))
(let ((sap (alien:alien-sap stuff)))
(unix:unix-ioctl slave-fd unix:TIOCGETP sap)
(unix:unix-ioctl slave-fd unix:TIOCSETP sap)
(unix:unix-ioctl master-fd unix:TIOCGETP sap)
(setf (alien:slot stuff 'unix:sg-flags)
(logand (alien:slot stuff 'unix:sg-flags)
(unix:unix-ioctl master-fd unix:TIOCSETP sap)))
(return-from find-a-pty
(values master-fd
slave-fd
slave-name))))
(unix:unix-close master-fd))
(error (intl:gettext "Could not find a pty.")))
(defun open-pty (pty cookie &optional (external-format :default))
(when pty
(multiple-value-bind
(master slave name)
(find-a-pty)
(push master *close-on-error*)
(push slave *close-in-parent*)
(when (streamp pty)
(multiple-value-bind (new-fd errno) (unix:unix-dup master)
(unless new-fd
(error (intl:gettext "Could not UNIX:UNIX-DUP ~D: ~A")
master (unix:get-unix-error-msg errno)))
(push new-fd *close-on-error*)
(copy-descriptor-to-stream new-fd pty cookie)))
(values name
(system:make-fd-stream master :input t :output t
:external-format external-format)))))
(defmacro round-bytes-to-words (n)
`(logand (the fixnum (+ (the fixnum ,n) 3)) (lognot 3)))
(defun string-list-to-c-strvec (string-list)
(let ((string-bytes 0)
(vec-bytes (* #-alpha 4 #+alpha 8 (+ (length string-list) 2))))
(declare (fixnum string-bytes vec-bytes))
(dolist (s string-list)
(check-type s simple-string)
(incf string-bytes (round-bytes-to-words (1+ (length s)))))
(let* ((total-bytes (+ string-bytes vec-bytes))
(vec-sap (system:allocate-system-memory total-bytes))
(string-sap (sap+ vec-sap vec-bytes))
(i #-alpha 4 #+alpha 8))
(declare (type (and unsigned-byte fixnum) total-bytes i)
(type system:system-area-pointer vec-sap string-sap))
(dolist (s string-list)
(declare (simple-string s))
(let ((n (length s)))
#-unicode
(kernel:copy-to-system-area (the simple-string s)
(* vm:vector-data-offset vm:word-bits)
string-sap 0
(* (1+ n) vm:byte-bits))
#+unicode
(progn
to convert Lisp unicode strings to C strings ? Utf-8 ?
(dotimes (k n)
(setf (sap-ref-8 string-sap k)
(logand #xff (char-code (aref s k)))))
(setf (sap-ref-8 string-sap n) 0))
(setf (sap-ref-sap vec-sap i) string-sap)
(setf string-sap (sap+ string-sap (round-bytes-to-words (1+ n))))
(incf i #-alpha 4 #+alpha 8)))
(setf (sap-ref-sap vec-sap i) (int-sap 0))
(values vec-sap (sap+ vec-sap #-alpha 4 #+alpha 8) total-bytes))))
(defmacro with-c-strvec ((var str-list) &body body)
(let ((sap (gensym "SAP-"))
(size (gensym "SIZE-")))
`(multiple-value-bind
(,sap ,var ,size)
(string-list-to-c-strvec ,str-list)
(unwind-protect
(progn
,@body)
(system:deallocate-system-memory ,sap ,size)))))
(alien:def-alien-routine spawn c-call:int
(program c-call:c-string)
(argv (* c-call:c-string))
(envp (* c-call:c-string))
(pty-name c-call:c-string)
(stdin c-call:int)
(stdout c-call:int)
(stderr c-call:int))
For input , there are five options :
- : STREAM : Use unix - pipe to create two descriptors . Use system : make - fd - stream
descriptor for EOF to be passed up correctly .
- T : Leave descriptor 1 alone .
and NIL if it did not .
(defun run-program (program args
&key (env *environment-list*) (wait t) pty input
if-input-does-not-exist output (if-output-exists :error)
(error :output) (if-error-exists :error) status-hook
(external-format :default)
(element-type 'base-char))
"RUN-PROGRAM creates a new process and runs the unix program in the
file specified by the simple-string PROGRAM. ARGS are the standard
arguments that can be passed to a Unix program, for no arguments
use NIL (which means just the name of the program is passed as arg 0).
RUN-PROGRAM will either return NIL or a PROCESS structure. See the CMU
Common Lisp Users Manual for details about the PROCESS structure.
The keyword arguments have the following meanings:
:env -
An A-LIST mapping keyword environment variables to
simple-string values. This is the shell environment for
Program. Defaults to *environment-list*.
:wait -
If non-NIL (default), wait until the created process finishes. If
NIL, continue running Lisp until the program finishes.
:pty -
Either T, NIL, or a stream. Unless NIL, the subprocess is established
under a PTY. If :pty is a stream, all output to this pty is sent to
this stream, otherwise the PROCESS-PTY slot is filled in with a stream
connected to pty that can read output and write input.
:input -
Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
input for the current process is inherited. If NIL, /dev/null
is used. If a pathname, the file so specified is used. If a stream,
all the input is read from that stream and send to the subprocess. If
:STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
its output to the process. Defaults to NIL.
:if-input-does-not-exist (when :input is the name of a file) -
can be one of:
:error - generate an error.
:create - create an empty file.
nil (default) - return nil from run-program.
:output -
Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
output for the current process is inherited. If NIL, /dev/null
is used. If a pathname, the file so specified is used. If a stream,
all the output from the process is written to this stream. If
:STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
be read to get the output. Defaults to NIL.
:if-output-exists (when :output is the name of a file) -
can be one of:
:error (default) - generates an error if the file already exists.
:supersede - output from the program supersedes the file.
:append - output from the program is appended to the file.
nil - run-program returns nil without doing anything.
:error and :if-error-exists -
Same as :output and :if-output-exists, except that :error can also be
specified as :output in which case all error output is routed to the
same place as normal output.
:status-hook -
This is a function the system calls whenever the status of the
process changes. The function takes the process as an argument.
:external-format -
This is the external-format used for communication with the subprocess.
:element-type -
When a stream is created for :input or :output, the stream
uses this element-type instead of the default 'BASE-CHAR type.
"
(system:enable-interrupt unix:sigchld #'sigchld-handler)
(unless (every #'simple-string-p args)
(error (intl:gettext "All args to program must be simple strings -- ~S.") args))
(setf program
(if (pathnamep program)
(lisp::with-pathname (p program)
(or (unix::unix-namestring p)
(namestring p)))
(namestring program)))
(check-type program string)
(push program args)
Clear random specials used by GET - DESCRIPTOR - FOR to communicate cleanup
(let (*close-on-error* *close-in-parent* *handlers-installed* proc)
(unwind-protect
(let ((cookie (list 0)))
(multiple-value-bind
(stdin input-stream)
(get-descriptor-for input cookie :direction :input
:if-does-not-exist if-input-does-not-exist
:external-format external-format
:element-type element-type)
(multiple-value-bind
(stdout output-stream)
(get-descriptor-for output cookie :direction :output
:if-does-not-exist :create
:if-exists if-output-exists
:external-format external-format
:element-type element-type)
(multiple-value-bind
(stderr error-stream)
(if (eq error :output)
(values stdout output-stream)
(get-descriptor-for error cookie :direction :output
:if-does-not-exist :create
:if-exists if-error-exists
:external-format external-format
:element-type element-type))
(multiple-value-bind (pty-name pty-stream)
(open-pty pty cookie external-format)
(system:without-interrupts
(with-c-strvec (argv args)
(with-c-strvec
(envp (mapcar #'(lambda (entry)
(concatenate
'string
(symbol-name (car entry))
"="
(cdr entry)))
env))
(let ((child-pid
(without-gcing
(spawn program
argv envp pty-name
stdin stdout stderr))))
(when (< child-pid 0)
(error (intl:gettext "Could not fork child process: ~A")
(unix:get-unix-error-msg)))
(setf proc (make-process :pid child-pid
:%status :running
:pty pty-stream
:input input-stream
:output output-stream
:error error-stream
:status-hook status-hook
:cookie cookie))
(push proc *active-processes*))))))))))
(dolist (fd *close-in-parent*)
(unix:unix-close fd))
(unless proc
(dolist (fd *close-on-error*)
(unix:unix-close fd))
(dolist (handler *handlers-installed*)
(system:remove-fd-handler handler))))
(when (and wait proc)
(process-wait proc))
proc))
Installs a handler for any input that shows up on the file descriptor .
(defun copy-descriptor-to-stream (descriptor stream cookie)
(incf (car cookie))
(let ((string (make-string 256))
handler)
(setf handler
(system:add-fd-handler descriptor :input
#'(lambda (fd)
(declare (ignore fd))
(loop
(unless handler
(return))
(multiple-value-bind
(result readable/errno)
(unix:unix-select (1+ descriptor) (ash 1 descriptor)
0 0 0)
(cond ((null result)
(error (intl:gettext "Could not select on sub-process: ~A")
(unix:get-unix-error-msg readable/errno)))
((zerop result)
(return))))
(alien:with-alien ((buf (alien:array c-call:char 256)))
(multiple-value-bind
(count errno)
(unix:unix-read descriptor (alien-sap buf) 256)
(cond ((or (and (null count)
(eql errno unix:eio))
(eql count 0))
(system:remove-fd-handler handler)
(setf handler nil)
(decf (car cookie))
(unix:unix-close descriptor)
(return))
((null count)
(system:remove-fd-handler handler)
(setf handler nil)
(decf (car cookie))
(error (intl:gettext "Could not read input from sub-process: ~A")
(unix:get-unix-error-msg errno)))
(t
#-unicode
(kernel:copy-from-system-area
(alien-sap buf) 0
string (* vm:vector-data-offset vm:word-bits)
(* count vm:byte-bits))
#+unicode
(let ((sap (alien-sap buf)))
(dotimes (k count)
(setf (aref string k)
(code-char (sap-ref-8 sap k)))))
(write-string string stream
:end count)))))))))))
GET - DESCRIPTOR - FOR -- internal
second value .
(defun get-descriptor-for (object cookie &rest keys &key direction
external-format
(element-type 'base-char)
&allow-other-keys)
(cond ((eq object t)
(values -1 nil))
((eq object nil)
(multiple-value-bind
(fd errno)
(unix:unix-open "/dev/null"
(case direction
(:input unix:o_rdonly)
(:output unix:o_wronly)
(t unix:o_rdwr))
#o666)
(unless fd
(error (intl:gettext "Could not open \"/dev/null\": ~A")
(unix:get-unix-error-msg errno)))
(push fd *close-in-parent*)
(values fd nil)))
((eq object :stream)
(multiple-value-bind
(read-fd write-fd)
(unix:unix-pipe)
(unless read-fd
(error (intl:gettext "Could not create pipe: ~A")
(unix:get-unix-error-msg write-fd)))
(case direction
(:input
(push read-fd *close-in-parent*)
(push write-fd *close-on-error*)
(let ((stream (system:make-fd-stream write-fd :output t
:external-format
external-format
:element-type
element-type)))
(values read-fd stream)))
(:output
(push read-fd *close-on-error*)
(push write-fd *close-in-parent*)
(let ((stream (system:make-fd-stream read-fd :input t
:external-format
external-format
:element-type
element-type)))
(values write-fd stream)))
(t
(unix:unix-close read-fd)
(unix:unix-close write-fd)
(error (intl:gettext "Direction must be either :INPUT or :OUTPUT, not ~S")
direction)))))
((or (pathnamep object) (stringp object))
(with-open-stream (file (apply #'open object keys))
(multiple-value-bind
(fd errno)
(unix:unix-dup (system:fd-stream-fd file))
(cond (fd
(push fd *close-in-parent*)
(values fd nil))
(t
(error (intl:gettext "Could not duplicate file descriptor: ~A")
(unix:get-unix-error-msg errno)))))))
((system:fd-stream-p object)
(values (system:fd-stream-fd object) nil))
((streamp object)
(ecase direction
(:input
(dotimes (count
256
(error (intl:gettext "Could not open a temporary file in /tmp")))
(let* ((name (format nil "/tmp/.run-program-~D" count))
(fd (unix:unix-open name
(logior unix:o_rdwr
unix:o_creat
unix:o_excl)
#o666)))
(unix:unix-unlink name)
(when fd
(let ((newline (make-array 1 :element-type '(unsigned-byte 8)
:initial-element (char-code #\Newline))))
(loop
(multiple-value-bind
(line no-cr)
(read-line object nil nil)
(unless line
(return))
Take just the low 8 bits of each char
(let ((output (make-array (length line) :element-type '(unsigned-byte 8))))
(dotimes (k (length output))
(setf (aref output k) (ldb (byte 8 0) (char-code (aref line k)))))
(unix:unix-write fd output 0 (length output)))
(if no-cr
(return)
(unix:unix-write fd newline 0 1)))))
(unix:unix-lseek fd 0 unix:l_set)
(push fd *close-in-parent*)
(return (values fd nil))))))
(:output
(multiple-value-bind (read-fd write-fd)
(unix:unix-pipe)
(unless read-fd
(error (intl:gettext "Could not create pipe: ~A")
(unix:get-unix-error-msg write-fd)))
(copy-descriptor-to-stream read-fd object cookie)
(push read-fd *close-on-error*)
(push write-fd *close-in-parent*)
(values write-fd nil)))))
(t
(error (intl:gettext "Invalid option to run-program: ~S") object))))
|
1868619c0f4618f0d814d800d9199df72dcdd1b88a13c670f800a26b34878c02
|
facebook/duckling
|
Corpus.hs
|
Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.AF.Corpus
( corpus
) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Numeral.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus =
( testContext {locale = makeLocale AF Nothing}
, testOptions
, allExamples
)
allExamples :: [Example]
allExamples = concat
[ examples (NumeralValue 0)
[ "nul"
, "geen"
, "niks"
]
, examples (NumeralValue 1)
[ "een"
]
, examples (NumeralValue 2)
[ "twee"
]
, examples (NumeralValue 3)
[ "drie"
]
, examples (NumeralValue 4)
[ "vier"
]
, examples (NumeralValue 5)
[ "vyf"
]
, examples (NumeralValue 6)
[ "ses"
]
, examples (NumeralValue 7)
[ "sewe"
]
, examples (NumeralValue 8)
[ "agt"
, "ag"
]
, examples (NumeralValue 9)
[ "nege"
]
, examples (NumeralValue 10)
[ "tien"
]
, examples (NumeralValue 11)
[ "elf"
]
, examples (NumeralValue 12)
[ "twaalf"
, "dosyn"
]
, examples (NumeralValue 14)
[ "veertien"
]
, examples (NumeralValue 15)
[ "vyftien"
]
, examples (NumeralValue 16)
[ "sestien"
]
, examples (NumeralValue 17)
[ "sewentien"
]
, examples (NumeralValue 19)
[ "negentien"
, "neentien"
]
, examples (NumeralValue 20)
[ "twintig"
]
, examples (NumeralValue 22)
[ "twee en twintig"
]
, examples (NumeralValue 24)
[ "vier en twintig"
]
, examples (NumeralValue 26)
[ "ses en twintig"
]
, examples (NumeralValue 28)
[ "agt en twintig"
]
, examples (NumeralValue 33)
[ "drie en dertig"
]
, examples (NumeralValue 34)
[ "vier en dertig"
]
, examples (NumeralValue 50)
[ "vyftig"
]
, examples (NumeralValue 55)
[ "vyf en vyftig"
]
, examples (NumeralValue 1.1)
[ "1,1"
, "1,10"
, "01,10"
]
, examples (NumeralValue 0.77)
[ "0,77"
, ",77"
]
, examples (NumeralValue 300)
[ "3 honderd"
, "drie honderd"
]
, examples (NumeralValue 5000)
[ "5 duisend"
, "vyf duisend"
]
, examples (NumeralValue 144)
[ "een honderd vier en veertig"
, "honderd vier en veertig"
]
, examples (NumeralValue 122)
[ "een honderd twee en twintig"
, "honderd twee en twintig"
]
, examples (NumeralValue 20000)
[ "twintig duisend"
]
, examples (NumeralValue 0.2)
[ "0,2"
, "1/5"
, "2/10"
, "3/15"
, "20/100"
]
]
| null |
https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Numeral/AF/Corpus.hs
|
haskell
|
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE OverloadedStrings #
|
Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.Numeral.AF.Corpus
( corpus
) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Numeral.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus =
( testContext {locale = makeLocale AF Nothing}
, testOptions
, allExamples
)
allExamples :: [Example]
allExamples = concat
[ examples (NumeralValue 0)
[ "nul"
, "geen"
, "niks"
]
, examples (NumeralValue 1)
[ "een"
]
, examples (NumeralValue 2)
[ "twee"
]
, examples (NumeralValue 3)
[ "drie"
]
, examples (NumeralValue 4)
[ "vier"
]
, examples (NumeralValue 5)
[ "vyf"
]
, examples (NumeralValue 6)
[ "ses"
]
, examples (NumeralValue 7)
[ "sewe"
]
, examples (NumeralValue 8)
[ "agt"
, "ag"
]
, examples (NumeralValue 9)
[ "nege"
]
, examples (NumeralValue 10)
[ "tien"
]
, examples (NumeralValue 11)
[ "elf"
]
, examples (NumeralValue 12)
[ "twaalf"
, "dosyn"
]
, examples (NumeralValue 14)
[ "veertien"
]
, examples (NumeralValue 15)
[ "vyftien"
]
, examples (NumeralValue 16)
[ "sestien"
]
, examples (NumeralValue 17)
[ "sewentien"
]
, examples (NumeralValue 19)
[ "negentien"
, "neentien"
]
, examples (NumeralValue 20)
[ "twintig"
]
, examples (NumeralValue 22)
[ "twee en twintig"
]
, examples (NumeralValue 24)
[ "vier en twintig"
]
, examples (NumeralValue 26)
[ "ses en twintig"
]
, examples (NumeralValue 28)
[ "agt en twintig"
]
, examples (NumeralValue 33)
[ "drie en dertig"
]
, examples (NumeralValue 34)
[ "vier en dertig"
]
, examples (NumeralValue 50)
[ "vyftig"
]
, examples (NumeralValue 55)
[ "vyf en vyftig"
]
, examples (NumeralValue 1.1)
[ "1,1"
, "1,10"
, "01,10"
]
, examples (NumeralValue 0.77)
[ "0,77"
, ",77"
]
, examples (NumeralValue 300)
[ "3 honderd"
, "drie honderd"
]
, examples (NumeralValue 5000)
[ "5 duisend"
, "vyf duisend"
]
, examples (NumeralValue 144)
[ "een honderd vier en veertig"
, "honderd vier en veertig"
]
, examples (NumeralValue 122)
[ "een honderd twee en twintig"
, "honderd twee en twintig"
]
, examples (NumeralValue 20000)
[ "twintig duisend"
]
, examples (NumeralValue 0.2)
[ "0,2"
, "1/5"
, "2/10"
, "3/15"
, "20/100"
]
]
|
1fd2852aa8bf2adc2f103ccc81c66feec12aa30b3fe4baae698ce9e22f82871a
|
ephemient/aoc2018
|
Day14Spec.hs
|
module Day14Spec (spec) where
import Day14 (day14a, day14b)
import Test.Hspec (Spec, describe, it, shouldBe)
spec :: Spec
spec = do
describe "part 1" $
it "examples" $ do
day14a "9" `shouldBe` "5158916779"
day14a "5" `shouldBe` "0124515891"
day14a "18" `shouldBe` "9251071085"
day14a "2018" `shouldBe` "5941429882"
describe "part 2" $
it "examples" $ do
day14b "51589" `shouldBe` 9
day14b "01245" `shouldBe` 5
day14b "92510" `shouldBe` 18
day14b "59414" `shouldBe` 2018
| null |
https://raw.githubusercontent.com/ephemient/aoc2018/eb0d04193ccb6ad98ed8ad2253faeb3d503a5938/test/Day14Spec.hs
|
haskell
|
module Day14Spec (spec) where
import Day14 (day14a, day14b)
import Test.Hspec (Spec, describe, it, shouldBe)
spec :: Spec
spec = do
describe "part 1" $
it "examples" $ do
day14a "9" `shouldBe` "5158916779"
day14a "5" `shouldBe` "0124515891"
day14a "18" `shouldBe` "9251071085"
day14a "2018" `shouldBe` "5941429882"
describe "part 2" $
it "examples" $ do
day14b "51589" `shouldBe` 9
day14b "01245" `shouldBe` 5
day14b "92510" `shouldBe` 18
day14b "59414" `shouldBe` 2018
|
|
cc12e44b9d8af950769607c76b8174f2e69bca0fe5f9af03e5198db4c40915ad
|
dparis/gen-phzr
|
tween.cljs
|
(ns phzr.tween
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [delay repeat loop update]))
(defn ->Tween
"A Tween allows you to alter one or more properties of a target object over a defined period of time.
This can be used for things such as alpha fading Sprites, scaling them or motion.
Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object
by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become 'child' tweens and
are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children.
Parameters:
* target (object) - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale.
* game (Phaser.Game) - Current game instance.
* manager (Phaser.TweenManager) - The TweenManager responsible for looking after this Tween."
([target game manager]
(js/Phaser.Tween. (clj->phaser target)
(clj->phaser game)
(clj->phaser manager))))
(defn chain
"This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called
as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress.
Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes.
For that you should listen to `onComplete` on the final tween in your chain.
If you pass multiple tweens to this method they will be joined into a single long chain.
For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C.
Any previously chained tweens that may have been set will be overwritten.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* tweens (Phaser.Tween) - One or more tweens that will be chained to this one.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween tweens]
(phaser->clj
(.chain tween
(clj->phaser tweens)))))
(defn delay
"Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts.
The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay.
If you have child tweens and pass -1 as the index value it sets the delay across all of them.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* duration (number) - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween duration]
(phaser->clj
(.delay tween
(clj->phaser duration))))
([tween duration index]
(phaser->clj
(.delay tween
(clj->phaser duration)
(clj->phaser index)))))
(defn easing
"Set easing function this tween will use, i.e. Phaser.Easing.Linear.None.
The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as 'Circ'.
'.easeIn', '.easeOut' and 'easeInOut' variants are all supported for all ease types.
If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* ease (function | string) - The easing function this tween will use, i.e. Phaser.Easing.Linear.None.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween ease]
(phaser->clj
(.easing tween
(clj->phaser ease))))
([tween ease index]
(phaser->clj
(.easing tween
(clj->phaser ease)
(clj->phaser index)))))
(defn from
"Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value.
For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`.
The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as 'Circ'.
'.easeIn', '.easeOut' and 'easeInOut' variants are all supported for all ease types.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* properties (object) - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
* duration (number) {optional} - Duration of this tween in ms.
* ease (function | string) {optional} - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden.
* auto-start (boolean) {optional} - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start().
* delay (number) {optional} - Delay before this tween will start in milliseconds. Defaults to 0, no delay.
* repeat (number) {optional} - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this induvidual tween, not any chained tweens.
* yoyo (boolean) {optional} - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
Returns: Phaser.Tween - This Tween object."
([tween properties]
(phaser->clj
(.from tween
(clj->phaser properties))))
([tween properties duration]
(phaser->clj
(.from tween
(clj->phaser properties)
(clj->phaser duration))))
([tween properties duration ease]
(phaser->clj
(.from tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease))))
([tween properties duration ease auto-start]
(phaser->clj
(.from tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start))))
([tween properties duration ease auto-start delay]
(phaser->clj
(.from tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start)
(clj->phaser delay))))
([tween properties duration ease auto-start delay repeat]
(phaser->clj
(.from tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start)
(clj->phaser delay)
(clj->phaser repeat))))
([tween properties duration ease auto-start delay repeat yoyo]
(phaser->clj
(.from tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start)
(clj->phaser delay)
(clj->phaser repeat)
(clj->phaser yoyo)))))
(defn generate-data
"This will generate an array populated with the tweened object values from start to end.
It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from.
It ignores delay and repeat counts and any chained tweens, but does include child tweens.
Just one play through of the tween data is returned, including yoyo if set.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* frame-rate (number) {optional} - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates.
* data (array) {optional} - If given the generated data will be appended to this array, otherwise a new array will be returned.
Returns: array - An array of tweened values."
([tween]
(phaser->clj
(.generateData tween)))
([tween frame-rate]
(phaser->clj
(.generateData tween
(clj->phaser frame-rate))))
([tween frame-rate data]
(phaser->clj
(.generateData tween
(clj->phaser frame-rate)
(clj->phaser data)))))
(defn interpolation
"Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation.
Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation.
The interpolation function is only used if the target properties is an array.
If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* interpolation (function) - The interpolation function to use (Phaser.Math.linearInterpolation by default)
* context (object) {optional} - The context under which the interpolation function will be run.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween interpolation]
(phaser->clj
(.interpolation tween
(clj->phaser interpolation))))
([tween interpolation context]
(phaser->clj
(.interpolation tween
(clj->phaser interpolation)
(clj->phaser context))))
([tween interpolation context index]
(phaser->clj
(.interpolation tween
(clj->phaser interpolation)
(clj->phaser context)
(clj->phaser index)))))
(defn loop
"Enables the looping of this tween and all child tweens. If this tween has no children this setting has no effect.
If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`.
If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero.
Usage:
game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true)
.to({ y: 300 }, 1000, Phaser.Easing.Linear.None)
.to({ x: 0 }, 1000, Phaser.Easing.Linear.None)
.to({ y: 0 }, 1000, Phaser.Easing.Linear.None)
.loop();
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* value (boolean) {optional} - If `true` this tween and any child tweens will loop once they reach the end. Set to `false` to remove an active loop.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween]
(phaser->clj
(.loop tween)))
([tween value]
(phaser->clj
(.loop tween
(clj->phaser value)))))
(defn on-update-callback
"Sets a callback to be fired each time this tween updates.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* callback (function) - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback.
* callback-context (object) - The context in which to call the onUpdate callback.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween callback callback-context]
(phaser->clj
(.onUpdateCallback tween
(clj->phaser callback)
(clj->phaser callback-context)))))
(defn pause
"Pauses the tween. Resume playback with Tween.resume."
([tween]
(phaser->clj
(.pause tween))))
(defn repeat
"Sets the number of times this tween will repeat.
If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat.
If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them.
If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* total (number) - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever.
* repeat (number) {optional} - This is the amount of time to pause (in ms) before the repeat will start.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween total]
(phaser->clj
(.repeat tween
(clj->phaser total))))
([tween total repeat]
(phaser->clj
(.repeat tween
(clj->phaser total)
(clj->phaser repeat))))
([tween total repeat index]
(phaser->clj
(.repeat tween
(clj->phaser total)
(clj->phaser repeat)
(clj->phaser index)))))
(defn repeat-all
"Set how many times this tween and all of its children will repeat.
A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing.
When all child tweens have completed Tween.onLoop will be dispatched.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* total (number) - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween total]
(phaser->clj
(.repeatAll tween
(clj->phaser total)))))
(defn repeat-delay
"Sets the delay in milliseconds before this tween will repeat itself.
The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on.
If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* duration (number) - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween duration]
(phaser->clj
(.repeatDelay tween
(clj->phaser duration))))
([tween duration index]
(phaser->clj
(.repeatDelay tween
(clj->phaser duration)
(clj->phaser index)))))
(defn resume
"Resumes a paused tween."
([tween]
(phaser->clj
(.resume tween))))
(defn start
"Starts the tween running. Can also be called by the autoStart parameter of `Tween.to` or `Tween.from`.
This sets the `Tween.isRunning` property to `true` and dispatches a `Tween.onStart` signal.
If the Tween has a delay set then nothing will start tweening until the delay has expired.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* index (number) {optional} - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween]
(phaser->clj
(.start tween)))
([tween index]
(phaser->clj
(.start tween
(clj->phaser index)))))
(defn stop
"Stops the tween if running and flags it for deletion from the TweenManager.
If called directly the `Tween.onComplete` signal is not dispatched and no chained tweens are started unless the complete parameter is set to `true`.
If you just wish to pause a tween then use Tween.pause instead.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* complete (boolean) {optional} - Set to `true` to dispatch the Tween.onComplete signal.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween]
(phaser->clj
(.stop tween)))
([tween complete]
(phaser->clj
(.stop tween
(clj->phaser complete)))))
(defn to
"Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given.
For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`.
The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as 'Circ'.
'.easeIn', '.easeOut' and 'easeInOut' variants are all supported for all ease types.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* properties (object) - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
* duration (number) {optional} - Duration of this tween in ms.
* ease (function | string) {optional} - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden.
* auto-start (boolean) {optional} - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start().
* delay (number) {optional} - Delay before this tween will start in milliseconds. Defaults to 0, no delay.
* repeat (number) {optional} - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this induvidual tween, not any chained tweens.
* yoyo (boolean) {optional} - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
Returns: Phaser.Tween - This Tween object."
([tween properties]
(phaser->clj
(.to tween
(clj->phaser properties))))
([tween properties duration]
(phaser->clj
(.to tween
(clj->phaser properties)
(clj->phaser duration))))
([tween properties duration ease]
(phaser->clj
(.to tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease))))
([tween properties duration ease auto-start]
(phaser->clj
(.to tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start))))
([tween properties duration ease auto-start delay]
(phaser->clj
(.to tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start)
(clj->phaser delay))))
([tween properties duration ease auto-start delay repeat]
(phaser->clj
(.to tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start)
(clj->phaser delay)
(clj->phaser repeat))))
([tween properties duration ease auto-start delay repeat yoyo]
(phaser->clj
(.to tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start)
(clj->phaser delay)
(clj->phaser repeat)
(clj->phaser yoyo)))))
(defn update
"Core tween update function called by the TweenManager. Does not need to be invoked directly.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* time (number) - A timestamp passed in by the TweenManager.
Returns: boolean - false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active)."
([tween time]
(phaser->clj
(.update tween
(clj->phaser time)))))
(defn update-tween-data
"Updates either a single TweenData or all TweenData objects properties to the given value.
Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak.
The property is not checked, so if you pass an invalid one you'll generate a run-time error.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* property (string) - The property to update.
* value (number | function) - The value to set the property to.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween property value]
(phaser->clj
(.updateTweenData tween
(clj->phaser property)
(clj->phaser value))))
([tween property value index]
(phaser->clj
(.updateTweenData tween
(clj->phaser property)
(clj->phaser value)
(clj->phaser index)))))
(defn yoyo
"A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start.
Used in combination with repeat you can create endless loops.
If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo.
If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them.
If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* enable (boolean) - Set to true to yoyo this tween, or false to disable an already active yoyo.
* yoyo-delay (number) {optional} - This is the amount of time to pause (in ms) before the yoyo will start.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween enable]
(phaser->clj
(.yoyo tween
(clj->phaser enable))))
([tween enable yoyo-delay]
(phaser->clj
(.yoyo tween
(clj->phaser enable)
(clj->phaser yoyo-delay))))
([tween enable yoyo-delay index]
(phaser->clj
(.yoyo tween
(clj->phaser enable)
(clj->phaser yoyo-delay)
(clj->phaser index)))))
(defn yoyo-delay
"Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled).
The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on.
If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* duration (number) - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween duration]
(phaser->clj
(.yoyoDelay tween
(clj->phaser duration))))
([tween duration index]
(phaser->clj
(.yoyoDelay tween
(clj->phaser duration)
(clj->phaser index)))))
| null |
https://raw.githubusercontent.com/dparis/gen-phzr/e4c7b272e225ac343718dc15fc84f5f0dce68023/out/tween.cljs
|
clojure
|
(ns phzr.tween
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [delay repeat loop update]))
(defn ->Tween
"A Tween allows you to alter one or more properties of a target object over a defined period of time.
This can be used for things such as alpha fading Sprites, scaling them or motion.
Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object
by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become 'child' tweens and
are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children.
Parameters:
* target (object) - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale.
* game (Phaser.Game) - Current game instance.
* manager (Phaser.TweenManager) - The TweenManager responsible for looking after this Tween."
([target game manager]
(js/Phaser.Tween. (clj->phaser target)
(clj->phaser game)
(clj->phaser manager))))
(defn chain
"This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called
as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress.
Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes.
For that you should listen to `onComplete` on the final tween in your chain.
If you pass multiple tweens to this method they will be joined into a single long chain.
For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C.
Any previously chained tweens that may have been set will be overwritten.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* tweens (Phaser.Tween) - One or more tweens that will be chained to this one.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween tweens]
(phaser->clj
(.chain tween
(clj->phaser tweens)))))
(defn delay
"Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts.
The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay.
If you have child tweens and pass -1 as the index value it sets the delay across all of them.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* duration (number) - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween duration]
(phaser->clj
(.delay tween
(clj->phaser duration))))
([tween duration index]
(phaser->clj
(.delay tween
(clj->phaser duration)
(clj->phaser index)))))
(defn easing
"Set easing function this tween will use, i.e. Phaser.Easing.Linear.None.
The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as 'Circ'.
'.easeIn', '.easeOut' and 'easeInOut' variants are all supported for all ease types.
If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* ease (function | string) - The easing function this tween will use, i.e. Phaser.Easing.Linear.None.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween ease]
(phaser->clj
(.easing tween
(clj->phaser ease))))
([tween ease index]
(phaser->clj
(.easing tween
(clj->phaser ease)
(clj->phaser index)))))
(defn from
"Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value.
For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`.
The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as 'Circ'.
'.easeIn', '.easeOut' and 'easeInOut' variants are all supported for all ease types.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* properties (object) - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
* duration (number) {optional} - Duration of this tween in ms.
* ease (function | string) {optional} - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden.
* auto-start (boolean) {optional} - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start().
* delay (number) {optional} - Delay before this tween will start in milliseconds. Defaults to 0, no delay.
* repeat (number) {optional} - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this induvidual tween, not any chained tweens.
* yoyo (boolean) {optional} - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
Returns: Phaser.Tween - This Tween object."
([tween properties]
(phaser->clj
(.from tween
(clj->phaser properties))))
([tween properties duration]
(phaser->clj
(.from tween
(clj->phaser properties)
(clj->phaser duration))))
([tween properties duration ease]
(phaser->clj
(.from tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease))))
([tween properties duration ease auto-start]
(phaser->clj
(.from tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start))))
([tween properties duration ease auto-start delay]
(phaser->clj
(.from tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start)
(clj->phaser delay))))
([tween properties duration ease auto-start delay repeat]
(phaser->clj
(.from tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start)
(clj->phaser delay)
(clj->phaser repeat))))
([tween properties duration ease auto-start delay repeat yoyo]
(phaser->clj
(.from tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start)
(clj->phaser delay)
(clj->phaser repeat)
(clj->phaser yoyo)))))
(defn generate-data
"This will generate an array populated with the tweened object values from start to end.
It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from.
It ignores delay and repeat counts and any chained tweens, but does include child tweens.
Just one play through of the tween data is returned, including yoyo if set.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* frame-rate (number) {optional} - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates.
* data (array) {optional} - If given the generated data will be appended to this array, otherwise a new array will be returned.
Returns: array - An array of tweened values."
([tween]
(phaser->clj
(.generateData tween)))
([tween frame-rate]
(phaser->clj
(.generateData tween
(clj->phaser frame-rate))))
([tween frame-rate data]
(phaser->clj
(.generateData tween
(clj->phaser frame-rate)
(clj->phaser data)))))
(defn interpolation
"Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation.
Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation.
The interpolation function is only used if the target properties is an array.
If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* interpolation (function) - The interpolation function to use (Phaser.Math.linearInterpolation by default)
* context (object) {optional} - The context under which the interpolation function will be run.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween interpolation]
(phaser->clj
(.interpolation tween
(clj->phaser interpolation))))
([tween interpolation context]
(phaser->clj
(.interpolation tween
(clj->phaser interpolation)
(clj->phaser context))))
([tween interpolation context index]
(phaser->clj
(.interpolation tween
(clj->phaser interpolation)
(clj->phaser context)
(clj->phaser index)))))
(defn loop
"Enables the looping of this tween and all child tweens. If this tween has no children this setting has no effect.
If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`.
If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero.
Usage:
game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true)
.to({ y: 300 }, 1000, Phaser.Easing.Linear.None)
.to({ x: 0 }, 1000, Phaser.Easing.Linear.None)
.to({ y: 0 }, 1000, Phaser.Easing.Linear.None)
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* value (boolean) {optional} - If `true` this tween and any child tweens will loop once they reach the end. Set to `false` to remove an active loop.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween]
(phaser->clj
(.loop tween)))
([tween value]
(phaser->clj
(.loop tween
(clj->phaser value)))))
(defn on-update-callback
"Sets a callback to be fired each time this tween updates.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* callback (function) - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback.
* callback-context (object) - The context in which to call the onUpdate callback.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween callback callback-context]
(phaser->clj
(.onUpdateCallback tween
(clj->phaser callback)
(clj->phaser callback-context)))))
(defn pause
"Pauses the tween. Resume playback with Tween.resume."
([tween]
(phaser->clj
(.pause tween))))
(defn repeat
"Sets the number of times this tween will repeat.
If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat.
If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them.
If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* total (number) - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever.
* repeat (number) {optional} - This is the amount of time to pause (in ms) before the repeat will start.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween total]
(phaser->clj
(.repeat tween
(clj->phaser total))))
([tween total repeat]
(phaser->clj
(.repeat tween
(clj->phaser total)
(clj->phaser repeat))))
([tween total repeat index]
(phaser->clj
(.repeat tween
(clj->phaser total)
(clj->phaser repeat)
(clj->phaser index)))))
(defn repeat-all
"Set how many times this tween and all of its children will repeat.
A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing.
When all child tweens have completed Tween.onLoop will be dispatched.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* total (number) - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween total]
(phaser->clj
(.repeatAll tween
(clj->phaser total)))))
(defn repeat-delay
"Sets the delay in milliseconds before this tween will repeat itself.
The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on.
If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* duration (number) - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween duration]
(phaser->clj
(.repeatDelay tween
(clj->phaser duration))))
([tween duration index]
(phaser->clj
(.repeatDelay tween
(clj->phaser duration)
(clj->phaser index)))))
(defn resume
"Resumes a paused tween."
([tween]
(phaser->clj
(.resume tween))))
(defn start
"Starts the tween running. Can also be called by the autoStart parameter of `Tween.to` or `Tween.from`.
This sets the `Tween.isRunning` property to `true` and dispatches a `Tween.onStart` signal.
If the Tween has a delay set then nothing will start tweening until the delay has expired.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* index (number) {optional} - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween]
(phaser->clj
(.start tween)))
([tween index]
(phaser->clj
(.start tween
(clj->phaser index)))))
(defn stop
"Stops the tween if running and flags it for deletion from the TweenManager.
If called directly the `Tween.onComplete` signal is not dispatched and no chained tweens are started unless the complete parameter is set to `true`.
If you just wish to pause a tween then use Tween.pause instead.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* complete (boolean) {optional} - Set to `true` to dispatch the Tween.onComplete signal.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween]
(phaser->clj
(.stop tween)))
([tween complete]
(phaser->clj
(.stop tween
(clj->phaser complete)))))
(defn to
"Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given.
For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`.
The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as 'Circ'.
'.easeIn', '.easeOut' and 'easeInOut' variants are all supported for all ease types.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* properties (object) - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
* duration (number) {optional} - Duration of this tween in ms.
* ease (function | string) {optional} - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden.
* auto-start (boolean) {optional} - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start().
* delay (number) {optional} - Delay before this tween will start in milliseconds. Defaults to 0, no delay.
* repeat (number) {optional} - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this induvidual tween, not any chained tweens.
* yoyo (boolean) {optional} - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
Returns: Phaser.Tween - This Tween object."
([tween properties]
(phaser->clj
(.to tween
(clj->phaser properties))))
([tween properties duration]
(phaser->clj
(.to tween
(clj->phaser properties)
(clj->phaser duration))))
([tween properties duration ease]
(phaser->clj
(.to tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease))))
([tween properties duration ease auto-start]
(phaser->clj
(.to tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start))))
([tween properties duration ease auto-start delay]
(phaser->clj
(.to tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start)
(clj->phaser delay))))
([tween properties duration ease auto-start delay repeat]
(phaser->clj
(.to tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start)
(clj->phaser delay)
(clj->phaser repeat))))
([tween properties duration ease auto-start delay repeat yoyo]
(phaser->clj
(.to tween
(clj->phaser properties)
(clj->phaser duration)
(clj->phaser ease)
(clj->phaser auto-start)
(clj->phaser delay)
(clj->phaser repeat)
(clj->phaser yoyo)))))
(defn update
"Core tween update function called by the TweenManager. Does not need to be invoked directly.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* time (number) - A timestamp passed in by the TweenManager.
Returns: boolean - false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active)."
([tween time]
(phaser->clj
(.update tween
(clj->phaser time)))))
(defn update-tween-data
"Updates either a single TweenData or all TweenData objects properties to the given value.
Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak.
The property is not checked, so if you pass an invalid one you'll generate a run-time error.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* property (string) - The property to update.
* value (number | function) - The value to set the property to.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween property value]
(phaser->clj
(.updateTweenData tween
(clj->phaser property)
(clj->phaser value))))
([tween property value index]
(phaser->clj
(.updateTweenData tween
(clj->phaser property)
(clj->phaser value)
(clj->phaser index)))))
(defn yoyo
"A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start.
Used in combination with repeat you can create endless loops.
If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo.
If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them.
If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* enable (boolean) - Set to true to yoyo this tween, or false to disable an already active yoyo.
* yoyo-delay (number) {optional} - This is the amount of time to pause (in ms) before the yoyo will start.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween enable]
(phaser->clj
(.yoyo tween
(clj->phaser enable))))
([tween enable yoyo-delay]
(phaser->clj
(.yoyo tween
(clj->phaser enable)
(clj->phaser yoyo-delay))))
([tween enable yoyo-delay index]
(phaser->clj
(.yoyo tween
(clj->phaser enable)
(clj->phaser yoyo-delay)
(clj->phaser index)))))
(defn yoyo-delay
"Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled).
The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on.
If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them.
Parameters:
* tween (Phaser.Tween) - Targeted instance for method
* duration (number) - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay.
* index (number) {optional} - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children.
Returns: Phaser.Tween - This tween. Useful for method chaining."
([tween duration]
(phaser->clj
(.yoyoDelay tween
(clj->phaser duration))))
([tween duration index]
(phaser->clj
(.yoyoDelay tween
(clj->phaser duration)
(clj->phaser index)))))
|
|
14c5e47e65651a6bba67ea9ad8278355aae5a20389fce60ae14dde46b2473c24
|
lspector/Clojush
|
report.clj
|
(ns clojush.pushgp.report
(:use [clojush util globals pushstate simplification individual]
[clojure.data.json :only (json-str)])
(:require [clojure.string :as string]
[config :as config]
[clj-random.core :as random]
[local-file]
[clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojush.pushgp.record :as r]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; helper functions
(defn default-problem-specific-initial-report
"Customize this for your own problem. It will be called at the beginning of the initial report."
[argmap]
:no-problem-specific-initial-report-function-defined)
(defn default-problem-specific-report
"Customize this for your own problem. It will be called at the beginning of the generational report."
[best population generation error-function report-simplifications]
:no-problem-specific-report-function-defined)
(defn git-last-commit-hash
"Returns the last Git commit hash"
[]
(let [dir (local-file/project-dir)]
(string/trim
(slurp
(str dir
"/.git/"
(subs
(string/trim
(slurp
(str dir "/.git/HEAD")))
5))))))
(defn print-params [push-argmap]
(doseq [[param val] push-argmap]
(println (name param) "="
(cond
(= param :random-seed) (random/seed-to-string val)
(= param :training-cases) (pr-str val)
:else val))))
(defn print-genome
[individual argmap]
(pr-str (not-lazy
(if (= :plush (:genome-representation argmap))
(map #(dissoc % :uuid :parent-uuid) (:genome individual))
(:genome individual)))))
(defn behavioral-diversity
"Returns the behavioral diversity of the population, as described by David
Jackson in 'Promoting phenotypic diversity in genetic programming'. It is
the percent of distinct behavior vectors in the population."
[population]
(float (/ (count (distinct (map :behaviors population)))
(count population))))
(defn sample-population-edit-distance
"Returns a sample of Levenshtein distances between programs in the population,
where each is divided by the length of the longer program."
[pop samples]
(let [instr-programs (map #(map :instruction %)
(map :genome pop))]
(repeatedly samples
#(let [prog1 (random/lrand-nth instr-programs)
prog2 (random/lrand-nth instr-programs)
longer-length (max (count prog1) (count prog2))]
(if (zero? longer-length)
0
(float (/ (levenshtein-distance prog1 prog2)
longer-length)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
log printing ( csv and )
(defn csv-print
"Prints a csv of the population, with each individual's fitness and size.
If log-fitnesses-for-all-cases is true, it also prints the value
of each fitness case."
[population generation {:keys [csv-log-filename csv-columns genome-representation]}]
(let [columns (vec
(map
(fn [col] (if (= col :genome-closes)
(if (= genome-representation :plush)
:plush-genome-closes
:plushy-genome-closes)
col))
(concat [:uuid]
(filter #(some #{%} csv-columns)
[:generation :location :parent-uuids :genetic-operators
:push-program-size :plush-genome-size :push-program
:plush-genome :total-error :is-random-replacement
:genome-closes :push-paren-locations]))))]
(when (zero? generation)
(with-open [csv-file (io/writer csv-log-filename :append false)]
(csv/write-csv csv-file
(vector (concat (map name columns)
(when (some #{:test-case-errors} csv-columns)
(map #(str "TC" %)
(range (count (:errors (first population)))))))))))
(with-open [csv-file (io/writer csv-log-filename :append true)]
(csv/write-csv
csv-file
(map-indexed
(fn [location individual]
(concat (map (assoc (into {} individual)
:generation generation
:location location
:parent-uuids (let [parent-uuids (not-lazy
(map str (:parent-uuids individual)))]
(if (empty? parent-uuids)
[]
parent-uuids))
:genetic-operators (if (nil? (:genetic-operators individual))
[]
(:genetic-operators individual))
:push-program-size (count-points (:program individual))
:push-program (if (and (seq? (:program individual))
(empty? (:program individual)))
"()"
(:program individual))
:plush-genome-size (count (:genome individual))
:plush-genome (if (empty? (:genome individual))
"()"
(not-lazy (:genome individual)))
:plush-genome-closes (if (empty? (:genome individual))
"()"
(apply str
(not-lazy
(map (fn [closes]
(if (<= closes 9)
closes
(str "<" closes ">")))
(map :close (:genome individual))))))
:plushy-genome-closes (if (empty? (:genome individual))
"()"
(apply str
(not-lazy (map (fn [instr]
(if (= instr :close)
1
0))
(:genome individual)))))
:push-paren-locations (if (empty? (:genome individual))
""
(apply str
(not-lazy
(map #(case %
:open "("
:close ")"
"-")
(list-to-open-close-sequence (:program individual))))))
) ; This is a map of an individual
columns)
(when (some #{:test-case-errors} csv-columns)
(:errors individual))))
population)))))
(defn edn-print
"Takes a population and appends all the individuals to the EDN log file.
If the internal representation of individuals changes in future versions
of Clojush, this code will likely continue to work, but will produce
output corresponding to the new representation."
[population generation edn-log-filename keys additional-keys]
Opens and closes the file once per call
(doall
(map-indexed (fn [index individual]
(let [additional-data {:generation generation
:location index
:push-program-size (count-points (:program individual))
:plush-genome-size (count (:genome individual))}]
(.write w "#clojush/individual")
(.write w (prn-str (merge
(select-keys additional-data additional-keys)
(select-keys individual keys))))))
population))))
(defn jsonize-individual
"Takes an individual and returns it with only the items of interest
for the json logs."
[log-fitnesses-for-all-cases json-log-program-strings generation individual]
(let [part1-ind (-> (if log-fitnesses-for-all-cases
{:errors (:errors individual)}
{})
(assoc :total-error (:total-error individual))
(assoc :generation generation)
(assoc :size (count-points (:program individual))))
part2-ind (if json-log-program-strings
(assoc part1-ind :program (str (not-lazy (:program individual))))
part1-ind)
part3-ind (if (:weighted-error individual)
(assoc part2-ind :weighted-error (:weighted-error individual))
part2-ind)]
part3-ind))
(defn json-print
"Prints a json file of the population, with each individual's fitness and size.
If log-fitnesses-for-all-cases is true, it also prints the value
of each fitness case."
[population generation json-log-filename log-fitnesses-for-all-cases
json-log-program-strings]
(let [pop-json-string (json-str (map #(jsonize-individual
log-fitnesses-for-all-cases
json-log-program-strings
generation
%)
population))]
(if (zero? generation)
(spit json-log-filename (str pop-json-string "\n") :append false)
(spit json-log-filename (str "," pop-json-string "\n") :append true))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; report printing functions
(defn lexicase-report
"This extra report is printed whenever lexicase selection is used."
[population {:keys [error-function report-simplifications print-errors
print-history meta-error-categories
print-lexicase-best-programs] :as argmap}]
(let [min-error-by-case (apply map
(fn [& args] (apply min args))
(map :errors population))
lex-best (apply max-key
(fn [ind]
(apply + (map #(if (== %1 %2) 1 0)
(:errors ind)
min-error-by-case)))
population)
pop-elite-by-case (map (fn [ind]
(map #(if (== %1 %2) 1 0)
(:errors ind)
min-error-by-case))
population)
count-elites-by-case (map #(apply + %) (apply mapv vector pop-elite-by-case))
most-zero-cases-best (apply max-key
(fn [ind]
(apply + (map #(if (zero? %) 1 0)
(:errors ind))))
population)
pop-zero-by-case (map (fn [ind]
(map #(if (zero? %) 1 0)
(:errors ind)))
population)
count-zero-by-case (map #(apply + %) (apply mapv vector pop-zero-by-case))]
(when print-lexicase-best-programs
(println "--- Lexicase Program with Most Elite Cases Statistics ---")
(println "Lexicase best genome:" (print-genome lex-best argmap))
(println "Lexicase best program:" (pr-str (not-lazy (:program lex-best))))
(when (> report-simplifications 0)
(println "Lexicase best partial simplification:"
(pr-str (not-lazy (:program (auto-simplify lex-best
error-function
report-simplifications
false
1000
argmap))))))
(when print-errors (println "Lexicase best errors:" (not-lazy (:errors lex-best))))
(when (and print-errors (not (empty? meta-error-categories)))
(println "Lexicase best meta-errors:" (not-lazy (:meta-errors lex-best))))
(println "Lexicase best number of elite cases:" (apply + (map #(if (== %1 %2) 1 0)
(:errors lex-best)
min-error-by-case)))
(println "Lexicase best total error:" (:total-error lex-best))
(println "Lexicase best mean error:" (float (/ (:total-error lex-best)
(count (:errors lex-best)))))
(when print-history (println "Lexicase best history:" (not-lazy (:history lex-best))))
(println "Lexicase best size:" (count-points (:program lex-best)))
(printf "Percent parens: %.3f\n"
(double (/ (count-parens (:program lex-best))
(count-points (:program lex-best))))) ;Number of (open) parens / points
(println "--- Lexicase Program with Most Zero Cases Statistics ---")
(println "Zero cases best genome:" (print-genome most-zero-cases-best argmap))
(println "Zero cases best program:" (pr-str (not-lazy (:program most-zero-cases-best))))
(when (> report-simplifications 0)
(println "Zero cases best partial simplification:"
(pr-str (not-lazy (:program (auto-simplify most-zero-cases-best
error-function
report-simplifications
false
1000
argmap))))))
(when print-errors (println "Zero cases best errors:" (not-lazy (:errors most-zero-cases-best))))
(when (and print-errors (not (empty? meta-error-categories)))
(println "Zero cases best meta-errors:" (not-lazy (:meta-errors most-zero-cases-best))))
(println "Zero cases best number of elite cases:"
(apply + (map #(if (== %1 %2) 1 0)
(:errors most-zero-cases-best)
min-error-by-case)))
(println "Zero cases best number of zero cases:"
(apply + (map #(if (< %1 min-number-magnitude) 1 0)
(:errors most-zero-cases-best))))
(println "Zero cases best total error:" (:total-error most-zero-cases-best))
(println "Zero cases best mean error:"
(float (/ (:total-error most-zero-cases-best)
(count (:errors most-zero-cases-best)))))
(when print-history (println "Zero cases best history:"
(not-lazy (:history most-zero-cases-best))))
(println "Zero cases best size:" (count-points (:program most-zero-cases-best)))
(printf "Percent parens: %.3f\n"
(double (/ (count-parens (:program most-zero-cases-best))
(count-points (:program most-zero-cases-best))))) ;Number of (open) parens / points
)
(println "--- Lexicase Population Statistics ---")
(println "Count of elite individuals by case:" count-elites-by-case)
(println (format "Population mean number of elite cases: %.2f"
(float (/ (apply + count-elites-by-case) (count population)))))
(println "Count of perfect (error zero) individuals by case:" count-zero-by-case)
(println (format "Population mean number of perfect (error zero) cases: %.2f"
(float (/ (apply + count-zero-by-case) (count population)))))))
(defn implicit-fitness-sharing-report
"This extra report is printed whenever implicit fitness sharing selection is used."
[population {:keys [print-errors meta-error-categories] :as argmap}]
(let [ifs-best (apply min-key :weighted-error population)]
(println "--- Program with Best Implicit Fitness Sharing Error Statistics ---")
(println "IFS best genome:" (print-genome ifs-best argmap))
(println "IFS best program:" (pr-str (not-lazy (:program ifs-best))))
(when print-errors (println "IFS best errors:" (not-lazy (:errors ifs-best))))
(when (and print-errors (not (empty? meta-error-categories)))
(println "IFS best meta-errors:" (not-lazy (:meta-errors ifs-best))))
(println "IFS best total error:" (:total-error ifs-best))
(println "IFS best mean error:" (float (/ (:total-error ifs-best)
(count (:errors ifs-best)))))
(println "IFS best IFS error:" (:weighted-error ifs-best))
(println "IFS best size:" (count-points (:program ifs-best)))
(printf "IFS best percent parens: %.3f\n"
(double (/ (count-parens (:program ifs-best))
(count-points (:program ifs-best))))))) ;Number of (open) parens / points
(defn report-and-check-for-success
"Reports on the specified generation of a pushgp run. Returns the best
individual of the generation."
[population generation
{:keys [error-function report-simplifications meta-error-categories
error-threshold max-generations population-size
print-errors print-history print-cosmos-data print-timings
problem-specific-report total-error-method
parent-selection print-homology-data max-point-evaluations
max-program-executions use-ALPS
print-error-frequencies-by-case normalization autoconstructive
print-selection-counts print-preselection-fraction exit-on-success
;; The following are for CSV or JSON logs
print-csv-logs print-json-logs csv-log-filename json-log-filename
log-fitnesses-for-all-cases json-log-program-strings
print-edn-logs edn-keys edn-log-filename edn-additional-keys
visualize calculate-mod-metrics]
:as argmap}]
(r/generation-data! [:population]
(map #(dissoc % :program) population))
(println)
(println ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;")
(println ";; -*- Report at generation" generation)
(let [point-evaluations-before-report @point-evaluations-count
program-executions-before-report @program-executions-count
err-fn (if (= total-error-method :rmse) :weighted-error :total-error)
sorted (sort-by err-fn < population)
err-fn-best (if (not= parent-selection :downsampled-lexicase)
(first sorted)
; This tests each individual that passes current generation's subsampled training
; cases on all training cases, and only treats it as winner if it
passes all of those as well . Otherwise , just returns first individual
; if none pass all subsampled cases, or random individual that passes
; all subsampled cases but not all training cases.
(error-function
(loop [sorted-individuals sorted]
(if (empty? (rest sorted-individuals))
(first sorted-individuals)
(if (and (<= (:total-error (first sorted-individuals)) error-threshold)
(> (apply + (:errors (error-function (first sorted-individuals) :train))) error-threshold)
(<= (:total-error (second sorted-individuals)) error-threshold))
(recur (rest sorted-individuals))
(first sorted-individuals))))
:train))
total-error-best (if (not= parent-selection :downsampled-lexicase)
err-fn-best
(assoc err-fn-best
:total-error
(apply +' (:errors err-fn-best))))
psr-best (problem-specific-report total-error-best
population
generation
error-function
report-simplifications)
best (if (= (type psr-best) clojush.individual.individual)
psr-best
total-error-best)
standard-deviation (fn [nums]
(if (<= (count nums) 1)
(str "Cannot find standard deviation of "
(count nums)
"numbers. Must have at least 2.")
(let [mean (mean nums)]
(Math/sqrt (/ (apply +' (map #(* (- % mean) (- % mean))
nums))
(dec (count nums)))))))
quartiles (fn [nums]
(if (zero? (count nums))
"Cannot find quartiles of zero numbers."
(let [sorted (sort nums)]
(vector (nth sorted
(truncate (/ (count nums) 4)))
(nth sorted
(truncate (/ (count nums) 2)))
(nth sorted
(truncate (/ (* 3 (count nums)) 4)))))))]
(when print-error-frequencies-by-case
(println "Error frequencies by case:"
(doall (map frequencies (apply map vector (map :errors population))))))
(when (some #{parent-selection}
#{:lexicase :elitegroup-lexicase :leaky-lexicase :epsilon-lexicase
:random-threshold-lexicase :random-toggle-lexicase
:randomly-truncated-lexicase})
(lexicase-report population argmap))
(when (= total-error-method :ifs) (implicit-fitness-sharing-report population argmap))
(println (format "--- Best Program (%s) Statistics ---" (str "based on " (name err-fn))))
(r/generation-data! [:best :individual] (dissoc best :program))
(println "Best genome:" (print-genome best argmap))
(println "Best program:" (pr-str (not-lazy (:program best))))
(when calculate-mod-metrics
(println "Reuse in Best Program:" (pr-str (:reuse-info best)))
(println "Repetition in Best Program:" (pr-str (:repetition-info best))))
(when (> report-simplifications 0)
(let [simplified (not-lazy (:program (r/generation-data! [:best :individual-simplified]
(auto-simplify best
error-function
report-simplifications
false
1000
argmap))))]
(println "Partial simplification:" (pr-str simplified))
(println "Partial simplified size:" (count-points simplified))))
(when print-errors (println "Errors:" (not-lazy (:errors best))))
(when (and print-errors (not (empty? meta-error-categories)))
(println "Meta-Errors:" (not-lazy (:meta-errors best))))
(println "Total:" (:total-error best))
(let [mean (r/generation-data! [:best :mean-error] (float (/ (:total-error best)
(count (:errors best)))))]
(println "Mean:" mean))
(when (not= normalization :none)
(println "Normalized error:" (:normalized-error best)))
(case total-error-method
:hah (println "HAH-error:" (:weighted-error best))
:rmse (println "RMS-error:" (:weighted-error best))
:ifs (println "IFS-error:" (:weighted-error best))
nil)
(when (= parent-selection :novelty-search)
(println "Novelty: " (float (:novelty best))))
(when print-history (println "History:" (not-lazy (:history best))))
(println "Genome size:" (r/generation-data! [:best :genome-size] (count (:genome best))))
(println "Size:" (r/generation-data! [:best :program-size] (count-points (:program best))))
(printf "Percent parens: %.3f\n"
(r/generation-data! [:best :percent-parens]
(double (/ (count-parens (:program best))
(count-points (:program best)))))) ;Number of (open) parens / points
(println "Age:" (:age best))
(println "--- Population Statistics ---")
(when print-cosmos-data
(println "Cosmos Data:" (let [quants (config/quantiles (count population))]
(zipmap quants
(map #(:total-error (nth (sort-by :total-error population) %))
quants)))))
(println "Average total errors in population:"
(r/generation-data! [:population-report :mean-total-error]
(*' 1.0 (mean (map :total-error sorted)))))
(println "Median total errors in population:"
(r/generation-data! [:population-report :median-total-error]
(median (map :total-error sorted))))
(when print-errors (println "Error averages by case:"
(apply map (fn [& args] (*' 1.0 (mean args)))
(map :errors population))))
(when print-errors (println "Error minima by case:"
(apply map (fn [& args] (apply min args))
(map :errors population))))
(when (and print-errors (not (empty? meta-error-categories)))
(println "Meta-Error averages by category:"
(apply map (fn [& args] (*' 1.0 (mean args)))
(map :meta-errors population)))
(println "Meta-Error minima by category:"
(apply map (fn [& args] (apply min args))
(map :meta-errors population))))
(println "Average genome size in population (length):"
(r/generation-data! [:population-report :mean-genome-size]
(*' 1.0 (mean (map count (map :genome sorted))))))
(println "Average program size in population (points):"
(r/generation-data! [:population-report :mean-program-size]
(*' 1.0 (mean (map count-points (map :program sorted))))))
(printf "Average percent parens in population: %.3f\n"
(r/generation-data! [:population-report :mean-program-percent-params]
(mean (map #(double (/ (count-parens (:program %)) (count-points (:program %)))) sorted))))
(let [ages (map :age population)]
(when use-ALPS
(println "Population ages:" ages))
(println "Minimum age in population:"
(r/generation-data! [:population-report :min-age]
(* 1.0 (apply min ages))))
(println "Maximum age in population:"
(r/generation-data! [:population-report :max-age]
(* 1.0 (apply max ages))))
(println "Average age in population:"
(r/generation-data! [:population-report :mean-age]
(* 1.0 (mean ages))))
(println "Median age in population:"
(r/generation-data! [:population-report :median-age]
(* 1.0 (median ages)))))
(let [grain-sizes (map :grain-size population)]
(println "Minimum grain-size in population:"
(r/generation-data! [:population-report :min-grain-size]
(* 1.0 (apply min grain-sizes))))
(println "Maximum grain-size in population:"
(r/generation-data! [:population-report :max-grain-size]
(* 1.0 (apply max grain-sizes))))
(println "Average grain-size in population:"
(r/generation-data! [:population-report :mean-grain-size]
(* 1.0 (mean grain-sizes))))
(println "Median grain-size in population:"
(r/generation-data! [:population-report :median-grain-size]
(* 1.0 (median grain-sizes)))))
(println "--- Population Diversity Statistics ---")
(let [genome-frequency-map (frequencies (map :genome population))]
(println "Min copy number of one genome:"
(r/generation-data! [:population-report :min-genome-frequency]
(apply min (vals genome-frequency-map))))
(println "Median copy number of one genome:"
(r/generation-data! [:population-report :median-genome-frequency]
(median (vals genome-frequency-map))))
(println "Max copy number of one genome:"
(r/generation-data! [:population-report :max-genome-frequency]
(apply max (vals genome-frequency-map))))
(println "Genome diversity (% unique genomes):\t"
(r/generation-data! [:population-report :percent-genomes-unique]
(float (/ (count genome-frequency-map) (count population))))))
(let [frequency-map (frequencies (map :program population))]
(println "Min copy number of one Push program:"
(r/generation-data! [:population-report :min-program-frequency]
(apply min (vals frequency-map))))
(println "Median copy number of one Push program:"
(r/generation-data! [:population-report :median-program-frequency]
(median (vals frequency-map))))
(println "Max copy number of one Push program:"
(r/generation-data! [:population-report :max-program-frequency]
(apply max (vals frequency-map))))
(println "Syntactic diversity (% unique Push programs):\t"
(r/generation-data! [:population-report :percent-programs-unique]
(float (/ (count frequency-map) (count population))))))
(println "Total error diversity:\t\t\t\t"
(r/generation-data! [:population-report :percent-total-error-unique]
(float (/ (count (distinct (map :total-error population))) (count population)))))
(println "Error (vector) diversity:\t\t\t"
(r/generation-data! [:population-report :percent-errors-unique]
(float (/ (count (distinct (map :errors population))) (count population)))))
(when (not (nil? (:behaviors (first population))))
(println "Behavioral diversity:\t\t\t\t" (behavioral-diversity population)))
(when print-homology-data
(let [num-samples 1000
sample-1 (sample-population-edit-distance population num-samples)
[first-quart-1 median-1 third-quart-1] (quartiles sample-1)]
(println "--- Population Homology Statistics (all stats reference the sampled population edit distance of programs) ---")
(println "Number of homology samples:" num-samples)
(println "Average: " (mean sample-1))
(println "Standard deviation: " (standard-deviation sample-1))
(println "First quartile: " first-quart-1)
(println "Median: " median-1)
(println "Third quartile: " third-quart-1)))
(when print-selection-counts
(println "Selection counts:"
(sort > (concat (vals @selection-counts)
(repeat (- population-size (count @selection-counts)) 0))))
(reset! selection-counts {}))
(when (and print-preselection-fraction
(not (empty? @preselection-counts)))
(println "Preselection fraction:" (float (/ (/ (reduce + @preselection-counts) population-size)
(count @preselection-counts))))
(reset! preselection-counts []))
(when autoconstructive
(println "Number of random replacements for non-diversifying individuals:"
(r/generation-data! [:population-report :number-random-replacements]
(count (filter :is-random-replacement population)))))
(println "--- Run Statistics ---")
(println "Number of individuals evaluated (running on all training cases counts as 1 evaluation):" @evaluations-count)
(println "Number of program executions (running on a single case counts as 1 execution):" program-executions-before-report)
(println "Number of point (instruction) evaluations so far:" point-evaluations-before-report)
(reset! point-evaluations-count point-evaluations-before-report)
(reset! program-executions-count program-executions-before-report)
(println "--- Timings ---")
(println "Current time:" (System/currentTimeMillis) "milliseconds")
(when print-timings
(let [total-time (apply + (vals @timing-map))
init (get @timing-map :initialization)
reproduction (get @timing-map :reproduction)
fitness (get @timing-map :fitness)
report-time (get @timing-map :report)
other (get @timing-map :other)]
(printf "Total Time: %8.1f seconds\n"
(/ total-time 1000.0))
(printf "Initialization: %8.1f seconds, %4.1f%%\n"
(/ init 1000.0) (* 100.0 (/ init total-time)))
(printf "Reproduction: %8.1f seconds, %4.1f%%\n"
(/ reproduction 1000.0) (* 100.0 (/ reproduction total-time)))
(printf "Fitness Testing: %8.1f seconds, %4.1f%%\n"
(/ fitness 1000.0) (* 100.0 (/ fitness total-time)))
(printf "Report: %8.1f seconds, %4.1f%%\n"
(/ report-time 1000.0) (* 100.0 (/ report-time total-time)))
(printf "Other: %8.1f seconds, %4.1f%%\n"
(/ other 1000.0) (* 100.0 (/ other total-time)))))
(println ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;")
(println ";; -*- End of report for generation" generation)
(println ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;")
(flush)
(when print-csv-logs (csv-print population generation argmap))
(when print-json-logs (json-print population generation json-log-filename
log-fitnesses-for-all-cases json-log-program-strings))
(when print-edn-logs
(edn-print population generation edn-log-filename edn-keys edn-additional-keys))
;; Visualization -- update viz-data-atom here
(when visualize
(swap! viz-data-atom update-in [:history-of-errors-of-best] conj (:errors best))
(swap! viz-data-atom assoc :generation generation))
(cond
; Succeed
(and exit-on-success
(or (<= (:total-error best) error-threshold)
(:success best)))
[:success best]
; Fail max generations
(>= generation max-generations)
[:failure best]
; Fail max program executions
(>= @program-executions-count max-program-executions)
[:failure best]
; Fail max point evaluations
(>= @point-evaluations-count max-point-evaluations)
[:failure best]
; Continue
:else
[:continue best])))
(defn remove-function-values [argmap]
(into {} (filter (fn [[k v]] (not (fn? v)))
(dissoc argmap :random-seed :atom-generators))))
(defn initial-report
"Prints the initial report of a PushGP run."
[{:keys [problem-specific-initial-report] :as push-argmap}]
(problem-specific-initial-report push-argmap)
(println "Registered instructions:"
(r/config-data! [:registered-instructions] @registered-instructions))
(println "Starting PushGP run.")
(printf "Clojush version = ")
(try
(let [version-str (apply str (butlast (re-find #"\".*\""
(first (string/split-lines
(local-file/slurp* "project.clj"))))))
version-number (.substring version-str 1 (count version-str))]
(if (empty? version-number)
(throw Exception)
(printf (str (r/config-data! [:version-number] version-number)) "\n")))
(flush)
(catch Exception e
(printf "version number unavailable\n")
(flush)))
(try
(let [git-hash (git-last-commit-hash)]
(if (empty? git-hash)
(throw Exception)
(do
;; NOTES: - Last commit hash will only be correct if this code has
;; been committed already.
;; - GitHub link will only work if commit has been pushed
to GitHub .
(r/config-data! [:git-hash] git-hash)
(printf (str "Hash of last Git commit = " git-hash "\n"))
(printf (str "GitHub link = /"
git-hash
"\n"))
(flush))))
(catch Exception e
(printf "Hash of last Git commit = unavailable\n")
(printf "GitHub link = unavailable\n")
(flush)))
(if (:print-edn-logs push-argmap)
;; The edn log is overwritten if it exists
(with-open [w (io/writer (:edn-log-filename push-argmap) :append false)]
(.write w "#clojush/run")
(.write w (prn-str (remove-function-values push-argmap)))))
(when (:visualize push-argmap) ;; Visualization
Require conditionally ( dynamically ) , avoiding unintended Quil sketch launch
(require 'clojush.pushgp.visualize)))
(defn final-report
"Prints the final report of a PushGP run if the run is successful."
[generation best
{:keys [error-function final-report-simplifications report-simplifications
print-ancestors-of-solution problem-specific-report] :as argmap}]
(printf "\n\nSUCCESS at generation %s\nSuccessful program: %s\nErrors: %s\nTotal error: %s\nHistory: %s\nSize: %s\n\n"
generation (pr-str (not-lazy (:program best))) (not-lazy (:errors best)) (:total-error best)
(not-lazy (:history best)) (count-points (:program best)))
(when print-ancestors-of-solution
(printf "\nAncestors of solution:\n")
(prn (:ancestors best)))
(let [simplified-best (auto-simplify best error-function final-report-simplifications true 500 argmap)]
(println "\n;;******************************")
(println ";; Problem-Specific Report of Simplified Solution")
(println "Reuse in Simplified Solution:" (:reuse-info (error-function simplified-best)))
(problem-specific-report simplified-best [] generation error-function report-simplifications)))
| null |
https://raw.githubusercontent.com/lspector/Clojush/8f8c6dcb181e675a3f514e6c9e9fc92cf76ac566/src/clojush/pushgp/report.clj
|
clojure
|
helper functions
This is a map of an individual
report printing functions
Number of (open) parens / points
Number of (open) parens / points
Number of (open) parens / points
The following are for CSV or JSON logs
This tests each individual that passes current generation's subsampled training
cases on all training cases, and only treats it as winner if it
if none pass all subsampled cases, or random individual that passes
all subsampled cases but not all training cases.
Number of (open) parens / points
Visualization -- update viz-data-atom here
Succeed
Fail max generations
Fail max program executions
Fail max point evaluations
Continue
NOTES: - Last commit hash will only be correct if this code has
been committed already.
- GitHub link will only work if commit has been pushed
The edn log is overwritten if it exists
Visualization
|
(ns clojush.pushgp.report
(:use [clojush util globals pushstate simplification individual]
[clojure.data.json :only (json-str)])
(:require [clojure.string :as string]
[config :as config]
[clj-random.core :as random]
[local-file]
[clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojush.pushgp.record :as r]))
(defn default-problem-specific-initial-report
"Customize this for your own problem. It will be called at the beginning of the initial report."
[argmap]
:no-problem-specific-initial-report-function-defined)
(defn default-problem-specific-report
"Customize this for your own problem. It will be called at the beginning of the generational report."
[best population generation error-function report-simplifications]
:no-problem-specific-report-function-defined)
(defn git-last-commit-hash
"Returns the last Git commit hash"
[]
(let [dir (local-file/project-dir)]
(string/trim
(slurp
(str dir
"/.git/"
(subs
(string/trim
(slurp
(str dir "/.git/HEAD")))
5))))))
(defn print-params [push-argmap]
(doseq [[param val] push-argmap]
(println (name param) "="
(cond
(= param :random-seed) (random/seed-to-string val)
(= param :training-cases) (pr-str val)
:else val))))
(defn print-genome
[individual argmap]
(pr-str (not-lazy
(if (= :plush (:genome-representation argmap))
(map #(dissoc % :uuid :parent-uuid) (:genome individual))
(:genome individual)))))
(defn behavioral-diversity
"Returns the behavioral diversity of the population, as described by David
Jackson in 'Promoting phenotypic diversity in genetic programming'. It is
the percent of distinct behavior vectors in the population."
[population]
(float (/ (count (distinct (map :behaviors population)))
(count population))))
(defn sample-population-edit-distance
"Returns a sample of Levenshtein distances between programs in the population,
where each is divided by the length of the longer program."
[pop samples]
(let [instr-programs (map #(map :instruction %)
(map :genome pop))]
(repeatedly samples
#(let [prog1 (random/lrand-nth instr-programs)
prog2 (random/lrand-nth instr-programs)
longer-length (max (count prog1) (count prog2))]
(if (zero? longer-length)
0
(float (/ (levenshtein-distance prog1 prog2)
longer-length)))))))
log printing ( csv and )
(defn csv-print
"Prints a csv of the population, with each individual's fitness and size.
If log-fitnesses-for-all-cases is true, it also prints the value
of each fitness case."
[population generation {:keys [csv-log-filename csv-columns genome-representation]}]
(let [columns (vec
(map
(fn [col] (if (= col :genome-closes)
(if (= genome-representation :plush)
:plush-genome-closes
:plushy-genome-closes)
col))
(concat [:uuid]
(filter #(some #{%} csv-columns)
[:generation :location :parent-uuids :genetic-operators
:push-program-size :plush-genome-size :push-program
:plush-genome :total-error :is-random-replacement
:genome-closes :push-paren-locations]))))]
(when (zero? generation)
(with-open [csv-file (io/writer csv-log-filename :append false)]
(csv/write-csv csv-file
(vector (concat (map name columns)
(when (some #{:test-case-errors} csv-columns)
(map #(str "TC" %)
(range (count (:errors (first population)))))))))))
(with-open [csv-file (io/writer csv-log-filename :append true)]
(csv/write-csv
csv-file
(map-indexed
(fn [location individual]
(concat (map (assoc (into {} individual)
:generation generation
:location location
:parent-uuids (let [parent-uuids (not-lazy
(map str (:parent-uuids individual)))]
(if (empty? parent-uuids)
[]
parent-uuids))
:genetic-operators (if (nil? (:genetic-operators individual))
[]
(:genetic-operators individual))
:push-program-size (count-points (:program individual))
:push-program (if (and (seq? (:program individual))
(empty? (:program individual)))
"()"
(:program individual))
:plush-genome-size (count (:genome individual))
:plush-genome (if (empty? (:genome individual))
"()"
(not-lazy (:genome individual)))
:plush-genome-closes (if (empty? (:genome individual))
"()"
(apply str
(not-lazy
(map (fn [closes]
(if (<= closes 9)
closes
(str "<" closes ">")))
(map :close (:genome individual))))))
:plushy-genome-closes (if (empty? (:genome individual))
"()"
(apply str
(not-lazy (map (fn [instr]
(if (= instr :close)
1
0))
(:genome individual)))))
:push-paren-locations (if (empty? (:genome individual))
""
(apply str
(not-lazy
(map #(case %
:open "("
:close ")"
"-")
(list-to-open-close-sequence (:program individual))))))
columns)
(when (some #{:test-case-errors} csv-columns)
(:errors individual))))
population)))))
(defn edn-print
"Takes a population and appends all the individuals to the EDN log file.
If the internal representation of individuals changes in future versions
of Clojush, this code will likely continue to work, but will produce
output corresponding to the new representation."
[population generation edn-log-filename keys additional-keys]
Opens and closes the file once per call
(doall
(map-indexed (fn [index individual]
(let [additional-data {:generation generation
:location index
:push-program-size (count-points (:program individual))
:plush-genome-size (count (:genome individual))}]
(.write w "#clojush/individual")
(.write w (prn-str (merge
(select-keys additional-data additional-keys)
(select-keys individual keys))))))
population))))
(defn jsonize-individual
"Takes an individual and returns it with only the items of interest
for the json logs."
[log-fitnesses-for-all-cases json-log-program-strings generation individual]
(let [part1-ind (-> (if log-fitnesses-for-all-cases
{:errors (:errors individual)}
{})
(assoc :total-error (:total-error individual))
(assoc :generation generation)
(assoc :size (count-points (:program individual))))
part2-ind (if json-log-program-strings
(assoc part1-ind :program (str (not-lazy (:program individual))))
part1-ind)
part3-ind (if (:weighted-error individual)
(assoc part2-ind :weighted-error (:weighted-error individual))
part2-ind)]
part3-ind))
(defn json-print
"Prints a json file of the population, with each individual's fitness and size.
If log-fitnesses-for-all-cases is true, it also prints the value
of each fitness case."
[population generation json-log-filename log-fitnesses-for-all-cases
json-log-program-strings]
(let [pop-json-string (json-str (map #(jsonize-individual
log-fitnesses-for-all-cases
json-log-program-strings
generation
%)
population))]
(if (zero? generation)
(spit json-log-filename (str pop-json-string "\n") :append false)
(spit json-log-filename (str "," pop-json-string "\n") :append true))))
(defn lexicase-report
"This extra report is printed whenever lexicase selection is used."
[population {:keys [error-function report-simplifications print-errors
print-history meta-error-categories
print-lexicase-best-programs] :as argmap}]
(let [min-error-by-case (apply map
(fn [& args] (apply min args))
(map :errors population))
lex-best (apply max-key
(fn [ind]
(apply + (map #(if (== %1 %2) 1 0)
(:errors ind)
min-error-by-case)))
population)
pop-elite-by-case (map (fn [ind]
(map #(if (== %1 %2) 1 0)
(:errors ind)
min-error-by-case))
population)
count-elites-by-case (map #(apply + %) (apply mapv vector pop-elite-by-case))
most-zero-cases-best (apply max-key
(fn [ind]
(apply + (map #(if (zero? %) 1 0)
(:errors ind))))
population)
pop-zero-by-case (map (fn [ind]
(map #(if (zero? %) 1 0)
(:errors ind)))
population)
count-zero-by-case (map #(apply + %) (apply mapv vector pop-zero-by-case))]
(when print-lexicase-best-programs
(println "--- Lexicase Program with Most Elite Cases Statistics ---")
(println "Lexicase best genome:" (print-genome lex-best argmap))
(println "Lexicase best program:" (pr-str (not-lazy (:program lex-best))))
(when (> report-simplifications 0)
(println "Lexicase best partial simplification:"
(pr-str (not-lazy (:program (auto-simplify lex-best
error-function
report-simplifications
false
1000
argmap))))))
(when print-errors (println "Lexicase best errors:" (not-lazy (:errors lex-best))))
(when (and print-errors (not (empty? meta-error-categories)))
(println "Lexicase best meta-errors:" (not-lazy (:meta-errors lex-best))))
(println "Lexicase best number of elite cases:" (apply + (map #(if (== %1 %2) 1 0)
(:errors lex-best)
min-error-by-case)))
(println "Lexicase best total error:" (:total-error lex-best))
(println "Lexicase best mean error:" (float (/ (:total-error lex-best)
(count (:errors lex-best)))))
(when print-history (println "Lexicase best history:" (not-lazy (:history lex-best))))
(println "Lexicase best size:" (count-points (:program lex-best)))
(printf "Percent parens: %.3f\n"
(double (/ (count-parens (:program lex-best))
(println "--- Lexicase Program with Most Zero Cases Statistics ---")
(println "Zero cases best genome:" (print-genome most-zero-cases-best argmap))
(println "Zero cases best program:" (pr-str (not-lazy (:program most-zero-cases-best))))
(when (> report-simplifications 0)
(println "Zero cases best partial simplification:"
(pr-str (not-lazy (:program (auto-simplify most-zero-cases-best
error-function
report-simplifications
false
1000
argmap))))))
(when print-errors (println "Zero cases best errors:" (not-lazy (:errors most-zero-cases-best))))
(when (and print-errors (not (empty? meta-error-categories)))
(println "Zero cases best meta-errors:" (not-lazy (:meta-errors most-zero-cases-best))))
(println "Zero cases best number of elite cases:"
(apply + (map #(if (== %1 %2) 1 0)
(:errors most-zero-cases-best)
min-error-by-case)))
(println "Zero cases best number of zero cases:"
(apply + (map #(if (< %1 min-number-magnitude) 1 0)
(:errors most-zero-cases-best))))
(println "Zero cases best total error:" (:total-error most-zero-cases-best))
(println "Zero cases best mean error:"
(float (/ (:total-error most-zero-cases-best)
(count (:errors most-zero-cases-best)))))
(when print-history (println "Zero cases best history:"
(not-lazy (:history most-zero-cases-best))))
(println "Zero cases best size:" (count-points (:program most-zero-cases-best)))
(printf "Percent parens: %.3f\n"
(double (/ (count-parens (:program most-zero-cases-best))
)
(println "--- Lexicase Population Statistics ---")
(println "Count of elite individuals by case:" count-elites-by-case)
(println (format "Population mean number of elite cases: %.2f"
(float (/ (apply + count-elites-by-case) (count population)))))
(println "Count of perfect (error zero) individuals by case:" count-zero-by-case)
(println (format "Population mean number of perfect (error zero) cases: %.2f"
(float (/ (apply + count-zero-by-case) (count population)))))))
(defn implicit-fitness-sharing-report
"This extra report is printed whenever implicit fitness sharing selection is used."
[population {:keys [print-errors meta-error-categories] :as argmap}]
(let [ifs-best (apply min-key :weighted-error population)]
(println "--- Program with Best Implicit Fitness Sharing Error Statistics ---")
(println "IFS best genome:" (print-genome ifs-best argmap))
(println "IFS best program:" (pr-str (not-lazy (:program ifs-best))))
(when print-errors (println "IFS best errors:" (not-lazy (:errors ifs-best))))
(when (and print-errors (not (empty? meta-error-categories)))
(println "IFS best meta-errors:" (not-lazy (:meta-errors ifs-best))))
(println "IFS best total error:" (:total-error ifs-best))
(println "IFS best mean error:" (float (/ (:total-error ifs-best)
(count (:errors ifs-best)))))
(println "IFS best IFS error:" (:weighted-error ifs-best))
(println "IFS best size:" (count-points (:program ifs-best)))
(printf "IFS best percent parens: %.3f\n"
(double (/ (count-parens (:program ifs-best))
(defn report-and-check-for-success
"Reports on the specified generation of a pushgp run. Returns the best
individual of the generation."
[population generation
{:keys [error-function report-simplifications meta-error-categories
error-threshold max-generations population-size
print-errors print-history print-cosmos-data print-timings
problem-specific-report total-error-method
parent-selection print-homology-data max-point-evaluations
max-program-executions use-ALPS
print-error-frequencies-by-case normalization autoconstructive
print-selection-counts print-preselection-fraction exit-on-success
print-csv-logs print-json-logs csv-log-filename json-log-filename
log-fitnesses-for-all-cases json-log-program-strings
print-edn-logs edn-keys edn-log-filename edn-additional-keys
visualize calculate-mod-metrics]
:as argmap}]
(r/generation-data! [:population]
(map #(dissoc % :program) population))
(println)
(println ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;")
(println ";; -*- Report at generation" generation)
(let [point-evaluations-before-report @point-evaluations-count
program-executions-before-report @program-executions-count
err-fn (if (= total-error-method :rmse) :weighted-error :total-error)
sorted (sort-by err-fn < population)
err-fn-best (if (not= parent-selection :downsampled-lexicase)
(first sorted)
passes all of those as well . Otherwise , just returns first individual
(error-function
(loop [sorted-individuals sorted]
(if (empty? (rest sorted-individuals))
(first sorted-individuals)
(if (and (<= (:total-error (first sorted-individuals)) error-threshold)
(> (apply + (:errors (error-function (first sorted-individuals) :train))) error-threshold)
(<= (:total-error (second sorted-individuals)) error-threshold))
(recur (rest sorted-individuals))
(first sorted-individuals))))
:train))
total-error-best (if (not= parent-selection :downsampled-lexicase)
err-fn-best
(assoc err-fn-best
:total-error
(apply +' (:errors err-fn-best))))
psr-best (problem-specific-report total-error-best
population
generation
error-function
report-simplifications)
best (if (= (type psr-best) clojush.individual.individual)
psr-best
total-error-best)
standard-deviation (fn [nums]
(if (<= (count nums) 1)
(str "Cannot find standard deviation of "
(count nums)
"numbers. Must have at least 2.")
(let [mean (mean nums)]
(Math/sqrt (/ (apply +' (map #(* (- % mean) (- % mean))
nums))
(dec (count nums)))))))
quartiles (fn [nums]
(if (zero? (count nums))
"Cannot find quartiles of zero numbers."
(let [sorted (sort nums)]
(vector (nth sorted
(truncate (/ (count nums) 4)))
(nth sorted
(truncate (/ (count nums) 2)))
(nth sorted
(truncate (/ (* 3 (count nums)) 4)))))))]
(when print-error-frequencies-by-case
(println "Error frequencies by case:"
(doall (map frequencies (apply map vector (map :errors population))))))
(when (some #{parent-selection}
#{:lexicase :elitegroup-lexicase :leaky-lexicase :epsilon-lexicase
:random-threshold-lexicase :random-toggle-lexicase
:randomly-truncated-lexicase})
(lexicase-report population argmap))
(when (= total-error-method :ifs) (implicit-fitness-sharing-report population argmap))
(println (format "--- Best Program (%s) Statistics ---" (str "based on " (name err-fn))))
(r/generation-data! [:best :individual] (dissoc best :program))
(println "Best genome:" (print-genome best argmap))
(println "Best program:" (pr-str (not-lazy (:program best))))
(when calculate-mod-metrics
(println "Reuse in Best Program:" (pr-str (:reuse-info best)))
(println "Repetition in Best Program:" (pr-str (:repetition-info best))))
(when (> report-simplifications 0)
(let [simplified (not-lazy (:program (r/generation-data! [:best :individual-simplified]
(auto-simplify best
error-function
report-simplifications
false
1000
argmap))))]
(println "Partial simplification:" (pr-str simplified))
(println "Partial simplified size:" (count-points simplified))))
(when print-errors (println "Errors:" (not-lazy (:errors best))))
(when (and print-errors (not (empty? meta-error-categories)))
(println "Meta-Errors:" (not-lazy (:meta-errors best))))
(println "Total:" (:total-error best))
(let [mean (r/generation-data! [:best :mean-error] (float (/ (:total-error best)
(count (:errors best)))))]
(println "Mean:" mean))
(when (not= normalization :none)
(println "Normalized error:" (:normalized-error best)))
(case total-error-method
:hah (println "HAH-error:" (:weighted-error best))
:rmse (println "RMS-error:" (:weighted-error best))
:ifs (println "IFS-error:" (:weighted-error best))
nil)
(when (= parent-selection :novelty-search)
(println "Novelty: " (float (:novelty best))))
(when print-history (println "History:" (not-lazy (:history best))))
(println "Genome size:" (r/generation-data! [:best :genome-size] (count (:genome best))))
(println "Size:" (r/generation-data! [:best :program-size] (count-points (:program best))))
(printf "Percent parens: %.3f\n"
(r/generation-data! [:best :percent-parens]
(double (/ (count-parens (:program best))
(println "Age:" (:age best))
(println "--- Population Statistics ---")
(when print-cosmos-data
(println "Cosmos Data:" (let [quants (config/quantiles (count population))]
(zipmap quants
(map #(:total-error (nth (sort-by :total-error population) %))
quants)))))
(println "Average total errors in population:"
(r/generation-data! [:population-report :mean-total-error]
(*' 1.0 (mean (map :total-error sorted)))))
(println "Median total errors in population:"
(r/generation-data! [:population-report :median-total-error]
(median (map :total-error sorted))))
(when print-errors (println "Error averages by case:"
(apply map (fn [& args] (*' 1.0 (mean args)))
(map :errors population))))
(when print-errors (println "Error minima by case:"
(apply map (fn [& args] (apply min args))
(map :errors population))))
(when (and print-errors (not (empty? meta-error-categories)))
(println "Meta-Error averages by category:"
(apply map (fn [& args] (*' 1.0 (mean args)))
(map :meta-errors population)))
(println "Meta-Error minima by category:"
(apply map (fn [& args] (apply min args))
(map :meta-errors population))))
(println "Average genome size in population (length):"
(r/generation-data! [:population-report :mean-genome-size]
(*' 1.0 (mean (map count (map :genome sorted))))))
(println "Average program size in population (points):"
(r/generation-data! [:population-report :mean-program-size]
(*' 1.0 (mean (map count-points (map :program sorted))))))
(printf "Average percent parens in population: %.3f\n"
(r/generation-data! [:population-report :mean-program-percent-params]
(mean (map #(double (/ (count-parens (:program %)) (count-points (:program %)))) sorted))))
(let [ages (map :age population)]
(when use-ALPS
(println "Population ages:" ages))
(println "Minimum age in population:"
(r/generation-data! [:population-report :min-age]
(* 1.0 (apply min ages))))
(println "Maximum age in population:"
(r/generation-data! [:population-report :max-age]
(* 1.0 (apply max ages))))
(println "Average age in population:"
(r/generation-data! [:population-report :mean-age]
(* 1.0 (mean ages))))
(println "Median age in population:"
(r/generation-data! [:population-report :median-age]
(* 1.0 (median ages)))))
(let [grain-sizes (map :grain-size population)]
(println "Minimum grain-size in population:"
(r/generation-data! [:population-report :min-grain-size]
(* 1.0 (apply min grain-sizes))))
(println "Maximum grain-size in population:"
(r/generation-data! [:population-report :max-grain-size]
(* 1.0 (apply max grain-sizes))))
(println "Average grain-size in population:"
(r/generation-data! [:population-report :mean-grain-size]
(* 1.0 (mean grain-sizes))))
(println "Median grain-size in population:"
(r/generation-data! [:population-report :median-grain-size]
(* 1.0 (median grain-sizes)))))
(println "--- Population Diversity Statistics ---")
(let [genome-frequency-map (frequencies (map :genome population))]
(println "Min copy number of one genome:"
(r/generation-data! [:population-report :min-genome-frequency]
(apply min (vals genome-frequency-map))))
(println "Median copy number of one genome:"
(r/generation-data! [:population-report :median-genome-frequency]
(median (vals genome-frequency-map))))
(println "Max copy number of one genome:"
(r/generation-data! [:population-report :max-genome-frequency]
(apply max (vals genome-frequency-map))))
(println "Genome diversity (% unique genomes):\t"
(r/generation-data! [:population-report :percent-genomes-unique]
(float (/ (count genome-frequency-map) (count population))))))
(let [frequency-map (frequencies (map :program population))]
(println "Min copy number of one Push program:"
(r/generation-data! [:population-report :min-program-frequency]
(apply min (vals frequency-map))))
(println "Median copy number of one Push program:"
(r/generation-data! [:population-report :median-program-frequency]
(median (vals frequency-map))))
(println "Max copy number of one Push program:"
(r/generation-data! [:population-report :max-program-frequency]
(apply max (vals frequency-map))))
(println "Syntactic diversity (% unique Push programs):\t"
(r/generation-data! [:population-report :percent-programs-unique]
(float (/ (count frequency-map) (count population))))))
(println "Total error diversity:\t\t\t\t"
(r/generation-data! [:population-report :percent-total-error-unique]
(float (/ (count (distinct (map :total-error population))) (count population)))))
(println "Error (vector) diversity:\t\t\t"
(r/generation-data! [:population-report :percent-errors-unique]
(float (/ (count (distinct (map :errors population))) (count population)))))
(when (not (nil? (:behaviors (first population))))
(println "Behavioral diversity:\t\t\t\t" (behavioral-diversity population)))
(when print-homology-data
(let [num-samples 1000
sample-1 (sample-population-edit-distance population num-samples)
[first-quart-1 median-1 third-quart-1] (quartiles sample-1)]
(println "--- Population Homology Statistics (all stats reference the sampled population edit distance of programs) ---")
(println "Number of homology samples:" num-samples)
(println "Average: " (mean sample-1))
(println "Standard deviation: " (standard-deviation sample-1))
(println "First quartile: " first-quart-1)
(println "Median: " median-1)
(println "Third quartile: " third-quart-1)))
(when print-selection-counts
(println "Selection counts:"
(sort > (concat (vals @selection-counts)
(repeat (- population-size (count @selection-counts)) 0))))
(reset! selection-counts {}))
(when (and print-preselection-fraction
(not (empty? @preselection-counts)))
(println "Preselection fraction:" (float (/ (/ (reduce + @preselection-counts) population-size)
(count @preselection-counts))))
(reset! preselection-counts []))
(when autoconstructive
(println "Number of random replacements for non-diversifying individuals:"
(r/generation-data! [:population-report :number-random-replacements]
(count (filter :is-random-replacement population)))))
(println "--- Run Statistics ---")
(println "Number of individuals evaluated (running on all training cases counts as 1 evaluation):" @evaluations-count)
(println "Number of program executions (running on a single case counts as 1 execution):" program-executions-before-report)
(println "Number of point (instruction) evaluations so far:" point-evaluations-before-report)
(reset! point-evaluations-count point-evaluations-before-report)
(reset! program-executions-count program-executions-before-report)
(println "--- Timings ---")
(println "Current time:" (System/currentTimeMillis) "milliseconds")
(when print-timings
(let [total-time (apply + (vals @timing-map))
init (get @timing-map :initialization)
reproduction (get @timing-map :reproduction)
fitness (get @timing-map :fitness)
report-time (get @timing-map :report)
other (get @timing-map :other)]
(printf "Total Time: %8.1f seconds\n"
(/ total-time 1000.0))
(printf "Initialization: %8.1f seconds, %4.1f%%\n"
(/ init 1000.0) (* 100.0 (/ init total-time)))
(printf "Reproduction: %8.1f seconds, %4.1f%%\n"
(/ reproduction 1000.0) (* 100.0 (/ reproduction total-time)))
(printf "Fitness Testing: %8.1f seconds, %4.1f%%\n"
(/ fitness 1000.0) (* 100.0 (/ fitness total-time)))
(printf "Report: %8.1f seconds, %4.1f%%\n"
(/ report-time 1000.0) (* 100.0 (/ report-time total-time)))
(printf "Other: %8.1f seconds, %4.1f%%\n"
(/ other 1000.0) (* 100.0 (/ other total-time)))))
(println ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;")
(println ";; -*- End of report for generation" generation)
(println ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;")
(flush)
(when print-csv-logs (csv-print population generation argmap))
(when print-json-logs (json-print population generation json-log-filename
log-fitnesses-for-all-cases json-log-program-strings))
(when print-edn-logs
(edn-print population generation edn-log-filename edn-keys edn-additional-keys))
(when visualize
(swap! viz-data-atom update-in [:history-of-errors-of-best] conj (:errors best))
(swap! viz-data-atom assoc :generation generation))
(cond
(and exit-on-success
(or (<= (:total-error best) error-threshold)
(:success best)))
[:success best]
(>= generation max-generations)
[:failure best]
(>= @program-executions-count max-program-executions)
[:failure best]
(>= @point-evaluations-count max-point-evaluations)
[:failure best]
:else
[:continue best])))
(defn remove-function-values [argmap]
(into {} (filter (fn [[k v]] (not (fn? v)))
(dissoc argmap :random-seed :atom-generators))))
(defn initial-report
"Prints the initial report of a PushGP run."
[{:keys [problem-specific-initial-report] :as push-argmap}]
(problem-specific-initial-report push-argmap)
(println "Registered instructions:"
(r/config-data! [:registered-instructions] @registered-instructions))
(println "Starting PushGP run.")
(printf "Clojush version = ")
(try
(let [version-str (apply str (butlast (re-find #"\".*\""
(first (string/split-lines
(local-file/slurp* "project.clj"))))))
version-number (.substring version-str 1 (count version-str))]
(if (empty? version-number)
(throw Exception)
(printf (str (r/config-data! [:version-number] version-number)) "\n")))
(flush)
(catch Exception e
(printf "version number unavailable\n")
(flush)))
(try
(let [git-hash (git-last-commit-hash)]
(if (empty? git-hash)
(throw Exception)
(do
to GitHub .
(r/config-data! [:git-hash] git-hash)
(printf (str "Hash of last Git commit = " git-hash "\n"))
(printf (str "GitHub link = /"
git-hash
"\n"))
(flush))))
(catch Exception e
(printf "Hash of last Git commit = unavailable\n")
(printf "GitHub link = unavailable\n")
(flush)))
(if (:print-edn-logs push-argmap)
(with-open [w (io/writer (:edn-log-filename push-argmap) :append false)]
(.write w "#clojush/run")
(.write w (prn-str (remove-function-values push-argmap)))))
Require conditionally ( dynamically ) , avoiding unintended Quil sketch launch
(require 'clojush.pushgp.visualize)))
(defn final-report
"Prints the final report of a PushGP run if the run is successful."
[generation best
{:keys [error-function final-report-simplifications report-simplifications
print-ancestors-of-solution problem-specific-report] :as argmap}]
(printf "\n\nSUCCESS at generation %s\nSuccessful program: %s\nErrors: %s\nTotal error: %s\nHistory: %s\nSize: %s\n\n"
generation (pr-str (not-lazy (:program best))) (not-lazy (:errors best)) (:total-error best)
(not-lazy (:history best)) (count-points (:program best)))
(when print-ancestors-of-solution
(printf "\nAncestors of solution:\n")
(prn (:ancestors best)))
(let [simplified-best (auto-simplify best error-function final-report-simplifications true 500 argmap)]
(println "\n;;******************************")
(println ";; Problem-Specific Report of Simplified Solution")
(println "Reuse in Simplified Solution:" (:reuse-info (error-function simplified-best)))
(problem-specific-report simplified-best [] generation error-function report-simplifications)))
|
b12178c689d43244d764b8047db36d82e363c59ca0a5db6c969518a9ffc02618
|
LuisThiamNye/chic
|
test_clj_syntax.clj
|
;; -Sublimed/blob/master/test_syntax/syntax_test_clojure.cljc
This file is a copy of -Sublimed/blob/43de45c36b3a40d1819f76243f09c18cac3625f3/test_syntax/syntax_test_clojure.cljc
;; Distributed under the following license:
The MIT License ( MIT )
Copyright ( c ) 2018 - 2021 Nikita Prokopov
;; 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.
SYNTAX TEST " Clojure ( Sublimed).sublime - syntax "
; VAR QUOTE
#'map
; ^ keyword.operator.var
#' , map
; ^^ keyword.operator.var
; ^^^^^^ - keyword.operator.var
; ^ punctuation.definition.comma
DEREF
@*atom
^ keyword.operator.deref
@ , *atom
^ keyword.operator.deref
; ^^^^^^^^ - keyword.operator.deref
; ^ punctuation.definition.comma
; READER CONDITIONALS
#?(:clj 1 :cljs 2)
; ^^^ punctuation.section.parens.begin
^^^^^^^^^^^^^^^^^^ meta.parens
; ^ punctuation.section.parens.end
; ^ - punctuation - meta.section
#?@(:clj [3 4] :cljs [5 6])
; ^^^^ punctuation.section.parens.begin
^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.parens
; ^ punctuation.section.parens.end
; ^ - punctuation - meta.section
; QUOTE
'[datascript :as ds] []
; ^ keyword.operator.quote
; ^^^^^^^^^^^^^^^^^^^^ meta.quoted
; ^^^ -meta.quoted
'datascript.core []
; ^ keyword.operator.quote
^^^^^^^^^^^^^^^^ meta.quoted
; ^^^ -meta.quoted
' , datascript.core []
; ^ keyword.operator.quote
^^^^^^^^^^^^^^^^^^ - keyword.operator
; ^^^^^^^^^^^^^^^^^^^ meta.quoted
; ^ punctuation.definition.comma
SYNTAX QUOTE , UNQUOTE , UNQUOTE SPLICING
`(let [x# ~x] ~@(do `(...))) []
; ^ keyword.operator.quote.syntax
; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.quoted.syntax
; ^^^ - meta.quoted
^ keyword.operator.unquote - invalid
; ^^ meta.quoted.syntax meta.unquoted
^^ keyword.operator.unquote - invalid
; ^^^^^^^^^^^^^ meta.quoted.syntax meta.unquoted
; ^^^^^^ meta.quoted.syntax meta.unquoted meta.quoted.syntax
` , (~ , x ~@ , xs) []
; ^^^^^^^^^^^^^^^^^^^ meta.quoted.syntax
; ^^^ - meta.quoted.syntax
; ^ keyword.operator.quote.syntax
; ^^^^^^^^^^^^^^^^^^^^^ - keyword.operator.quote.syntax
; ^ punctuation.definition.comma
; ^^^^ meta.unquoted
^ keyword.operator.unquote
; ^^^ - keyword.operator.unquote
; ^ punctuation.definition.comma
; ^^^^^^^ meta.unquoted
^^ keyword.operator.unquote
^^^^^ - keyword.operator.unquote
; ^ punctuation.definition.comma
METADATA
^{:a 1 :b 2} ^String ^"String" ^:dynamic x
; ^ punctuation.definition.metadata
^^^^^^^^^^^^ meta.metadata
; ^ - meta.metadata
; ^ punctuation.definition.metadata
; ^^^^^^^ meta.metadata
; ^ - meta.metadata
; ^ punctuation.definition.metadata
; ^^^^^^^^^ meta.metadata
; ^ - meta.metadata
; ^ punctuation.definition.metadata
; ^^^^^^^^ meta.metadata
; ^ - meta.metadata
^ , :dynamic x
^^^^^^^^^^^^ meta.metadata
; ^^ - meta.metadata
; ^ punctuation.definition.metadata
; ^^^^^^^^^^^^^ - punctuation.definition.metadata
; ^ punctuation.definition.comma
^123 x ^[:dynamic true] x
; ^^^ -meta.metadata
; ^^^^^^^^^^^^^^^ -meta.metadata
REGEXPS
#""
; ^^^ string.regexp
; ^^ punctuation.definition.string.begin
; ^ punctuation.definition.string.end
; ^ - string.regexp
#"abc"
; ^^^^^^ string.regexp
; ^^ punctuation.definition.string.begin
; ^ punctuation.definition.string.end
; ^ - string.regexp
#"\\ \07 \077 \0377 \xFF \uFFFF \x{0} \x{FFFFF} \x{10FFFF} \N{white smiling face}"
; ^^ constant.character.escape
; ^^^ constant.character.escape
; ^^^^ constant.character.escape
^^^^^ constant.character.escape
; ^^^^ constant.character.escape
; ^^^^^^ constant.character.escape
; ^^^^^ constant.character.escape
; ^^^^^^^^^ constant.character.escape
; ^^^^^^^^^^ constant.character.escape
; ^^^^^^^^^^^^^^^^^^^^^^ constant.character.escape
#"\t \n \r \f \a \e \cC \d \D \h \H \s \S \v \V \w \W"
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
#"\p{IsLatin} \p{L} \b \b{g} \B \A \G \Z \z \R \X \0 \99 \k<gr3> \( \} \""
^^^^^^^^^^^ constant.character.escape
^^^^^ constant.character.escape
; ^^ constant.character.escape
^^^^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^^ constant.character.escape
; ^^^^^^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
; ^^ constant.character.escape
#"\y \x \uABC \p{Is Latin} \k<1gr> "
; ^^ invalid.illegal.escape.regexp
; ^^ invalid.illegal.escape.regexp
; ^^ invalid.illegal.escape.regexp
; ^^ invalid.illegal.escape.regexp
; ^^ invalid.illegal.escape.regexp
#"[^a-z\[^&&[-a-z-]]]"
; ^ punctuation.section.brackets.begin
; ^ keyword.operator.negation.regexp
; ^ - punctuation.section.brackets
; ^ - keyword.operator.negation.regexp
; ^^ keyword.operator.intersection.regexp
; ^ punctuation.section.brackets.begin
; ^ - keyword.operator.range.regexp
; ^ keyword.operator.range.regexp
; ^ - keyword.operator.range.regexp
; ^^ punctuation.section.brackets.end
; ^ - punctuation
#"a? a* a+ a{1} a{1,} a{1,2}"
; ^ keyword.operator.quantifier.regexp
; ^ keyword.operator.quantifier.regexp
; ^ keyword.operator.quantifier.regexp
^^^^ keyword.operator.quantifier.regexp
^^^^^ keyword.operator.quantifier.regexp
#"a?? a*? a+? a{1}? a{1,}? a{1,2}?"
; ^^ keyword.operator.quantifier.regexp
; ^^ keyword.operator.quantifier.regexp
; ^^ keyword.operator.quantifier.regexp
^^^^ keyword.operator.quantifier.regexp
^^^^^ keyword.operator.quantifier.regexp
; ^^^^^^ keyword.operator.quantifier.regexp
#"a?+ a*+ a++ a{1}+ a{1,}+ a{1,2}+"
; ^^ keyword.operator.quantifier.regexp
; ^^ keyword.operator.quantifier.regexp
; ^^ keyword.operator.quantifier.regexp
^^^^ keyword.operator.quantifier.regexp
^^^^^ keyword.operator.quantifier.regexp
; ^^^^^^ keyword.operator.quantifier.regexp
#"(x|(\(\||[)|])))"
; ^ punctuation.section.parens.begin
; ^ keyword.operator.union.regexp
; ^ punctuation.section.parens.begin
; ^ - punctuation.section.parens
; ^ - keyword.operator
; ^ keyword.operator.union.regexp
; ^ - punctuation.section.parens - invalid
; ^ - keyword.operator - invalid
; ^^ punctuation.section.parens.end
; ^ invalid.illegal.stray-bracket-end
#"(?<name>a) (?:a) (?idm-suxUa) (?sux-idm:a) (?=a) (?!a) (?<=a) (?<!a) (?>a)"
; ^ punctuation.section.parens.begin
; ^^^^^^^ keyword.operator.special.regexp
; ^ punctuation.section.parens.end
; ^^ keyword.operator.special.regexp
; ^^^^^^^^^ keyword.operator.special.regexp
; ^^^^^^^^^ keyword.operator.special.regexp
; ^^ keyword.operator.special.regexp
; ^^ keyword.operator.special.regexp
; ^^^ keyword.operator.special.regexp
; ^^^ keyword.operator.special.regexp
; ^^ keyword.operator.special.regexp
#"(abc) \Q (a|b) [^DE] )] \" \E (abc)"
; ^ punctuation.section.parens.end - constant.character.escape
; ^^ punctuation.section.quotation.begin
; ^^^^^^^^^^^^^^^^^^^ constant.character.escape - punctuation - keyword - invalid
; ^^ punctuation.section.quotation.end
; ^ punctuation.section.parens.begin - constant.character.escape
#"\Q ABC" #"(" #"["
; ^^^^^^^^^ string.regexp
; ^^^^ constant.character.escape
; ^ punctuation.definition.string.end - constant.character.escape
; ^ - string.regexp
^^^^ string.regexp
; ^ - string.regexp
; ^^^^ string.regexp
; ^ - string.regexp
; SIMPLE DEFN
(defn fname [arg arg2] body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.definition & meta.parens
; ^ -meta.definition -meta.parens
; ^^^^^ source.symbol entity.name
; ^ punctuation.section.parens.begin
^^^^ source.symbol
; ^ punctuation.section.parens.end
; EVERYTHING
(defn- ^{:meta :map} fn "doc" {:attr :map} [args] {:pre ()} body)
; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.definition
^^^^^ source.symbol
; ^^^^^^^^^^^^^ meta.metadata
; ^^ entity.name
INCOMPLETE FNS ARE STILL CLOSED
(defn)
; ^^^^^^ meta.definition
; ^ -meta.definition
(defn f)
; ^^^^^^^^ meta.definition
; ^ -meta.definition
; ^ entity.name
; PRECEDING SYMBOLS AND OTHER GARBAGE DO NOT CONFUSE ENTITY.NAME LOOKUP
(defn 15 "str" {a b} fname 15 sym \n ("abc") [])
^^^^^ entity.name
; DEF
(def x 1)
; ^^^^^^^^^ meta.definition
^^^ source.symbol
; ^ entity.name
DEFMETHOD
(defmethod x 1)
^^^^^^^^^^^^^^^ meta.definition
^^^^^^^^^ source.symbol
; ^ entity.name
; NAMESPACED DEF
(rum/defcs x 1)
^^^^^^^^^^^^^^^ meta.definition & meta.parens
; ^ entity.name
; ^ punctuation.section.parens.begin
^^^^^^^^^ source.symbol
; ^ punctuation.definition.symbol.namespace
; ^ punctuation.section.parens.end
; DEF OF NAMESPACED SYMBOL
(defmethod clojure.test/report :error [m])
; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.definition & meta.parens
; ^^^^^^^^^^^^^^^^^^^ entity.name
; ^ punctuation.section.parens.begin
; ^ punctuation.definition.symbol.namespace
; ^ punctuation.section.parens.end
; NON-TOP DEF
#?(:clj (def x 1))
; ^^^^^^^^^ meta.definition & meta.parens
; ^ entity.name
; ^ punctuation.section.parens.begin
; ^ punctuation.section.parens.end
#(+ %1 %2)
^^^^^^^^^^ meta.function & meta.parens
; ^^ - meta.function
; ^^ punctuation.section.parens.begin
; ^ punctuation.section.parens.end
| null |
https://raw.githubusercontent.com/LuisThiamNye/chic/813633a689f9080731613f788a295604d4d9a510/resources/clj/test_clj_syntax.clj
|
clojure
|
-Sublimed/blob/master/test_syntax/syntax_test_clojure.cljc
Distributed under the following license:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
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
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
VAR QUOTE
^ keyword.operator.var
^^ keyword.operator.var
^^^^^^ - keyword.operator.var
^ punctuation.definition.comma
^^^^^^^^ - keyword.operator.deref
^ punctuation.definition.comma
READER CONDITIONALS
^^^ punctuation.section.parens.begin
^ punctuation.section.parens.end
^ - punctuation - meta.section
^^^^ punctuation.section.parens.begin
^ punctuation.section.parens.end
^ - punctuation - meta.section
QUOTE
^ keyword.operator.quote
^^^^^^^^^^^^^^^^^^^^ meta.quoted
^^^ -meta.quoted
^ keyword.operator.quote
^^^ -meta.quoted
^ keyword.operator.quote
^^^^^^^^^^^^^^^^^^^ meta.quoted
^ punctuation.definition.comma
^ keyword.operator.quote.syntax
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.quoted.syntax
^^^ - meta.quoted
^^ meta.quoted.syntax meta.unquoted
^^^^^^^^^^^^^ meta.quoted.syntax meta.unquoted
^^^^^^ meta.quoted.syntax meta.unquoted meta.quoted.syntax
^^^^^^^^^^^^^^^^^^^ meta.quoted.syntax
^^^ - meta.quoted.syntax
^ keyword.operator.quote.syntax
^^^^^^^^^^^^^^^^^^^^^ - keyword.operator.quote.syntax
^ punctuation.definition.comma
^^^^ meta.unquoted
^^^ - keyword.operator.unquote
^ punctuation.definition.comma
^^^^^^^ meta.unquoted
^ punctuation.definition.comma
^ punctuation.definition.metadata
^ - meta.metadata
^ punctuation.definition.metadata
^^^^^^^ meta.metadata
^ - meta.metadata
^ punctuation.definition.metadata
^^^^^^^^^ meta.metadata
^ - meta.metadata
^ punctuation.definition.metadata
^^^^^^^^ meta.metadata
^ - meta.metadata
^^ - meta.metadata
^ punctuation.definition.metadata
^^^^^^^^^^^^^ - punctuation.definition.metadata
^ punctuation.definition.comma
^^^ -meta.metadata
^^^^^^^^^^^^^^^ -meta.metadata
^^^ string.regexp
^^ punctuation.definition.string.begin
^ punctuation.definition.string.end
^ - string.regexp
^^^^^^ string.regexp
^^ punctuation.definition.string.begin
^ punctuation.definition.string.end
^ - string.regexp
^^ constant.character.escape
^^^ constant.character.escape
^^^^ constant.character.escape
^^^^ constant.character.escape
^^^^^^ constant.character.escape
^^^^^ constant.character.escape
^^^^^^^^^ constant.character.escape
^^^^^^^^^^ constant.character.escape
^^^^^^^^^^^^^^^^^^^^^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^^ constant.character.escape
^^^^^^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ constant.character.escape
^^ invalid.illegal.escape.regexp
^^ invalid.illegal.escape.regexp
^^ invalid.illegal.escape.regexp
^^ invalid.illegal.escape.regexp
^^ invalid.illegal.escape.regexp
^ punctuation.section.brackets.begin
^ keyword.operator.negation.regexp
^ - punctuation.section.brackets
^ - keyword.operator.negation.regexp
^^ keyword.operator.intersection.regexp
^ punctuation.section.brackets.begin
^ - keyword.operator.range.regexp
^ keyword.operator.range.regexp
^ - keyword.operator.range.regexp
^^ punctuation.section.brackets.end
^ - punctuation
^ keyword.operator.quantifier.regexp
^ keyword.operator.quantifier.regexp
^ keyword.operator.quantifier.regexp
^^ keyword.operator.quantifier.regexp
^^ keyword.operator.quantifier.regexp
^^ keyword.operator.quantifier.regexp
^^^^^^ keyword.operator.quantifier.regexp
^^ keyword.operator.quantifier.regexp
^^ keyword.operator.quantifier.regexp
^^ keyword.operator.quantifier.regexp
^^^^^^ keyword.operator.quantifier.regexp
^ punctuation.section.parens.begin
^ keyword.operator.union.regexp
^ punctuation.section.parens.begin
^ - punctuation.section.parens
^ - keyword.operator
^ keyword.operator.union.regexp
^ - punctuation.section.parens - invalid
^ - keyword.operator - invalid
^^ punctuation.section.parens.end
^ invalid.illegal.stray-bracket-end
^ punctuation.section.parens.begin
^^^^^^^ keyword.operator.special.regexp
^ punctuation.section.parens.end
^^ keyword.operator.special.regexp
^^^^^^^^^ keyword.operator.special.regexp
^^^^^^^^^ keyword.operator.special.regexp
^^ keyword.operator.special.regexp
^^ keyword.operator.special.regexp
^^^ keyword.operator.special.regexp
^^^ keyword.operator.special.regexp
^^ keyword.operator.special.regexp
^ punctuation.section.parens.end - constant.character.escape
^^ punctuation.section.quotation.begin
^^^^^^^^^^^^^^^^^^^ constant.character.escape - punctuation - keyword - invalid
^^ punctuation.section.quotation.end
^ punctuation.section.parens.begin - constant.character.escape
^^^^^^^^^ string.regexp
^^^^ constant.character.escape
^ punctuation.definition.string.end - constant.character.escape
^ - string.regexp
^ - string.regexp
^^^^ string.regexp
^ - string.regexp
SIMPLE DEFN
^ -meta.definition -meta.parens
^^^^^ source.symbol entity.name
^ punctuation.section.parens.begin
^ punctuation.section.parens.end
EVERYTHING
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.definition
^^^^^^^^^^^^^ meta.metadata
^^ entity.name
^^^^^^ meta.definition
^ -meta.definition
^^^^^^^^ meta.definition
^ -meta.definition
^ entity.name
PRECEDING SYMBOLS AND OTHER GARBAGE DO NOT CONFUSE ENTITY.NAME LOOKUP
DEF
^^^^^^^^^ meta.definition
^ entity.name
^ entity.name
NAMESPACED DEF
^ entity.name
^ punctuation.section.parens.begin
^ punctuation.definition.symbol.namespace
^ punctuation.section.parens.end
DEF OF NAMESPACED SYMBOL
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.definition & meta.parens
^^^^^^^^^^^^^^^^^^^ entity.name
^ punctuation.section.parens.begin
^ punctuation.definition.symbol.namespace
^ punctuation.section.parens.end
NON-TOP DEF
^^^^^^^^^ meta.definition & meta.parens
^ entity.name
^ punctuation.section.parens.begin
^ punctuation.section.parens.end
^^ - meta.function
^^ punctuation.section.parens.begin
^ punctuation.section.parens.end
|
This file is a copy of -Sublimed/blob/43de45c36b3a40d1819f76243f09c18cac3625f3/test_syntax/syntax_test_clojure.cljc
The MIT License ( MIT )
Copyright ( c ) 2018 - 2021 Nikita Prokopov
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
SYNTAX TEST " Clojure ( Sublimed).sublime - syntax "
#'map
#' , map
DEREF
@*atom
^ keyword.operator.deref
@ , *atom
^ keyword.operator.deref
#?(:clj 1 :cljs 2)
^^^^^^^^^^^^^^^^^^ meta.parens
#?@(:clj [3 4] :cljs [5 6])
^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.parens
'[datascript :as ds] []
'datascript.core []
^^^^^^^^^^^^^^^^ meta.quoted
' , datascript.core []
^^^^^^^^^^^^^^^^^^ - keyword.operator
SYNTAX QUOTE , UNQUOTE , UNQUOTE SPLICING
`(let [x# ~x] ~@(do `(...))) []
^ keyword.operator.unquote - invalid
^^ keyword.operator.unquote - invalid
` , (~ , x ~@ , xs) []
^ keyword.operator.unquote
^^ keyword.operator.unquote
^^^^^ - keyword.operator.unquote
METADATA
^{:a 1 :b 2} ^String ^"String" ^:dynamic x
^^^^^^^^^^^^ meta.metadata
^ , :dynamic x
^^^^^^^^^^^^ meta.metadata
^123 x ^[:dynamic true] x
REGEXPS
#""
#"abc"
#"\\ \07 \077 \0377 \xFF \uFFFF \x{0} \x{FFFFF} \x{10FFFF} \N{white smiling face}"
^^^^^ constant.character.escape
#"\t \n \r \f \a \e \cC \d \D \h \H \s \S \v \V \w \W"
#"\p{IsLatin} \p{L} \b \b{g} \B \A \G \Z \z \R \X \0 \99 \k<gr3> \( \} \""
^^^^^^^^^^^ constant.character.escape
^^^^^ constant.character.escape
^^^^^ constant.character.escape
#"\y \x \uABC \p{Is Latin} \k<1gr> "
#"[^a-z\[^&&[-a-z-]]]"
#"a? a* a+ a{1} a{1,} a{1,2}"
^^^^ keyword.operator.quantifier.regexp
^^^^^ keyword.operator.quantifier.regexp
#"a?? a*? a+? a{1}? a{1,}? a{1,2}?"
^^^^ keyword.operator.quantifier.regexp
^^^^^ keyword.operator.quantifier.regexp
#"a?+ a*+ a++ a{1}+ a{1,}+ a{1,2}+"
^^^^ keyword.operator.quantifier.regexp
^^^^^ keyword.operator.quantifier.regexp
#"(x|(\(\||[)|])))"
#"(?<name>a) (?:a) (?idm-suxUa) (?sux-idm:a) (?=a) (?!a) (?<=a) (?<!a) (?>a)"
#"(abc) \Q (a|b) [^DE] )] \" \E (abc)"
#"\Q ABC" #"(" #"["
^^^^ string.regexp
(defn fname [arg arg2] body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.definition & meta.parens
^^^^ source.symbol
(defn- ^{:meta :map} fn "doc" {:attr :map} [args] {:pre ()} body)
^^^^^ source.symbol
INCOMPLETE FNS ARE STILL CLOSED
(defn)
(defn f)
(defn 15 "str" {a b} fname 15 sym \n ("abc") [])
^^^^^ entity.name
(def x 1)
^^^ source.symbol
DEFMETHOD
(defmethod x 1)
^^^^^^^^^^^^^^^ meta.definition
^^^^^^^^^ source.symbol
(rum/defcs x 1)
^^^^^^^^^^^^^^^ meta.definition & meta.parens
^^^^^^^^^ source.symbol
(defmethod clojure.test/report :error [m])
#?(:clj (def x 1))
#(+ %1 %2)
^^^^^^^^^^ meta.function & meta.parens
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.