_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 |
|---|---|---|---|---|---|---|---|---|
208e94f797359289ea64d7dc3e04921ad826b79606c095d884256fd20af08b0c | fumieval/liszt | Internal.hs | # LANGUAGE LambdaCase , DeriveTraversable , DeriveGeneric #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE RecordWildCards #
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE RankNTypes #-}
module Database.Liszt.Internal (
Key(..)
, Tag
, LisztHandle(..)
, openLiszt
, closeLiszt
, withLiszt
-- * Writing
, clear
, insertRaw
, commit
, Transaction
, TransactionState
-- * Reading
, availableKeys
-- * Node
, Node(..)
, peekNode
, LisztDecodingException(..)
-- * Fetching
, Fetchable(..)
, KeyPointer(..)
, RawPointer(..)
-- * Footer
, footerSize
, isFooter
-- * Node
, lookupSpine
, traverseNode
-- * Spine
, Spine
, spineLength
, QueryResult
, wholeSpine
, takeSpine
, dropSpine
, takeSpineWhile
, dropSpineWhile
) where
import Control.Concurrent
import Control.DeepSeq
import Control.Monad
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Trans.State.Strict
import qualified Data.Aeson as J
import Data.Bifunctor
import qualified Data.ByteString as B
import qualified Data.ByteString.Internal as B
import qualified Data.IntMap.Strict as IM
import Data.IORef
import Data.Monoid
import Data.Word
import Data.String
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Mason.Builder
import Database.Liszt.Internal.Decoder
import Foreign.ForeignPtr
import Foreign.Ptr
import GHC.Generics (Generic)
import System.Directory
import System.IO
newtype Key = Key { unKey :: B.ByteString } deriving (Eq, Ord)
instance Show Key where
show = show . T.decodeUtf8 . unKey
instance IsString Key where
fromString = Key . T.encodeUtf8 . T.pack
instance J.FromJSON Key where
parseJSON obj = Key . T.encodeUtf8 <$> J.parseJSON obj
instance J.ToJSON Key where
toJSON = J.toJSON . T.decodeUtf8 . unKey
-- | Tag is an extra value attached to a payload. This can be used to perform
-- a binary search.
type Tag = B.ByteString
type Spine a = [(Int, a)]
newtype KeyPointer = KeyPointer RawPointer deriving (Show, Eq, NFData)
data RawPointer = RP !Int !Int deriving (Show, Eq, Generic)
instance NFData RawPointer where
rnf r = r `seq` ()
data Node a = Empty
| Leaf1 !KeyPointer !(Spine a)
| Leaf2 !KeyPointer !(Spine a) !KeyPointer !(Spine a)
| Node2 !a !KeyPointer !(Spine a) !a
| Node3 !a !KeyPointer !(Spine a) !a !KeyPointer !(Spine a) !a
| Tip !Tag !RawPointer
| Bin !Tag !RawPointer !a !a
deriving (Generic, Show, Eq, Functor, Foldable, Traversable)
encodeUInt :: Int -> Builder
encodeUInt = wordVLQ . fromIntegral
encodeNode :: Node RawPointer -> Builder
encodeNode Empty = word8 0x00
encodeNode (Leaf1 (KeyPointer p) s) = word8 0x01 <> encodeRP p <> encodeSpine s
encodeNode (Leaf2 (KeyPointer p) s (KeyPointer q) t) = word8 0x02
<> encodeRP p <> encodeSpine s <> encodeRP q <> encodeSpine t
encodeNode (Node2 l (KeyPointer p) s r) = word8 0x12
<> encodeRP l <> encodeRP p <> encodeSpine s <> encodeRP r
encodeNode (Node3 l (KeyPointer p) s m (KeyPointer q) t r) = word8 0x13
<> encodeRP l <> encodeRP p <> encodeSpine s
<> encodeRP m <> encodeRP q <> encodeSpine t <> encodeRP r
encodeNode (Tip t p) = word8 0x80 <> encodeUInt (B.length t) <> byteString t <> encodeRP p
encodeNode (Bin t p l r) = word8 0x81 <> encodeUInt (B.length t) <> byteString t
<> encodeRP p <> encodeRP l <> encodeRP r
encodeRP :: RawPointer -> Builder
encodeRP (RP p l) = encodeUInt p <> encodeUInt l
encodeSpine :: Spine RawPointer -> Builder
encodeSpine s = encodeUInt (length s) <> foldMap (\(r, p) -> encodeUInt r <> encodeRP p) s
data LisztDecodingException = LisztDecodingException deriving Show
instance Exception LisztDecodingException
peekNode :: Ptr Word8 -> IO (Node RawPointer)
peekNode = runDecoder $ decodeWord8 >>= \case
0x00 -> return Empty
0x01 -> Leaf1 <$> kp <*> spine
0x02 -> Leaf2 <$> kp <*> spine <*> kp <*> spine
0x12 -> Node2 <$> rp <*> kp <*> spine <*> rp
0x13 -> Node3 <$> rp <*> kp <*> spine <*> rp <*> kp <*> spine <*> rp
0x80 -> Tip <$> bs <*> rp
0x81 -> Bin <$> bs <*> rp <*> rp <*> rp
_ -> throwM LisztDecodingException
where
kp = fmap KeyPointer rp
rp = RP <$> decodeVarInt <*> decodeVarInt
spine = do
len <- decodeVarInt
replicateM len $ (,) <$> decodeVarInt <*> rp
bs = do
len <- decodeVarInt
Decoder $ \src -> do
fp <- B.mallocByteString len
withForeignPtr fp $ \dst -> B.memcpy dst src len
return $ DecodeResult (src `plusPtr` len) (B.PS fp 0 len)
data LisztHandle = LisztHandle
{ hPayload :: !Handle
, refBuffer :: MVar (Int, ForeignPtr Word8)
, keyCache :: IORef (IM.IntMap Key)
, refModified :: IORef Bool
, handleLock :: MVar ()
}
openLiszt :: MonadIO m => FilePath -> m LisztHandle
openLiszt path = liftIO $ do
exist <- doesFileExist path
hPayload <- openBinaryFile path ReadWriteMode
unless exist $ B.hPutStr hPayload emptyFooter
buf <- B.mallocByteString 4096
refBuffer <- newMVar (4096, buf)
keyCache <- newIORef IM.empty
handleLock <- newMVar ()
refModified <- newIORef False
return LisztHandle{..}
closeLiszt :: MonadIO m => LisztHandle -> m ()
closeLiszt lh = liftIO $ hClose $ hPayload lh
withLiszt :: (MonadIO m, MonadMask m) => FilePath -> (LisztHandle -> m a) -> m a
withLiszt path = bracket (openLiszt path) closeLiszt
--------------------------------------------------------------------------------
-- Transaction
data StagePointer = Commited !RawPointer | Uncommited !(Node StagePointer) deriving Eq
data TransactionState = TS
{ dbHandle :: !LisztHandle
, currentRoot :: !(Node StagePointer)
, currentPos :: !Int
}
type Transaction = StateT TransactionState IO
-- | Replace the specified key with an empty list.
clear :: Key -> Transaction ()
clear key = do
root <- gets currentRoot
insertF key (const $ return []) root >>= \case
Pure t -> modify $ \ts -> ts { currentRoot = t }
Carry l k a r -> modify $ \ts -> ts { currentRoot = Node2 l k a r }
append :: LisztHandle -> (Handle -> IO a) -> IO a
append LisztHandle{..} cont = do
hSeek hPayload SeekFromEnd 0
writeIORef refModified True
cont hPayload
insertRaw :: Key -> Tag -> BuilderFor BufferedIOBackend -> Transaction ()
insertRaw key tag payload = do
lh <- gets dbHandle
ofs <- gets currentPos
len <- liftIO $ append lh $ \h -> hPutBuilderLen h payload
root <- gets currentRoot
modify $ \ts -> ts { currentPos = ofs + len }
insertF key (insertSpine tag (ofs `RP` len)) root >>= \case
Pure t -> modify $ \ts -> ts { currentRoot = t }
Carry l k a r -> modify $ \ts -> ts { currentRoot = Node2 l k a r }
allocKey :: Key -> Transaction KeyPointer
allocKey (Key key) = do
lh <- gets dbHandle
ofs <- gets currentPos
liftIO $ append lh $ \h -> do
B.hPutStr h key
modifyIORef' (keyCache lh) (IM.insert ofs (Key key))
modify $ \ts -> ts { currentPos = ofs + B.length key }
return $ KeyPointer $ RP ofs (B.length key)
commit :: MonadIO m => LisztHandle -> Transaction a -> m a
commit h transaction = liftIO $ modifyMVar (handleLock h) $ const $ do
offset0 <- fromIntegral <$> hFileSize h'
root <- fetchRoot h
do
(a, TS _ root' offset1) <- runStateT transaction
$ TS h (fmap Commited root) offset0
let substP :: StagePointer -> StateT Int IO RawPointer
substP (Commited ofs) = return ofs
substP (Uncommited f) = substF f
substF :: Node StagePointer -> StateT Int IO RawPointer
substF Empty = return (RP 0 0)
substF (Leaf1 pk pv) = do
pv' <- traverse (traverse substP) pv
write (Leaf1 pk pv')
substF (Leaf2 pk pv qk qv) = do
pv' <- traverse (traverse substP) pv
qv' <- traverse (traverse substP) qv
write (Leaf2 pk pv' qk qv')
substF (Node2 l pk pv r) = do
l' <- substP l
pv' <- traverse (traverse substP) pv
r' <- substP r
write (Node2 l' pk pv' r')
substF (Node3 l pk pv m qk qv r) = do
l' <- substP l
pv' <- traverse (traverse substP) pv
m' <- substP m
qv' <- traverse (traverse substP) qv
r' <- substP r
write (Node3 l' pk pv' m' qk qv' r')
substF (Bin t p l r) = do
l' <- substP l
r' <- substP r
write (Bin t p l' r')
substF (Tip t p) = write (Tip t p)
writeFooter offset1 $ substF root'
return ((), a)
`onException` writeFooter offset0 (write root)
where
writeFooter ofs m = do
modified <- readIORef (refModified h)
when modified $ do
hSeek h' SeekFromEnd 0
RP _ len <- evalStateT m ofs
B.hPutStr h' $ B.drop len emptyFooter
hFlush h'
writeIORef (refModified h) False
h' = hPayload h
write :: Node RawPointer -> StateT Int IO RawPointer
write f = do
ofs <- get
let e = encodeNode f
len <- liftIO $ hPutBuilderLen h' e
put $! ofs + len
return $ RP ofs len
fetchKeyT :: KeyPointer -> Transaction Key
fetchKeyT p = gets dbHandle >>= \h -> liftIO (fetchKey h p)
fetchStage :: StagePointer -> Transaction (Node StagePointer)
fetchStage (Commited p) = do
h <- gets dbHandle
liftIO $ fmap Commited <$> fetchNode h p
fetchStage (Uncommited f) = pure f
insertF :: Key
-> (Spine StagePointer -> Transaction (Spine StagePointer))
-> Node StagePointer
-> Transaction (Result StagePointer)
insertF k u Empty = Pure <$> (Leaf1 <$> allocKey k <*> u [])
insertF k u (Leaf1 pk pv) = do
vpk <- fetchKeyT pk
Pure <$> case compare k vpk of
LT -> do
kp <- allocKey k
(\v -> Leaf2 kp v pk pv) <$> u []
EQ -> Leaf1 pk <$> u pv
GT -> do
kp <- allocKey k
Leaf2 pk pv kp <$> u []
insertF k u (Leaf2 pk pv qk qv) = do
vpk <- fetchKeyT pk
case compare k vpk of
LT -> do
v <- u []
kp <- allocKey k
let l = Uncommited $ Leaf1 kp v
let r = Uncommited $ Leaf1 qk qv
return $ Carry l pk pv r
EQ -> do
v <- u pv
return $ Pure $ Leaf2 pk v qk qv
GT -> do
vqk <- fetchKeyT qk
case compare k vqk of
LT -> do
v <- u []
let l = Uncommited $ Leaf1 pk pv
let r = Uncommited $ Leaf1 qk qv
kp <- allocKey k
return $ Carry l kp v r
EQ -> do
v <- u qv
return $ Pure $ Leaf2 pk pv qk v
GT -> do
v <- u []
kp <- allocKey k
let l = Uncommited $ Leaf1 pk pv
let r = Uncommited $ Leaf1 kp v
return $ Carry l qk qv r
insertF k u (Node2 l pk0 pv0 r) = do
vpk0 <- fetchKeyT pk0
case compare k vpk0 of
LT -> do
fl <- fetchStage l
insertF k u fl >>= \case
Pure l' -> do
let l'' = Uncommited $ l'
return $ Pure $ Node2 l'' pk0 pv0 r
Carry l' ck cv r' -> return $ Pure $ Node3 l' ck cv r' pk0 pv0 r
EQ -> do
v <- u pv0
return $ Pure $ Node2 l pk0 v r
GT -> do
fr <- fetchStage r
insertF k u fr >>= \case
Pure r' -> do
let r'' = Uncommited $ r'
return $ Pure $ Node2 l pk0 pv0 r''
Carry l' ck cv r' -> return $ Pure $ Node3 l pk0 pv0 l' ck cv r'
insertF k u (Node3 l pk0 pv0 m qk0 qv0 r) = do
vpk0 <- fetchKeyT pk0
case compare k vpk0 of
LT -> do
fl <- fetchStage l
insertF k u fl >>= \case
Pure l' -> do
let l'' = Uncommited $ l'
return $ Pure $ Node3 l'' pk0 pv0 m qk0 qv0 r
Carry l' ck cv r' -> do
let bl = Uncommited (Node2 l' ck cv r')
let br = Uncommited (Node2 m qk0 qv0 r)
return $ Pure $ Node2 bl pk0 pv0 br
EQ -> do
v <- u pv0
return $ Pure $ Node3 l pk0 v m qk0 qv0 r
GT -> do
vqk0 <- fetchKeyT qk0
case compare k vqk0 of
LT -> do
fm <- fetchStage m
insertF k u fm >>= \case
Pure m' -> do
let m'' = Uncommited $ m'
return $ Pure $ Node3 l pk0 pv0 m'' qk0 qv0 r
Carry l' ck cv r' -> do
let bl = Uncommited $ Node2 l pk0 pv0 l'
let br = Uncommited $ Node2 r' qk0 qv0 r
return $ Pure $ Node2 bl ck cv br
EQ -> do
v <- u qv0
return $ Pure $ Node3 l pk0 pv0 m qk0 v r
GT -> do
fr <- fetchStage r
insertF k u fr >>= \case
Pure r' -> do
let r'' = Uncommited $ r'
return $ Pure $ Node3 l pk0 pv0 m qk0 qv0 r''
Carry l' ck cv r' -> do
let bl = Uncommited $ Node2 l pk0 pv0 m
let br = Uncommited $ Node2 l' ck cv r'
return $ Pure $ Node2 bl qk0 qv0 br
insertF _ _ (Bin _ _ _ _) = fail "Unexpected Tree"
insertF _ _ (Tip _ _) = fail "Unexpected Leaf"
data Result a = Pure (Node a)
| Carry !a !KeyPointer !(Spine a) !a
insertSpine :: Tag -> RawPointer -> Spine StagePointer -> Transaction (Spine StagePointer)
insertSpine tag p ((m, x) : (n, y) : ss) | m == n = do
let t = Uncommited $ Bin tag p x y
return $ (2 * m + 1, t) : ss
insertSpine tag p ss = do
let t = Uncommited $ Tip tag p
return $ (1, t) : ss
--------------------------------------------------------------------------------
-- Fetching
class Fetchable a where
fetchNode :: a -> RawPointer -> IO (Node RawPointer)
fetchKey :: a -> KeyPointer -> IO Key
fetchRoot :: a -> IO (Node RawPointer)
fetchPayload :: a -> RawPointer -> IO B.ByteString
instance Fetchable LisztHandle where
fetchNode h (RP ofs len) = fetchNode'
(hSeek (hPayload h) AbsoluteSeek (fromIntegral ofs)) h len
fetchKey LisztHandle{..} (KeyPointer (RP ofs len)) = do
cache <- readIORef keyCache
case IM.lookup ofs cache of
Just key -> return key
Nothing -> do
hSeek hPayload AbsoluteSeek (fromIntegral ofs)
key <- Key <$> B.hGet hPayload len
modifyIORef' keyCache (IM.insert ofs key)
return key
fetchRoot h = fetchNode'
(hSeek (hPayload h) SeekFromEnd (-fromIntegral footerSize)) h footerSize
fetchPayload LisztHandle{..} (RP ofs len) = do
hSeek hPayload AbsoluteSeek (fromIntegral ofs)
B.hGet hPayload len
fetchNode' :: IO () -> LisztHandle -> Int -> IO (Node RawPointer)
fetchNode' seek h len = modifyMVar (refBuffer h) $ \(blen, buf) -> do
seek
(blen', buf') <- if blen < len
then do
buf' <- B.mallocByteString len
return (len, buf')
else return (blen, buf)
f <- withForeignPtr buf' $ \ptr -> do
_ <- hGetBuf (hPayload h) ptr len
peekNode ptr
return ((blen', buf'), f)
{-# INLINE fetchNode' #-}
lookupSpine :: Fetchable a => a -> Key -> Node RawPointer -> IO (Maybe (Spine RawPointer))
lookupSpine h k (Leaf1 p v) = do
vp <- fetchKey h p
if k == vp then return (Just v) else return Nothing
lookupSpine h k (Leaf2 p u q v) = do
vp <- fetchKey h p
if k == vp then return (Just u) else do
vq <- fetchKey h q
return $ if k == vq then Just v else Nothing
lookupSpine h k (Node2 l p v r) = do
vp <- fetchKey h p
case compare k vp of
LT -> fetchNode h l >>= lookupSpine h k
EQ -> return (Just v)
GT -> fetchNode h r >>= lookupSpine h k
lookupSpine h k (Node3 l p u m q v r) = do
vp <- fetchKey h p
case compare k vp of
LT -> fetchNode h l >>= lookupSpine h k
EQ -> return (Just u)
GT -> do
vq <- fetchKey h q
case compare k vq of
LT -> fetchNode h m >>= lookupSpine h k
EQ -> return (Just v)
GT -> fetchNode h r >>= lookupSpine h k
lookupSpine _ _ _ = return Nothing
traverseNode :: (MonadIO m, Fetchable a) => a -> (Key -> Spine RawPointer -> m ()) -> Node RawPointer -> m ()
traverseNode h f = go where
go (Leaf1 p v) = do
vp <- liftIO $ fetchKey h p
f vp v
go (Leaf2 p u q v) = do
vp <- liftIO $ fetchKey h p
f vp u
vq <- liftIO $ fetchKey h q
f vq v
go (Node2 l p v r) = do
liftIO (fetchNode h l) >>= go
vp <- liftIO $ fetchKey h p
f vp v
liftIO (fetchNode h r) >>= go
go (Node3 l p u m q v r) = do
liftIO (fetchNode h l) >>= go
vp <- liftIO $ fetchKey h p
f vp u
liftIO (fetchNode h m) >>= go
vq <- liftIO $ fetchKey h q
f vq v
liftIO (fetchNode h r) >>= go
go _ = pure ()
availableKeys :: Fetchable a => a -> Node RawPointer -> IO [Key]
availableKeys _ Empty = return []
availableKeys h (Leaf1 k _) = pure <$> fetchKey h k
availableKeys h (Leaf2 j _ k _) = sequence [fetchKey h j, fetchKey h k]
availableKeys h (Node2 l k _ r) = do
lks <- fetchNode h l >>= availableKeys h
vk <- fetchKey h k
rks <- fetchNode h r >>= availableKeys h
return $ lks ++ vk : rks
availableKeys h (Node3 l j _ m k _ r) = do
lks <- fetchNode h l >>= availableKeys h
vj <- fetchKey h j
mks <- fetchNode h m >>= availableKeys h
vk <- fetchKey h k
rks <- fetchNode h r >>= availableKeys h
return $ lks ++ vj : mks ++ vk : rks
availableKeys _ _ = fail "availableKeys: unexpected frame"
--------------------------------------------------------------------------------
-- Footer (root node)
footerSize :: Int
footerSize = 256
emptyFooter :: B.ByteString
emptyFooter = B.pack [0,14,171,160,140,150,185,18,22,70,203,145,129,232,42,76,81,176,163,195,96,209,8,74,97,123,57,136,107,174,241,142,100,164,181,138,253,170,25,77,12,191,212,224,142,167,215,73,48,0,2,170,226,114,8,29,141,85,243,179,81,11,59,246,62,189,202,254,56,140,227,195,189,118,152,26,106,81,4,121,152,72,247,119,111,128,75,242,29,96,157,190,170,1,57,77,61,132,72,8,233,94,254,18,197,152,128,15,174,9,91,78,125,21,72,250,179,176,176,47,230,45,255,228,214,223,28,61,123,159,104,233,131,39,88,245,13,242,228,48,17,119,159,173,71,172,238,69,137,141,153,133,79,24,81,242,19,21,209,44,120,69,180,103,100,185,189,191,50,132,52,229,248,12,207,134,45,241,2,217,112,21,239,65,39,30,33,16,147,152,52,204,221,56,87,191,235,235,173,181,106,165,37,52,245,221,13,80,91,207,224,95,157,222,3,210,54,28,99,1,7,50,189,163,141,244,200,101,250,61,48,10,243,248,153,98,224,73,227,121,72,156,228,205,43,82,166,48,85,132,0,76,73,83,90,84]
isFooter :: B.ByteString -> Bool
isFooter bs = B.drop (footerSize - 64) bs == B.drop (footerSize - 64) emptyFooter
--------------------------------------------------------------------------------
-- Spine operations
spineLength :: Spine a -> Int
spineLength = sum . map fst
type QueryResult = (Tag, RawPointer)
dropSpine :: Fetchable a => a -> Int -> Spine RawPointer -> IO (Spine RawPointer)
dropSpine _ _ [] = return []
dropSpine _ 0 s = return s
dropSpine h n0 ((siz0, t0) : xs0)
| siz0 <= n0 = dropSpine h (n0 - siz0) xs0
| otherwise = dropBin n0 siz0 t0 xs0
where
dropBin 0 siz t xs = return $ (siz, t) : xs
dropBin n siz t xs = fetchNode h t >>= \case
Bin _ _ l r
| n == 1 -> return $ (siz', l) : (siz', r) : xs
| n <= siz' -> dropBin (n - 1) siz' l ((siz', r) : xs)
| otherwise -> dropBin (n - siz' - 1) siz' r xs
Tip _ _ -> return xs
_ -> error $ "dropTree: unexpected frame"
where
siz' = siz `div` 2
takeSpine :: Fetchable a => a -> Int -> Spine RawPointer -> [QueryResult] -> IO [QueryResult]
takeSpine _ n _ ps | n <= 0 = return ps
takeSpine _ _ [] ps = return ps
takeSpine h n ((siz, t) : xs) ps
| n >= siz = takeAll h t ps >>= takeSpine h (n - siz) xs
| otherwise = takeBin h n siz t ps
takeBin :: Fetchable a => a -> Int -> Int -> RawPointer -> [QueryResult] -> IO [QueryResult]
takeBin _ n _ _ ps | n <= 0 = return ps
takeBin h n siz t ps = fetchNode h t >>= \case
Bin tag p l r
| n == 1 -> return $ (tag, p) : ps
| n <= siz' -> takeBin h (n - 1) siz' l ((tag, p) : ps)
| otherwise -> do
ps' <- takeAll h l ((tag, p) : ps)
takeBin h (n - siz' - 1) siz' r ps'
Tip tag p -> return $ (tag, p) : ps
_ -> error $ "takeTree: unexpected frame"
where
siz' = siz `div` 2
wholeSpine :: Fetchable a => a -> Spine RawPointer -> [QueryResult] -> IO [QueryResult]
wholeSpine h ((_, s) : ss) r = wholeSpine h ss r >>= takeAll h s
wholeSpine _ [] r = return r
takeAll :: Fetchable a => a -> RawPointer -> [QueryResult] -> IO [QueryResult]
takeAll h t ps = fetchNode h t >>= \case
Bin tag p l r -> takeAll h l ((tag, p) : ps) >>= takeAll h r
Tip tag p -> return ((tag, p) : ps)
_ -> error $ "takeAll: unexpected frame"
takeSpineWhile :: Fetchable a
=> (Tag -> Bool)
-> a
-> Spine RawPointer
-> [QueryResult] -> IO [QueryResult]
takeSpineWhile cond h = go where
go (t0 : ((siz, t) : xs)) ps = fetchNode h t >>= \case
Tip tag p
| cond tag -> takeAll h (snd t0) ps >>= go xs . ((tag, p):)
| otherwise -> inner t0 ps
Bin tag p l r
| cond tag -> takeAll h (snd t0) ps
>>= go ((siz', l) : (siz', r) : xs) . ((tag, p):)
| otherwise -> inner t0 ps
_ -> error "takeSpineWhile: unexpected frame"
where
siz' = siz `div` 2
go [t] ps = inner t ps
go [] ps = return ps
inner (siz, t) ps = fetchNode h t >>= \case
Tip tag p
| cond tag -> return $ (tag, p) : ps
| otherwise -> return ps
Bin tag p l r
| cond tag -> go [(siz', l), (siz', r)] ((tag, p) : ps)
| otherwise -> return ps
_ -> error "takeSpineWhile: unexpected frame"
where
siz' = siz `div` 2
dropSpineWhile :: Fetchable a
=> (Tag -> Bool)
-> a
-> Spine RawPointer
-> IO (Maybe (Int, QueryResult, Spine RawPointer))
dropSpineWhile cond h = go 0 where
go !total (t0@(siz0, _) : ts@((siz, t) : xs)) = fetchNode h t >>= \case
Tip tag _
| cond tag -> go (total + siz0 + siz) xs
| otherwise -> dropBin total t0 ts
Bin tag _ l r
| cond tag -> go (total + siz0 + 1) $ (siz', l) : (siz', r) : xs
| otherwise -> dropBin total t0 ts
_ -> error "dropSpineWhile: unexpected frame"
where
siz' = siz `div` 2
go total (t : ts) = dropBin total t ts
go _ [] = return Nothing
dropBin !total (siz, t) ts = fetchNode h t >>= \case
Tip tag p
| cond tag -> go (total + 1) ts
| otherwise -> return $ Just (total, (tag, p), ts)
Bin tag p l r
| cond tag -> go (total + 1) $ (siz', l) : (siz', r) : ts
| otherwise -> return $ Just (total, (tag, p), (siz', l) : (siz', r) : ts)
_ -> error "dropSpineWhile: unexpected frame"
where
siz' = siz `div` 2
| null | https://raw.githubusercontent.com/fumieval/liszt/44195372034b397a5a109899330995fba0152e1b/src/Database/Liszt/Internal.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE RankNTypes #
* Writing
* Reading
* Node
* Fetching
* Footer
* Node
* Spine
| Tag is an extra value attached to a payload. This can be used to perform
a binary search.
------------------------------------------------------------------------------
Transaction
| Replace the specified key with an empty list.
------------------------------------------------------------------------------
Fetching
# INLINE fetchNode' #
------------------------------------------------------------------------------
Footer (root node)
------------------------------------------------------------------------------
Spine operations | # LANGUAGE LambdaCase , DeriveTraversable , DeriveGeneric #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE RecordWildCards #
module Database.Liszt.Internal (
Key(..)
, Tag
, LisztHandle(..)
, openLiszt
, closeLiszt
, withLiszt
, clear
, insertRaw
, commit
, Transaction
, TransactionState
, availableKeys
, Node(..)
, peekNode
, LisztDecodingException(..)
, Fetchable(..)
, KeyPointer(..)
, RawPointer(..)
, footerSize
, isFooter
, lookupSpine
, traverseNode
, Spine
, spineLength
, QueryResult
, wholeSpine
, takeSpine
, dropSpine
, takeSpineWhile
, dropSpineWhile
) where
import Control.Concurrent
import Control.DeepSeq
import Control.Monad
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Trans.State.Strict
import qualified Data.Aeson as J
import Data.Bifunctor
import qualified Data.ByteString as B
import qualified Data.ByteString.Internal as B
import qualified Data.IntMap.Strict as IM
import Data.IORef
import Data.Monoid
import Data.Word
import Data.String
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Mason.Builder
import Database.Liszt.Internal.Decoder
import Foreign.ForeignPtr
import Foreign.Ptr
import GHC.Generics (Generic)
import System.Directory
import System.IO
newtype Key = Key { unKey :: B.ByteString } deriving (Eq, Ord)
instance Show Key where
show = show . T.decodeUtf8 . unKey
instance IsString Key where
fromString = Key . T.encodeUtf8 . T.pack
instance J.FromJSON Key where
parseJSON obj = Key . T.encodeUtf8 <$> J.parseJSON obj
instance J.ToJSON Key where
toJSON = J.toJSON . T.decodeUtf8 . unKey
type Tag = B.ByteString
type Spine a = [(Int, a)]
newtype KeyPointer = KeyPointer RawPointer deriving (Show, Eq, NFData)
data RawPointer = RP !Int !Int deriving (Show, Eq, Generic)
instance NFData RawPointer where
rnf r = r `seq` ()
data Node a = Empty
| Leaf1 !KeyPointer !(Spine a)
| Leaf2 !KeyPointer !(Spine a) !KeyPointer !(Spine a)
| Node2 !a !KeyPointer !(Spine a) !a
| Node3 !a !KeyPointer !(Spine a) !a !KeyPointer !(Spine a) !a
| Tip !Tag !RawPointer
| Bin !Tag !RawPointer !a !a
deriving (Generic, Show, Eq, Functor, Foldable, Traversable)
encodeUInt :: Int -> Builder
encodeUInt = wordVLQ . fromIntegral
encodeNode :: Node RawPointer -> Builder
encodeNode Empty = word8 0x00
encodeNode (Leaf1 (KeyPointer p) s) = word8 0x01 <> encodeRP p <> encodeSpine s
encodeNode (Leaf2 (KeyPointer p) s (KeyPointer q) t) = word8 0x02
<> encodeRP p <> encodeSpine s <> encodeRP q <> encodeSpine t
encodeNode (Node2 l (KeyPointer p) s r) = word8 0x12
<> encodeRP l <> encodeRP p <> encodeSpine s <> encodeRP r
encodeNode (Node3 l (KeyPointer p) s m (KeyPointer q) t r) = word8 0x13
<> encodeRP l <> encodeRP p <> encodeSpine s
<> encodeRP m <> encodeRP q <> encodeSpine t <> encodeRP r
encodeNode (Tip t p) = word8 0x80 <> encodeUInt (B.length t) <> byteString t <> encodeRP p
encodeNode (Bin t p l r) = word8 0x81 <> encodeUInt (B.length t) <> byteString t
<> encodeRP p <> encodeRP l <> encodeRP r
encodeRP :: RawPointer -> Builder
encodeRP (RP p l) = encodeUInt p <> encodeUInt l
encodeSpine :: Spine RawPointer -> Builder
encodeSpine s = encodeUInt (length s) <> foldMap (\(r, p) -> encodeUInt r <> encodeRP p) s
data LisztDecodingException = LisztDecodingException deriving Show
instance Exception LisztDecodingException
peekNode :: Ptr Word8 -> IO (Node RawPointer)
peekNode = runDecoder $ decodeWord8 >>= \case
0x00 -> return Empty
0x01 -> Leaf1 <$> kp <*> spine
0x02 -> Leaf2 <$> kp <*> spine <*> kp <*> spine
0x12 -> Node2 <$> rp <*> kp <*> spine <*> rp
0x13 -> Node3 <$> rp <*> kp <*> spine <*> rp <*> kp <*> spine <*> rp
0x80 -> Tip <$> bs <*> rp
0x81 -> Bin <$> bs <*> rp <*> rp <*> rp
_ -> throwM LisztDecodingException
where
kp = fmap KeyPointer rp
rp = RP <$> decodeVarInt <*> decodeVarInt
spine = do
len <- decodeVarInt
replicateM len $ (,) <$> decodeVarInt <*> rp
bs = do
len <- decodeVarInt
Decoder $ \src -> do
fp <- B.mallocByteString len
withForeignPtr fp $ \dst -> B.memcpy dst src len
return $ DecodeResult (src `plusPtr` len) (B.PS fp 0 len)
data LisztHandle = LisztHandle
{ hPayload :: !Handle
, refBuffer :: MVar (Int, ForeignPtr Word8)
, keyCache :: IORef (IM.IntMap Key)
, refModified :: IORef Bool
, handleLock :: MVar ()
}
openLiszt :: MonadIO m => FilePath -> m LisztHandle
openLiszt path = liftIO $ do
exist <- doesFileExist path
hPayload <- openBinaryFile path ReadWriteMode
unless exist $ B.hPutStr hPayload emptyFooter
buf <- B.mallocByteString 4096
refBuffer <- newMVar (4096, buf)
keyCache <- newIORef IM.empty
handleLock <- newMVar ()
refModified <- newIORef False
return LisztHandle{..}
closeLiszt :: MonadIO m => LisztHandle -> m ()
closeLiszt lh = liftIO $ hClose $ hPayload lh
withLiszt :: (MonadIO m, MonadMask m) => FilePath -> (LisztHandle -> m a) -> m a
withLiszt path = bracket (openLiszt path) closeLiszt
data StagePointer = Commited !RawPointer | Uncommited !(Node StagePointer) deriving Eq
data TransactionState = TS
{ dbHandle :: !LisztHandle
, currentRoot :: !(Node StagePointer)
, currentPos :: !Int
}
type Transaction = StateT TransactionState IO
clear :: Key -> Transaction ()
clear key = do
root <- gets currentRoot
insertF key (const $ return []) root >>= \case
Pure t -> modify $ \ts -> ts { currentRoot = t }
Carry l k a r -> modify $ \ts -> ts { currentRoot = Node2 l k a r }
append :: LisztHandle -> (Handle -> IO a) -> IO a
append LisztHandle{..} cont = do
hSeek hPayload SeekFromEnd 0
writeIORef refModified True
cont hPayload
insertRaw :: Key -> Tag -> BuilderFor BufferedIOBackend -> Transaction ()
insertRaw key tag payload = do
lh <- gets dbHandle
ofs <- gets currentPos
len <- liftIO $ append lh $ \h -> hPutBuilderLen h payload
root <- gets currentRoot
modify $ \ts -> ts { currentPos = ofs + len }
insertF key (insertSpine tag (ofs `RP` len)) root >>= \case
Pure t -> modify $ \ts -> ts { currentRoot = t }
Carry l k a r -> modify $ \ts -> ts { currentRoot = Node2 l k a r }
allocKey :: Key -> Transaction KeyPointer
allocKey (Key key) = do
lh <- gets dbHandle
ofs <- gets currentPos
liftIO $ append lh $ \h -> do
B.hPutStr h key
modifyIORef' (keyCache lh) (IM.insert ofs (Key key))
modify $ \ts -> ts { currentPos = ofs + B.length key }
return $ KeyPointer $ RP ofs (B.length key)
commit :: MonadIO m => LisztHandle -> Transaction a -> m a
commit h transaction = liftIO $ modifyMVar (handleLock h) $ const $ do
offset0 <- fromIntegral <$> hFileSize h'
root <- fetchRoot h
do
(a, TS _ root' offset1) <- runStateT transaction
$ TS h (fmap Commited root) offset0
let substP :: StagePointer -> StateT Int IO RawPointer
substP (Commited ofs) = return ofs
substP (Uncommited f) = substF f
substF :: Node StagePointer -> StateT Int IO RawPointer
substF Empty = return (RP 0 0)
substF (Leaf1 pk pv) = do
pv' <- traverse (traverse substP) pv
write (Leaf1 pk pv')
substF (Leaf2 pk pv qk qv) = do
pv' <- traverse (traverse substP) pv
qv' <- traverse (traverse substP) qv
write (Leaf2 pk pv' qk qv')
substF (Node2 l pk pv r) = do
l' <- substP l
pv' <- traverse (traverse substP) pv
r' <- substP r
write (Node2 l' pk pv' r')
substF (Node3 l pk pv m qk qv r) = do
l' <- substP l
pv' <- traverse (traverse substP) pv
m' <- substP m
qv' <- traverse (traverse substP) qv
r' <- substP r
write (Node3 l' pk pv' m' qk qv' r')
substF (Bin t p l r) = do
l' <- substP l
r' <- substP r
write (Bin t p l' r')
substF (Tip t p) = write (Tip t p)
writeFooter offset1 $ substF root'
return ((), a)
`onException` writeFooter offset0 (write root)
where
writeFooter ofs m = do
modified <- readIORef (refModified h)
when modified $ do
hSeek h' SeekFromEnd 0
RP _ len <- evalStateT m ofs
B.hPutStr h' $ B.drop len emptyFooter
hFlush h'
writeIORef (refModified h) False
h' = hPayload h
write :: Node RawPointer -> StateT Int IO RawPointer
write f = do
ofs <- get
let e = encodeNode f
len <- liftIO $ hPutBuilderLen h' e
put $! ofs + len
return $ RP ofs len
fetchKeyT :: KeyPointer -> Transaction Key
fetchKeyT p = gets dbHandle >>= \h -> liftIO (fetchKey h p)
fetchStage :: StagePointer -> Transaction (Node StagePointer)
fetchStage (Commited p) = do
h <- gets dbHandle
liftIO $ fmap Commited <$> fetchNode h p
fetchStage (Uncommited f) = pure f
insertF :: Key
-> (Spine StagePointer -> Transaction (Spine StagePointer))
-> Node StagePointer
-> Transaction (Result StagePointer)
insertF k u Empty = Pure <$> (Leaf1 <$> allocKey k <*> u [])
insertF k u (Leaf1 pk pv) = do
vpk <- fetchKeyT pk
Pure <$> case compare k vpk of
LT -> do
kp <- allocKey k
(\v -> Leaf2 kp v pk pv) <$> u []
EQ -> Leaf1 pk <$> u pv
GT -> do
kp <- allocKey k
Leaf2 pk pv kp <$> u []
insertF k u (Leaf2 pk pv qk qv) = do
vpk <- fetchKeyT pk
case compare k vpk of
LT -> do
v <- u []
kp <- allocKey k
let l = Uncommited $ Leaf1 kp v
let r = Uncommited $ Leaf1 qk qv
return $ Carry l pk pv r
EQ -> do
v <- u pv
return $ Pure $ Leaf2 pk v qk qv
GT -> do
vqk <- fetchKeyT qk
case compare k vqk of
LT -> do
v <- u []
let l = Uncommited $ Leaf1 pk pv
let r = Uncommited $ Leaf1 qk qv
kp <- allocKey k
return $ Carry l kp v r
EQ -> do
v <- u qv
return $ Pure $ Leaf2 pk pv qk v
GT -> do
v <- u []
kp <- allocKey k
let l = Uncommited $ Leaf1 pk pv
let r = Uncommited $ Leaf1 kp v
return $ Carry l qk qv r
insertF k u (Node2 l pk0 pv0 r) = do
vpk0 <- fetchKeyT pk0
case compare k vpk0 of
LT -> do
fl <- fetchStage l
insertF k u fl >>= \case
Pure l' -> do
let l'' = Uncommited $ l'
return $ Pure $ Node2 l'' pk0 pv0 r
Carry l' ck cv r' -> return $ Pure $ Node3 l' ck cv r' pk0 pv0 r
EQ -> do
v <- u pv0
return $ Pure $ Node2 l pk0 v r
GT -> do
fr <- fetchStage r
insertF k u fr >>= \case
Pure r' -> do
let r'' = Uncommited $ r'
return $ Pure $ Node2 l pk0 pv0 r''
Carry l' ck cv r' -> return $ Pure $ Node3 l pk0 pv0 l' ck cv r'
insertF k u (Node3 l pk0 pv0 m qk0 qv0 r) = do
vpk0 <- fetchKeyT pk0
case compare k vpk0 of
LT -> do
fl <- fetchStage l
insertF k u fl >>= \case
Pure l' -> do
let l'' = Uncommited $ l'
return $ Pure $ Node3 l'' pk0 pv0 m qk0 qv0 r
Carry l' ck cv r' -> do
let bl = Uncommited (Node2 l' ck cv r')
let br = Uncommited (Node2 m qk0 qv0 r)
return $ Pure $ Node2 bl pk0 pv0 br
EQ -> do
v <- u pv0
return $ Pure $ Node3 l pk0 v m qk0 qv0 r
GT -> do
vqk0 <- fetchKeyT qk0
case compare k vqk0 of
LT -> do
fm <- fetchStage m
insertF k u fm >>= \case
Pure m' -> do
let m'' = Uncommited $ m'
return $ Pure $ Node3 l pk0 pv0 m'' qk0 qv0 r
Carry l' ck cv r' -> do
let bl = Uncommited $ Node2 l pk0 pv0 l'
let br = Uncommited $ Node2 r' qk0 qv0 r
return $ Pure $ Node2 bl ck cv br
EQ -> do
v <- u qv0
return $ Pure $ Node3 l pk0 pv0 m qk0 v r
GT -> do
fr <- fetchStage r
insertF k u fr >>= \case
Pure r' -> do
let r'' = Uncommited $ r'
return $ Pure $ Node3 l pk0 pv0 m qk0 qv0 r''
Carry l' ck cv r' -> do
let bl = Uncommited $ Node2 l pk0 pv0 m
let br = Uncommited $ Node2 l' ck cv r'
return $ Pure $ Node2 bl qk0 qv0 br
insertF _ _ (Bin _ _ _ _) = fail "Unexpected Tree"
insertF _ _ (Tip _ _) = fail "Unexpected Leaf"
data Result a = Pure (Node a)
| Carry !a !KeyPointer !(Spine a) !a
insertSpine :: Tag -> RawPointer -> Spine StagePointer -> Transaction (Spine StagePointer)
insertSpine tag p ((m, x) : (n, y) : ss) | m == n = do
let t = Uncommited $ Bin tag p x y
return $ (2 * m + 1, t) : ss
insertSpine tag p ss = do
let t = Uncommited $ Tip tag p
return $ (1, t) : ss
class Fetchable a where
fetchNode :: a -> RawPointer -> IO (Node RawPointer)
fetchKey :: a -> KeyPointer -> IO Key
fetchRoot :: a -> IO (Node RawPointer)
fetchPayload :: a -> RawPointer -> IO B.ByteString
instance Fetchable LisztHandle where
fetchNode h (RP ofs len) = fetchNode'
(hSeek (hPayload h) AbsoluteSeek (fromIntegral ofs)) h len
fetchKey LisztHandle{..} (KeyPointer (RP ofs len)) = do
cache <- readIORef keyCache
case IM.lookup ofs cache of
Just key -> return key
Nothing -> do
hSeek hPayload AbsoluteSeek (fromIntegral ofs)
key <- Key <$> B.hGet hPayload len
modifyIORef' keyCache (IM.insert ofs key)
return key
fetchRoot h = fetchNode'
(hSeek (hPayload h) SeekFromEnd (-fromIntegral footerSize)) h footerSize
fetchPayload LisztHandle{..} (RP ofs len) = do
hSeek hPayload AbsoluteSeek (fromIntegral ofs)
B.hGet hPayload len
fetchNode' :: IO () -> LisztHandle -> Int -> IO (Node RawPointer)
fetchNode' seek h len = modifyMVar (refBuffer h) $ \(blen, buf) -> do
seek
(blen', buf') <- if blen < len
then do
buf' <- B.mallocByteString len
return (len, buf')
else return (blen, buf)
f <- withForeignPtr buf' $ \ptr -> do
_ <- hGetBuf (hPayload h) ptr len
peekNode ptr
return ((blen', buf'), f)
lookupSpine :: Fetchable a => a -> Key -> Node RawPointer -> IO (Maybe (Spine RawPointer))
lookupSpine h k (Leaf1 p v) = do
vp <- fetchKey h p
if k == vp then return (Just v) else return Nothing
lookupSpine h k (Leaf2 p u q v) = do
vp <- fetchKey h p
if k == vp then return (Just u) else do
vq <- fetchKey h q
return $ if k == vq then Just v else Nothing
lookupSpine h k (Node2 l p v r) = do
vp <- fetchKey h p
case compare k vp of
LT -> fetchNode h l >>= lookupSpine h k
EQ -> return (Just v)
GT -> fetchNode h r >>= lookupSpine h k
lookupSpine h k (Node3 l p u m q v r) = do
vp <- fetchKey h p
case compare k vp of
LT -> fetchNode h l >>= lookupSpine h k
EQ -> return (Just u)
GT -> do
vq <- fetchKey h q
case compare k vq of
LT -> fetchNode h m >>= lookupSpine h k
EQ -> return (Just v)
GT -> fetchNode h r >>= lookupSpine h k
lookupSpine _ _ _ = return Nothing
traverseNode :: (MonadIO m, Fetchable a) => a -> (Key -> Spine RawPointer -> m ()) -> Node RawPointer -> m ()
traverseNode h f = go where
go (Leaf1 p v) = do
vp <- liftIO $ fetchKey h p
f vp v
go (Leaf2 p u q v) = do
vp <- liftIO $ fetchKey h p
f vp u
vq <- liftIO $ fetchKey h q
f vq v
go (Node2 l p v r) = do
liftIO (fetchNode h l) >>= go
vp <- liftIO $ fetchKey h p
f vp v
liftIO (fetchNode h r) >>= go
go (Node3 l p u m q v r) = do
liftIO (fetchNode h l) >>= go
vp <- liftIO $ fetchKey h p
f vp u
liftIO (fetchNode h m) >>= go
vq <- liftIO $ fetchKey h q
f vq v
liftIO (fetchNode h r) >>= go
go _ = pure ()
availableKeys :: Fetchable a => a -> Node RawPointer -> IO [Key]
availableKeys _ Empty = return []
availableKeys h (Leaf1 k _) = pure <$> fetchKey h k
availableKeys h (Leaf2 j _ k _) = sequence [fetchKey h j, fetchKey h k]
availableKeys h (Node2 l k _ r) = do
lks <- fetchNode h l >>= availableKeys h
vk <- fetchKey h k
rks <- fetchNode h r >>= availableKeys h
return $ lks ++ vk : rks
availableKeys h (Node3 l j _ m k _ r) = do
lks <- fetchNode h l >>= availableKeys h
vj <- fetchKey h j
mks <- fetchNode h m >>= availableKeys h
vk <- fetchKey h k
rks <- fetchNode h r >>= availableKeys h
return $ lks ++ vj : mks ++ vk : rks
availableKeys _ _ = fail "availableKeys: unexpected frame"
footerSize :: Int
footerSize = 256
emptyFooter :: B.ByteString
emptyFooter = B.pack [0,14,171,160,140,150,185,18,22,70,203,145,129,232,42,76,81,176,163,195,96,209,8,74,97,123,57,136,107,174,241,142,100,164,181,138,253,170,25,77,12,191,212,224,142,167,215,73,48,0,2,170,226,114,8,29,141,85,243,179,81,11,59,246,62,189,202,254,56,140,227,195,189,118,152,26,106,81,4,121,152,72,247,119,111,128,75,242,29,96,157,190,170,1,57,77,61,132,72,8,233,94,254,18,197,152,128,15,174,9,91,78,125,21,72,250,179,176,176,47,230,45,255,228,214,223,28,61,123,159,104,233,131,39,88,245,13,242,228,48,17,119,159,173,71,172,238,69,137,141,153,133,79,24,81,242,19,21,209,44,120,69,180,103,100,185,189,191,50,132,52,229,248,12,207,134,45,241,2,217,112,21,239,65,39,30,33,16,147,152,52,204,221,56,87,191,235,235,173,181,106,165,37,52,245,221,13,80,91,207,224,95,157,222,3,210,54,28,99,1,7,50,189,163,141,244,200,101,250,61,48,10,243,248,153,98,224,73,227,121,72,156,228,205,43,82,166,48,85,132,0,76,73,83,90,84]
isFooter :: B.ByteString -> Bool
isFooter bs = B.drop (footerSize - 64) bs == B.drop (footerSize - 64) emptyFooter
spineLength :: Spine a -> Int
spineLength = sum . map fst
type QueryResult = (Tag, RawPointer)
dropSpine :: Fetchable a => a -> Int -> Spine RawPointer -> IO (Spine RawPointer)
dropSpine _ _ [] = return []
dropSpine _ 0 s = return s
dropSpine h n0 ((siz0, t0) : xs0)
| siz0 <= n0 = dropSpine h (n0 - siz0) xs0
| otherwise = dropBin n0 siz0 t0 xs0
where
dropBin 0 siz t xs = return $ (siz, t) : xs
dropBin n siz t xs = fetchNode h t >>= \case
Bin _ _ l r
| n == 1 -> return $ (siz', l) : (siz', r) : xs
| n <= siz' -> dropBin (n - 1) siz' l ((siz', r) : xs)
| otherwise -> dropBin (n - siz' - 1) siz' r xs
Tip _ _ -> return xs
_ -> error $ "dropTree: unexpected frame"
where
siz' = siz `div` 2
takeSpine :: Fetchable a => a -> Int -> Spine RawPointer -> [QueryResult] -> IO [QueryResult]
takeSpine _ n _ ps | n <= 0 = return ps
takeSpine _ _ [] ps = return ps
takeSpine h n ((siz, t) : xs) ps
| n >= siz = takeAll h t ps >>= takeSpine h (n - siz) xs
| otherwise = takeBin h n siz t ps
takeBin :: Fetchable a => a -> Int -> Int -> RawPointer -> [QueryResult] -> IO [QueryResult]
takeBin _ n _ _ ps | n <= 0 = return ps
takeBin h n siz t ps = fetchNode h t >>= \case
Bin tag p l r
| n == 1 -> return $ (tag, p) : ps
| n <= siz' -> takeBin h (n - 1) siz' l ((tag, p) : ps)
| otherwise -> do
ps' <- takeAll h l ((tag, p) : ps)
takeBin h (n - siz' - 1) siz' r ps'
Tip tag p -> return $ (tag, p) : ps
_ -> error $ "takeTree: unexpected frame"
where
siz' = siz `div` 2
wholeSpine :: Fetchable a => a -> Spine RawPointer -> [QueryResult] -> IO [QueryResult]
wholeSpine h ((_, s) : ss) r = wholeSpine h ss r >>= takeAll h s
wholeSpine _ [] r = return r
takeAll :: Fetchable a => a -> RawPointer -> [QueryResult] -> IO [QueryResult]
takeAll h t ps = fetchNode h t >>= \case
Bin tag p l r -> takeAll h l ((tag, p) : ps) >>= takeAll h r
Tip tag p -> return ((tag, p) : ps)
_ -> error $ "takeAll: unexpected frame"
takeSpineWhile :: Fetchable a
=> (Tag -> Bool)
-> a
-> Spine RawPointer
-> [QueryResult] -> IO [QueryResult]
takeSpineWhile cond h = go where
go (t0 : ((siz, t) : xs)) ps = fetchNode h t >>= \case
Tip tag p
| cond tag -> takeAll h (snd t0) ps >>= go xs . ((tag, p):)
| otherwise -> inner t0 ps
Bin tag p l r
| cond tag -> takeAll h (snd t0) ps
>>= go ((siz', l) : (siz', r) : xs) . ((tag, p):)
| otherwise -> inner t0 ps
_ -> error "takeSpineWhile: unexpected frame"
where
siz' = siz `div` 2
go [t] ps = inner t ps
go [] ps = return ps
inner (siz, t) ps = fetchNode h t >>= \case
Tip tag p
| cond tag -> return $ (tag, p) : ps
| otherwise -> return ps
Bin tag p l r
| cond tag -> go [(siz', l), (siz', r)] ((tag, p) : ps)
| otherwise -> return ps
_ -> error "takeSpineWhile: unexpected frame"
where
siz' = siz `div` 2
dropSpineWhile :: Fetchable a
=> (Tag -> Bool)
-> a
-> Spine RawPointer
-> IO (Maybe (Int, QueryResult, Spine RawPointer))
dropSpineWhile cond h = go 0 where
go !total (t0@(siz0, _) : ts@((siz, t) : xs)) = fetchNode h t >>= \case
Tip tag _
| cond tag -> go (total + siz0 + siz) xs
| otherwise -> dropBin total t0 ts
Bin tag _ l r
| cond tag -> go (total + siz0 + 1) $ (siz', l) : (siz', r) : xs
| otherwise -> dropBin total t0 ts
_ -> error "dropSpineWhile: unexpected frame"
where
siz' = siz `div` 2
go total (t : ts) = dropBin total t ts
go _ [] = return Nothing
dropBin !total (siz, t) ts = fetchNode h t >>= \case
Tip tag p
| cond tag -> go (total + 1) ts
| otherwise -> return $ Just (total, (tag, p), ts)
Bin tag p l r
| cond tag -> go (total + 1) $ (siz', l) : (siz', r) : ts
| otherwise -> return $ Just (total, (tag, p), (siz', l) : (siz', r) : ts)
_ -> error "dropSpineWhile: unexpected frame"
where
siz' = siz `div` 2
|
fa08ab781c96e7978dc9da1540e776e0fb5a497b2d276ef7af808f2cde661db0 | geophf/1HaskellADay | Solution.hs | module Y2017.M09.D13.Solution where
import Data.Time
import Data.Time.Clock
import Network.HTTP.Conduit
below imports available via 1HaskellADay git repository
import Y2017.M09.D08.Solution
-
There 's something funny about the article titles of the Y2017.M09.D08.Exercise
Check out the title names .
Ring any bells ? They did to me . These are funny encodings of dates .
Hear me out .
Let 's look at :
-
There's something funny about the article titles of the Y2017.M09.D08.Exercise
Check out the title names.
Ring any bells? They did to me. These are funny encodings of Julian dates.
Hear me out.
Let's look at:
--}
sampleTitle :: FileName
sampleTitle = "AP900327-0242.txt"
-
dateFromJulianDate : : Integer - > Day
dateFromJulianDate jd = undefined
-- hint , you may need to do a bit of research here , as it may require more
-- than the functions provided for by Data . Time . Calendar . Julian
Actually , after looking at this sideways , and realizing something : those
are dates , but not Y2K - compliant . SO , this becomes a bit easier
to recode
-
dateFromJulianDate :: Integer -> Day
dateFromJulianDate jd = undefined
-- hint, you may need to do a bit of research here, as it may require more
-- than the functions provided for by Data.Time.Calendar.Julian
Actually, after looking at this sideways, and realizing something: those
are Gregorian dates, but not Y2K-compliant. SO, this becomes a bit easier
to recode
--}
dateFromString :: String -> UTCTime
dateFromString (y1:y2:m1:m2:d1:d2:_dash:minutes) =
UTCTime (fromGregorian (1900 + fromIntegral (c y1 y2)) (c m1 m2) (c d1 d2))
(secondsToDiffTime (60 * read (take 4 minutes)))
where c x y = read [x,y]
-
Actually , I noted minutes were like 0094 , etc , so I 'm thinkin they are minutes
from midnight : I 'm going with that .
> > > sampleTitle
" AP900327-0242.txt "
> > > dateFromString ( drop 2 sampleTitle )
1990 - 03 - 27 04:02:00
Actually, I noted minutes were like 0094, etc, so I'm thinkin they are minutes
from midnight: I'm going with that.
>>> sampleTitle
"AP900327-0242.txt"
>>> dateFromString (drop 2 sampleTitle)
1990-03-27 04:02:00 UTC
--}
TODAY 'S HASKELL EXERCISE -------------------------------------------------
-- Read in the file names at
articlesDir :: FilePath
articlesDir = "Y2017/M09/D08/articles/b"
and for each article extract the Julian date ( by reading in the first
Integer ) and return the corresponding Day published for that article :
fileNameToDay :: FilePath -> UTCTime
fileNameToDay = dateFromString . drop 2
-
> > > fmap ( map fileNameToDay . filter ( startsWith ' . ' ) ) $ filesAt articlesDir " "
[ 1990 - 03 - 27,1990 - 03 - 27,1990 - 03 - 27,1990 - 03 - 28,1990 - 03 - 28,1990 - 03 - 29,1990 - 03 - 30 ,
1990 - 03 - 30,1990 - 04 - 01,1990 - 04 - 02 ]
So : question !
ARE these hidden dates ?
OR is geophf off his rocker ?
I guess we 'll never know the answer to some questions in life ...
-
>>> fmap (map fileNameToDay . filter (startsWith '.')) $ filesAt articlesDir ""
[1990-03-27,1990-03-27,1990-03-27,1990-03-28,1990-03-28,1990-03-29,1990-03-30,
1990-03-30,1990-04-01,1990-04-02]
So: question!
ARE these hidden Julian dates?
OR is geophf off his rocker?
I guess we'll never know the answer to some questions in life ...
--}
- BONUS -----------------------------------------------------------------
Or , you can use the API call from the US Naval Observatory , e.g. :
-
Or, you can use the API call from the US Naval Observatory, e.g.:
--}
myID :: String
myID = "geophf"
and as a courtesy , email the Navy with your i d and who you are :
navyEmail :: URL
navyEmail = ""
-- they use this to justify their services
jdconverter :: URL
jdconverter = ""
-- call the jdconverter with your id and the jd. What do you get?
-- ... you may get a surprise. Just saying.
-
> > > simpleHttp ( jdconverter + + " ? ID = geophf&jd=900327&format = ) > > = putStrLn
{
" error":false ,
" apiversion":"2.0.0 " ,
" data " : [
{
" jd " : 900327.000000 ,
" month " : 12 ,
" day " : 17 ,
" year " : 2249 ,
" era " : " B.C. " ,
" time " : " 12:00:00.0 " ,
" tz " : 0 ,
" dayofweek " : " Tuesday "
}
]
}
... and you can use Data . Aeson to convert these values .
-
>>> simpleHttp (jdconverter ++ "?ID=geophf&jd=900327&format=json") >>= putStrLn
{
"error":false,
"apiversion":"2.0.0",
"data":[
{
"jd": 900327.000000,
"month": 12,
"day": 17,
"year": 2249,
"era": "B.C.",
"time": "12:00:00.0",
"tz": 0,
"dayofweek" : "Tuesday"
}
]
}
... and you can use Data.Aeson to convert these values.
--}
| null | https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2017/M09/D13/Solution.hs | haskell | }
hint , you may need to do a bit of research here , as it may require more
than the functions provided for by Data . Time . Calendar . Julian
hint, you may need to do a bit of research here, as it may require more
than the functions provided for by Data.Time.Calendar.Julian
}
}
-----------------------------------------------
Read in the file names at
}
---------------------------------------------------------------
}
they use this to justify their services
call the jdconverter with your id and the jd. What do you get?
... you may get a surprise. Just saying.
} | module Y2017.M09.D13.Solution where
import Data.Time
import Data.Time.Clock
import Network.HTTP.Conduit
below imports available via 1HaskellADay git repository
import Y2017.M09.D08.Solution
-
There 's something funny about the article titles of the Y2017.M09.D08.Exercise
Check out the title names .
Ring any bells ? They did to me . These are funny encodings of dates .
Hear me out .
Let 's look at :
-
There's something funny about the article titles of the Y2017.M09.D08.Exercise
Check out the title names.
Ring any bells? They did to me. These are funny encodings of Julian dates.
Hear me out.
Let's look at:
sampleTitle :: FileName
sampleTitle = "AP900327-0242.txt"
-
dateFromJulianDate : : Integer - > Day
dateFromJulianDate jd = undefined
Actually , after looking at this sideways , and realizing something : those
are dates , but not Y2K - compliant . SO , this becomes a bit easier
to recode
-
dateFromJulianDate :: Integer -> Day
dateFromJulianDate jd = undefined
Actually, after looking at this sideways, and realizing something: those
are Gregorian dates, but not Y2K-compliant. SO, this becomes a bit easier
to recode
dateFromString :: String -> UTCTime
dateFromString (y1:y2:m1:m2:d1:d2:_dash:minutes) =
UTCTime (fromGregorian (1900 + fromIntegral (c y1 y2)) (c m1 m2) (c d1 d2))
(secondsToDiffTime (60 * read (take 4 minutes)))
where c x y = read [x,y]
-
Actually , I noted minutes were like 0094 , etc , so I 'm thinkin they are minutes
from midnight : I 'm going with that .
> > > sampleTitle
" AP900327-0242.txt "
> > > dateFromString ( drop 2 sampleTitle )
1990 - 03 - 27 04:02:00
Actually, I noted minutes were like 0094, etc, so I'm thinkin they are minutes
from midnight: I'm going with that.
>>> sampleTitle
"AP900327-0242.txt"
>>> dateFromString (drop 2 sampleTitle)
1990-03-27 04:02:00 UTC
articlesDir :: FilePath
articlesDir = "Y2017/M09/D08/articles/b"
and for each article extract the Julian date ( by reading in the first
Integer ) and return the corresponding Day published for that article :
fileNameToDay :: FilePath -> UTCTime
fileNameToDay = dateFromString . drop 2
-
> > > fmap ( map fileNameToDay . filter ( startsWith ' . ' ) ) $ filesAt articlesDir " "
[ 1990 - 03 - 27,1990 - 03 - 27,1990 - 03 - 27,1990 - 03 - 28,1990 - 03 - 28,1990 - 03 - 29,1990 - 03 - 30 ,
1990 - 03 - 30,1990 - 04 - 01,1990 - 04 - 02 ]
So : question !
ARE these hidden dates ?
OR is geophf off his rocker ?
I guess we 'll never know the answer to some questions in life ...
-
>>> fmap (map fileNameToDay . filter (startsWith '.')) $ filesAt articlesDir ""
[1990-03-27,1990-03-27,1990-03-27,1990-03-28,1990-03-28,1990-03-29,1990-03-30,
1990-03-30,1990-04-01,1990-04-02]
So: question!
ARE these hidden Julian dates?
OR is geophf off his rocker?
I guess we'll never know the answer to some questions in life ...
Or , you can use the API call from the US Naval Observatory , e.g. :
-
Or, you can use the API call from the US Naval Observatory, e.g.:
myID :: String
myID = "geophf"
and as a courtesy , email the Navy with your i d and who you are :
navyEmail :: URL
navyEmail = ""
jdconverter :: URL
jdconverter = ""
-
> > > simpleHttp ( jdconverter + + " ? ID = geophf&jd=900327&format = ) > > = putStrLn
{
" error":false ,
" apiversion":"2.0.0 " ,
" data " : [
{
" jd " : 900327.000000 ,
" month " : 12 ,
" day " : 17 ,
" year " : 2249 ,
" era " : " B.C. " ,
" time " : " 12:00:00.0 " ,
" tz " : 0 ,
" dayofweek " : " Tuesday "
}
]
}
... and you can use Data . Aeson to convert these values .
-
>>> simpleHttp (jdconverter ++ "?ID=geophf&jd=900327&format=json") >>= putStrLn
{
"error":false,
"apiversion":"2.0.0",
"data":[
{
"jd": 900327.000000,
"month": 12,
"day": 17,
"year": 2249,
"era": "B.C.",
"time": "12:00:00.0",
"tz": 0,
"dayofweek" : "Tuesday"
}
]
}
... and you can use Data.Aeson to convert these values.
|
80d939a887702ce45d208dbb6187309a3d7a78375bd0eb55e764cde972a8890e | diagrams/diagrams-lib | Offset.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
# OPTIONS_GHC -fno - warn - unused - imports #
for Data . Semigroup
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.TwoD.Offset
Copyright : ( c ) 2013 diagrams - lib team ( see LICENSE )
-- License : BSD-style (see LICENSE)
-- Maintainer :
--
Compute offsets to segments in two dimensions . More details can be
-- found in the manual at
-- <#offsets-of-segments-trails-and-paths>.
--
-----------------------------------------------------------------------------
module Diagrams.TwoD.Offset
(
-- * Offsets
offsetSegment
, OffsetOpts(..), offsetJoin, offsetMiterLimit, offsetEpsilon
, offsetTrail
, offsetTrail'
, offsetPath
, offsetPath'
-- * Expansions
, ExpandOpts(..), expandJoin, expandMiterLimit, expandCap, expandEpsilon
, expandTrail
, expandTrail'
, expandPath
, expandPath'
) where
import Control.Applicative
import Control.Lens hiding (at)
import Prelude
import Data.Maybe (catMaybes)
import Data.Monoid
import Data.Monoid.Inf
import Data.Default.Class
import Diagrams.Core
import Diagrams.Attributes
import Diagrams.Direction
import Diagrams.Located
import Diagrams.Parametric
import Diagrams.Path
import Diagrams.Segment
import Diagrams.Trail hiding (isLoop, offset)
import Diagrams.TrailLike
import Diagrams.TwoD.Arc
import Diagrams.TwoD.Curvature
import Diagrams.TwoD.Path ()
import Diagrams.TwoD.Types
import Diagrams.TwoD.Vector hiding (e)
import Linear.Affine
import Linear.Metric
import Linear.Vector
unitPerp :: OrderedField n => V2 n -> V2 n
unitPerp = signorm . perp
perpAtParam :: OrderedField n => Segment Closed V2 n -> n -> V2 n
perpAtParam (Linear (OffsetClosed a)) _ = negated $ unitPerp a
perpAtParam cubic t = negated $ unitPerp a
where
(Cubic a _ _) = snd $ splitAtParam cubic t
-- | Compute the offset of a segment. Given a segment compute the offset
curve that is a fixed distance from the original curve . For linear
-- segments nothing special happens, the same linear segment is returned
-- with a point that is offset by a perpendicular vector of the given offset
-- length.
--
Cubic segments require a search for a subdivision of cubic segments that
-- gives an approximation of the offset within the given epsilon factor
-- (the given epsilon factor is applied to the radius giving a concrete epsilon
-- value).
-- We must do this because the offset of a cubic is not a cubic itself (the
degree of the curve increases ) . Cubics do , however , approach constant
-- curvature as we subdivide. In light of this we scale the handles of
-- the offset cubic segment in proportion to the radius of curvature difference
-- between the original subsegment and the offset which will have a radius
-- increased by the offset parameter.
--
-- In the following example the blue lines are the original segments and
-- the alternating green and red lines are the resulting offset trail segments.
--
< < diagrams / src_Diagrams_TwoD_Offset_cubicOffsetExample.svg#diagram = cubicOffsetExample&width=600 > >
--
-- Note that when the original curve has a cusp, the offset curve forms a
-- radius around the cusp, and when there is a loop in the original curve,
there can be two cusps in the offset curve .
--
-- | Options for specifying line join and segment epsilon for an offset
-- involving multiple segments.
data OffsetOpts d = OffsetOpts
{ _offsetJoin :: LineJoin
, _offsetMiterLimit :: d
, _offsetEpsilon :: d
}
deriving instance Eq d => Eq (OffsetOpts d)
deriving instance Show d => Show (OffsetOpts d)
makeLensesWith (lensRules & generateSignatures .~ False) ''OffsetOpts
-- | Specifies the style of join for between adjacent offset segments.
offsetJoin :: Lens' (OffsetOpts d) LineJoin
-- | Specifies the miter limit for the join.
offsetMiterLimit :: Lens' (OffsetOpts d) d
-- | Epsilon perimeter for 'offsetSegment'.
offsetEpsilon :: Lens' (OffsetOpts d) d
| The default offset options use the default ' LineJoin ' ( ' LineJoinMiter ' ) , a
miter limit of 10 , and epsilon factor of 0.01 .
instance Fractional d => Default (OffsetOpts d) where
def = OffsetOpts def 10 0.01
-- | Options for specifying how a 'Trail' should be expanded.
data ExpandOpts d = ExpandOpts
{ _expandJoin :: LineJoin
, _expandMiterLimit :: d
, _expandCap :: LineCap
, _expandEpsilon :: d
} deriving (Eq, Show)
makeLensesWith (lensRules & generateSignatures .~ False) ''ExpandOpts
-- | Specifies the style of join for between adjacent offset segments.
expandJoin :: Lens' (ExpandOpts d) LineJoin
-- | Specifies the miter limit for the join.
expandMiterLimit :: Lens' (ExpandOpts d) d
-- | Specifies how the ends are handled.
expandCap :: Lens' (ExpandOpts d) LineCap
-- | Epsilon perimeter for 'offsetSegment'.
expandEpsilon :: Lens' (ExpandOpts d) d
| The default ' ExpandOpts ' is the default ' LineJoin ' ( ' LineJoinMiter ' ) ,
miter limit of 10 , default ' ' ( ' LineCapButt ' ) , and epsilon factor
of 0.01 .
instance (Fractional d) => Default (ExpandOpts d) where
def = ExpandOpts def 10 def 0.01
offsetSegment :: RealFloat n
=> n -- ^ Epsilon factor that when multiplied to the
-- absolute value of the radius gives a
-- value that represents the maximum
-- allowed deviation from the true offset. In
-- the current implementation each result segment
-- should be bounded by arcs that are plus or
-- minus epsilon factor from the radius of curvature of
-- the offset.
-> n -- ^ Offset from the original segment, positive is
-- on the right of the curve, negative is on the
-- left.
-> Segment Closed V2 n -- ^ Original segment
-> Located (Trail V2 n) -- ^ Resulting located (at the offset) trail.
offsetSegment _ r s@(Linear (OffsetClosed a)) = trailFromSegments [s] `at` origin .+^ va
where va = (-r) *^ unitPerp a
offsetSegment epsilon r s@(Cubic a b (OffsetClosed c)) = t `at` origin .+^ va
where
t = trailFromSegments (go (radiusOfCurvature s 0.5))
Perpendiculars to handles .
va = (-r) *^ unitPerp a
vc = (-r) *^ unitPerp (c ^-^ b)
-- Split segments.
ss = (\(x,y) -> [x,y]) $ splitAtParam s 0.5
subdivided = concatMap (trailSegments . unLoc . offsetSegment epsilon r) ss
-- Offset with handles scaled based on curvature.
offset factor = bezier3 (a^*factor) ((b ^-^ c)^*factor ^+^ c ^+^ vc ^-^ va) (c ^+^ vc ^-^ va)
We observe a corner . Subdivide right away .
go (Finite 0) = subdivided
-- We have some curvature
go roc
| close = [o]
| otherwise = subdivided
where
-- We want the multiplicative factor that takes us from the original
segment 's radius of curvature roc , to roc + r.
--
-- r + sr = x * sr
--
o = offset $ case roc of
Infinity -> 1 -- Do the right thing.
Finite sr -> 1 + r / sr
close = and [epsilon * abs r > norm (p o ^+^ va ^-^ p s ^-^ pp s)
| t' <- [0.25, 0.5, 0.75]
, let p = (`atParam` t')
, let pp = (r *^) . (`perpAtParam` t')
]
-- > import Diagrams.TwoD.Offset
-- >
-- > showExample :: Segment Closed V2 Double -> Diagram SVG
> showExample s = pad 1.1 . centerXY $ d # lc blue # lw thick < > d ' # lw thick
-- > where
-- > d = strokeP . fromSegments $ [s]
> d ' = mconcat . . map strokeP .
> $ offsetSegment 0.1 ( -1 ) s
-- >
-- > colors = cycle [green, red]
-- >
-- > cubicOffsetExample :: Diagram SVG
-- > cubicOffsetExample = hcat . map showExample $
> [ bezier3 ( 10 ^ & 0 ) ( 5 ^ & 18 ) ( 10 ^ & 20 )
> , bezier3 ( 0 ^ & 20 ) ( 10 ^ & 10 ) ( 5 ^ & 10 )
> , bezier3 ( 10 ^ & 20 ) ( 0 ^ & 10 ) ( 10 ^ & 0 )
> , bezier3 ( 10 ^ & 20 ) ( ( -5 ) ^ & 10 ) ( 10 ^ & 0 )
-- > ]
-- Similar to (=<<). This is when we want to map a function across something
-- located, but the result of the mapping will be transformable so we can
-- collapse the Located into the result. This assumes that Located has the
-- meaning of merely taking something that cannot be translated and lifting
-- it into a space with translation.
bindLoc :: (Transformable b, V a ~ V b, N a ~ N b, V a ~ V2, N a ~ n, Num n) => (a -> b) -> Located a -> b
bindLoc f = join' . mapLoc f
where
join' (viewLoc -> (p,a)) = translate (p .-. origin) a
-- While we build offsets and expansions we will use the [Located (Segment Closed v)]
and [ Located ( Trail V2 n ) ] intermediate representations .
locatedTrailSegments :: OrderedField n
=> Located (Trail V2 n) -> [Located (Segment Closed V2 n)]
locatedTrailSegments t = zipWith at (trailSegments (unLoc t)) (trailPoints t)
-- | Offset a 'Trail' with options and by a given radius. This generates a new
-- trail that is always radius 'r' away from the given 'Trail' (depending on
-- the line join option) on the right.
--
-- The styles applied to an outside corner can be seen here (with the original
-- trail in blue and the result of 'offsetTrail'' in green):
--
-- <<diagrams/src_Diagrams_TwoD_Offset_offsetTrailExample.svg#diagram=offsetTrailExample&width=600>>
--
-- When a negative radius is given, the offset trail will be on the left:
--
-- <<diagrams/src_Diagrams_TwoD_Offset_offsetTrailLeftExample.svg#diagram=offsetTrailLeftExample&width=200>>
--
-- When offseting a counter-clockwise loop a positive radius gives an outer loop
-- while a negative radius gives an inner loop (both counter-clockwise).
--
-- <<diagrams/src_Diagrams_TwoD_Offset_offsetTrailOuterExample.svg#diagram=offsetTrailOuterExample&width=300>>
--
offsetTrail' :: RealFloat n
=> OffsetOpts n
-> n -- ^ Radius of offset. A negative value gives an offset on
-- the left for a line and on the inside for a counter-clockwise
-- loop.
-> Located (Trail V2 n)
-> Located (Trail V2 n)
offsetTrail' opts r t = joinSegments eps j isLoop (opts^.offsetMiterLimit) r ends . offset $ t
where
eps = opts^.offsetEpsilon
offset = map (bindLoc (offsetSegment eps r)) . locatedTrailSegments
ends | isLoop = (\(a:as) -> as ++ [a]) . trailPoints $ t
| otherwise = tail . trailPoints $ t
j = fromLineJoin (opts^.offsetJoin)
isLoop = withTrail (const False) (const True) (unLoc t)
-- | Offset a 'Trail' with the default options and a given radius. See 'offsetTrail''.
offsetTrail :: RealFloat n => n -> Located (Trail V2 n) -> Located (Trail V2 n)
offsetTrail = offsetTrail' def
-- | Offset a 'Path' by applying 'offsetTrail'' to each trail in the path.
offsetPath' :: RealFloat n => OffsetOpts n -> n -> Path V2 n -> Path V2 n
offsetPath' opts r = mconcat
. map (bindLoc (trailLike . offsetTrail' opts r) . (`at` origin))
. op Path
-- | Offset a 'Path' with the default options and given radius. See 'offsetPath''.
offsetPath :: RealFloat n => n -> Path V2 n -> Path V2 n
offsetPath = offsetPath' def
-- TODO: Include arrowheads on examples to indicate direction so the "left" and
-- "right" make sense.
--
-- > import Diagrams.TwoD.Offset
-- > import Data.Default.Class
-- >
> corner : : ( OrderedField n ) = > Located ( Trail V2 n )
> corner = fromVertices ( map p2 [ ( 0 , 0 ) , ( 10 , 0 ) , ( 5 , 6 ) ] ) ` at ` origin
-- >
-- > offsetTrailExample :: Diagram SVG
> offsetTrailExample = pad 1.1 . centerXY . lwO 3 . hcat ' ( def & sep .~ 1 )
-- > . map (uncurry showStyle)
-- > $ [ (LineJoinMiter, "LineJoinMiter")
> , ( LineJoinRound , " LineJoinRound " )
> , ( LineJoinBevel , " LineJoinBevel " )
-- > ]
-- > where
> j s = centerXY ( trailLike corner # lc blue
> < > trailLike ( offsetTrail ' ( def & offsetJoin .~ j ) 2 corner ) # lc green )
> = = = ( strutY 3 < > text s # font " Helvetica " # bold )
-- >
-- > offsetTrailLeftExample :: Diagram SVG
> offsetTrailLeftExample = pad 1.1 . centerXY . lwO 3
-- > $ (trailLike c # lc blue)
-- > <> (lc green . trailLike
> . ' ( def & offsetJoin .~ LineJoinRound ) ( -2 ) $ c )
-- > where
-- > c = reflectY corner
-- >
-- > offsetTrailOuterExample :: Diagram SVG
> offsetTrailOuterExample = pad 1.1 . centerXY . lwO 3
-- > $ (trailLike c # lc blue)
-- > <> (lc green . trailLike
> . ' ( def & offsetJoin .~ LineJoinRound ) 2 $ c )
-- > where
> c = hexagon 5
withTrailL :: (Located (Trail' Line V2 n) -> r) -> (Located (Trail' Loop V2 n) -> r) -> Located (Trail V2 n) -> r
withTrailL f g l = withTrail (f . (`at` p)) (g . (`at` p)) (unLoc l)
where
p = loc l
-- | Expand a 'Trail' with the given options and radius 'r' around a given 'Trail'.
-- Expanding can be thought of as generating the loop that, when filled, represents
-- stroking the trail with a radius 'r' brush.
--
-- The cap styles applied to an outside corner can be seen here (with the original
-- trail in white and the result of 'expandTrail'' filled in green):
--
-- <<diagrams/src_Diagrams_TwoD_Offset_expandTrailExample.svg#diagram=expandTrailExample&width=600>>
--
-- Loops result in a path with an inner and outer loop:
--
-- <<diagrams/src_Diagrams_TwoD_Offset_expandLoopExample.svg#diagram=expandLoopExample&width=300>>
--
expandTrail' :: (OrderedField n, RealFloat n, RealFrac n)
=> ExpandOpts n
-> n -- ^ Radius of offset. Only non-negative values allowed.
-- For a line this gives a loop of the offset. For a
loop this gives two loops , the outer counter - clockwise
-- and the inner clockwise.
-> Located (Trail V2 n)
-> Path V2 n
expandTrail' o r t
| r < 0 = error "expandTrail' with negative radius"
-- TODO: consider just reversing the path instead of this error.
| otherwise = withTrailL (pathFromLocTrail . expandLine o r) (expandLoop o r) t
expandLine :: RealFloat n => ExpandOpts n -> n -> Located (Trail' Line V2 n) -> Located (Trail V2 n)
expandLine opts r (mapLoc wrapLine -> t) = caps cap r s e (f r) (f $ -r)
where
eps = opts^.expandEpsilon
offset r' = map (bindLoc (offsetSegment eps r')) . locatedTrailSegments
f r' = joinSegments eps (fromLineJoin (opts^.expandJoin)) False (opts^.expandMiterLimit) r' ends
. offset r' $ t
ends = tail . trailPoints $ t
s = atStart t
e = atEnd t
cap = fromLineCap (opts^.expandCap)
expandLoop :: RealFloat n => ExpandOpts n -> n -> Located (Trail' Loop V2 n) -> Path V2 n
expandLoop opts r (mapLoc wrapLoop -> t) = trailLike (f r) <> (trailLike . reverseDomain . f $ -r)
where
eps = opts^.expandEpsilon
offset r' = map (bindLoc (offsetSegment eps r')) . locatedTrailSegments
f r' = joinSegments eps (fromLineJoin (opts^.expandJoin)) True (opts^.expandMiterLimit) r' ends
. offset r' $ t
ends = (\(a:as) -> as ++ [a]) . trailPoints $ t
-- | Expand a 'Trail' with the given radius and default options. See 'expandTrail''.
expandTrail :: RealFloat n => n -> Located (Trail V2 n) -> Path V2 n
expandTrail = expandTrail' def
-- | Expand a 'Path' using 'expandTrail'' on each trail in the path.
expandPath' :: RealFloat n => ExpandOpts n -> n -> Path V2 n -> Path V2 n
expandPath' opts r = mconcat
. map (bindLoc (expandTrail' opts r) . (`at` origin))
. op Path
-- | Expand a 'Path' with the given radius and default options. See 'expandPath''.
expandPath :: RealFloat n => n -> Path V2 n -> Path V2 n
expandPath = expandPath' def
-- > import Diagrams.TwoD.Offset
-- > import Data.Default.Class
-- >
-- > expandTrailExample :: Diagram SVG
> expandTrailExample = pad 1.1 . centerXY . hcat ' ( def & sep .~ 1 )
-- > . map (uncurry showStyle)
> $ [ ( LineCapButt , " LineCapButt " )
> , ( LineCapRound , " LineCapRound " )
-- > , (LineCapSquare, "LineCapSquare")
-- > ]
-- > where
> showStyle c s = centerXY ( trailLike corner # lc white # lw
> < > stroke ( '
-- > (def & expandJoin .~ LineJoinRound
-- > & expandCap .~ c
> ) 2 corner )
-- > # lw none # fc green)
> = = = ( strutY 3 < > text s # font " Helvetica " # bold )
-- >
-- > expandLoopExample :: Diagram SVG
> expandLoopExample = pad 1.1 . centerXY $ ( ( strokeLocT t # lw veryThick # lc white )
> < > ( stroke t ' # lw none # fc green ) )
-- > where
> t = mapLoc fromVertices ( map p2 [ ( 0 , 0 ) , ( 5 , 0 ) , ( 10 , 5 ) , ( 10 , 10 ) , ( 0 , 0 ) ] )
> t ' = expandTrail ' ( def & expandJoin .~ LineJoinRound ) 1 t
-- | When we expand a line (the original line runs through the center of offset
-- lines at r and -r) there is some choice in what the ends will look like.
If we are using a circle brush we should see a half circle at each end .
-- Similar caps could be made for square brushes or simply stopping exactly at
-- the end with a straight line (a perpendicular line brush).
--
-- caps takes the radius and the start and end points of the original line and
-- the offset trails going out and coming back. The result is a new list of
-- trails with the caps included.
caps :: RealFloat n => (n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n)
-> n -> Point V2 n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Located (Trail V2 n)
caps cap r s e fs bs = mapLoc glueTrail $ mconcat
[ cap r s (atStart bs) (atStart fs)
, unLoc fs
, cap r e (atEnd fs) (atEnd bs)
, reverseDomain (unLoc bs)
] `at` atStart bs
| Take a style and give a function for building the cap from
fromLineCap :: RealFloat n => LineCap -> n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n
fromLineCap c = case c of
LineCapButt -> capCut
LineCapRound -> capArc
LineCapSquare -> capSquare
-- | Builds a cap that directly connects the ends.
capCut :: RealFloat n => n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n
capCut _r _c a b = fromSegments [straight (b .-. a)]
-- | Builds a cap with a square centered on the end.
capSquare :: RealFloat n => n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n
capSquare _r c a b = unLoc $ fromVertices [ a, a .+^ v, b .+^ v, b ]
where
v = perp (a .-. c)
-- | Builds an arc to fit with a given radius, center, start, and end points.
-- A Negative r means a counter-clockwise arc
capArc :: RealFloat n => n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n
capArc r c a b = trailLike . moveTo c $ fs
where
fs | r < 0 = scale (-r) $ arcCW (dirBetween c a) (dirBetween c b)
| otherwise = scale r $ arcCCW (dirBetween c a) (dirBetween c b)
-- | Join together a list of located trails with the given join style. The
-- style is given as a function to compute the join given the local information
-- of the original vertex, the previous trail, and the next trail. The result
-- is a single located trail. A join radius is also given to aid in arc joins.
--
-- Note: this is not a general purpose join and assumes that we are joining an
-- offset trail. For instance, a fixed radius arc will not fit between arbitrary
-- trails without trimming or extending.
joinSegments :: RealFloat n
=> n
-> (n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n)
-> Bool
-> n
-> n
-> [Point V2 n]
-> [Located (Trail V2 n)]
-> Located (Trail V2 n)
joinSegments _ _ _ _ _ _ [] = mempty `at` origin
joinSegments _ _ _ _ _ [] _ = mempty `at` origin
joinSegments epsilon j isLoop ml r es ts@(t:_) = t'
where
t' | isLoop = mapLoc (glueTrail . (<> f (take (length ts * 2 - 1) $ ss es (ts ++ [t])))) t
| otherwise = mapLoc (<> f (ss es ts)) t
ss es' ts' = concat [[test a b $ j ml r e a b, Just $ unLoc b] | (e,(a,b)) <- zip es' . (zip <*> tail) $ ts']
test a b tj
| atStart b `distance` atEnd a > epsilon = Just tj
| otherwise = Nothing
f = mconcat . catMaybes
-- | Take a join style and give the join function to be used by joinSegments.
fromLineJoin
:: RealFloat n => LineJoin -> n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
fromLineJoin j = case j of
LineJoinMiter -> joinSegmentIntersect
LineJoinRound -> joinSegmentArc
LineJoinBevel -> joinSegmentClip
-- TODO: The joinSegmentCut option is not in our standard line joins. I don't know
-- how useful it is graphically, I mostly had it as it was useful for debugging
-- | Join with segments going back to the original corner .
joinSegmentCut : : ( OrderedField n ) = > n - > n - > Point V2 n - > Located ( Trail V2 n ) - > Located ( Trail V2 n ) - > Trail V2 n
joinSegmentCut _ _ e a b = fromSegments
[ straight ( e .- . atEnd a )
, straight ( atStart b .- . e )
]
-- | Join with segments going back to the original corner.
joinSegmentCut :: (OrderedField n) => n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
joinSegmentCut _ _ e a b = fromSegments
[ straight (e .-. atEnd a)
, straight (atStart b .-. e)
]
-}
-- | Join by directly connecting the end points. On an inside corner this
-- creates negative space for even-odd fill. Here is where we would want to
-- use an arc or something else in the future.
joinSegmentClip :: RealFloat n
=> n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
joinSegmentClip _ _ _ a b = fromSegments [straight $ atStart b .-. atEnd a]
-- | Join with a radius arc. On an inside corner this will loop around the interior
-- of the offset trail. With a winding fill this will not be visible.
joinSegmentArc :: RealFloat n
=> n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
joinSegmentArc _ r e a b = capArc r e (atEnd a) (atStart b)
-- | Join to the intersection of the incoming trails projected tangent to their ends.
-- If the intersection is beyond the miter limit times the radius, stop at the limit.
joinSegmentIntersect
:: RealFloat n => n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
joinSegmentIntersect miterLimit r e a b =
if cross < 0.000001
then clip
else case traceP pa va t of
-- clip join when we excede the miter limit. We could instead
-- Join at exactly the miter limit, but standard behavior seems
-- to be clipping.
Nothing -> clip
Just p
-- If trace gave us garbage...
| p `distance` pb > abs (miterLimit * r) -> clip
| otherwise -> unLoc $ fromVertices [ pa, p, pb ]
where
t = straight (miter vb) `at` pb
va = unitPerp (pa .-. e)
vb = negated $ unitPerp (pb .-. e)
pa = atEnd a
pb = atStart b
miter v = abs (miterLimit * r) *^ v
clip = joinSegmentClip miterLimit r e a b
cross = let (xa,ya) = unr2 va; (xb,yb) = unr2 vb in abs (xa * yb - xb * ya)
| null | https://raw.githubusercontent.com/diagrams/diagrams-lib/b7357d6d9d56f80f6c06a185514600c31d53c944/src/Diagrams/TwoD/Offset.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE GADTs #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
---------------------------------------------------------------------------
|
Module : Diagrams.TwoD.Offset
License : BSD-style (see LICENSE)
Maintainer :
found in the manual at
<#offsets-of-segments-trails-and-paths>.
---------------------------------------------------------------------------
* Offsets
* Expansions
| Compute the offset of a segment. Given a segment compute the offset
segments nothing special happens, the same linear segment is returned
with a point that is offset by a perpendicular vector of the given offset
length.
gives an approximation of the offset within the given epsilon factor
(the given epsilon factor is applied to the radius giving a concrete epsilon
value).
We must do this because the offset of a cubic is not a cubic itself (the
curvature as we subdivide. In light of this we scale the handles of
the offset cubic segment in proportion to the radius of curvature difference
between the original subsegment and the offset which will have a radius
increased by the offset parameter.
In the following example the blue lines are the original segments and
the alternating green and red lines are the resulting offset trail segments.
Note that when the original curve has a cusp, the offset curve forms a
radius around the cusp, and when there is a loop in the original curve,
| Options for specifying line join and segment epsilon for an offset
involving multiple segments.
| Specifies the style of join for between adjacent offset segments.
| Specifies the miter limit for the join.
| Epsilon perimeter for 'offsetSegment'.
| Options for specifying how a 'Trail' should be expanded.
| Specifies the style of join for between adjacent offset segments.
| Specifies the miter limit for the join.
| Specifies how the ends are handled.
| Epsilon perimeter for 'offsetSegment'.
^ Epsilon factor that when multiplied to the
absolute value of the radius gives a
value that represents the maximum
allowed deviation from the true offset. In
the current implementation each result segment
should be bounded by arcs that are plus or
minus epsilon factor from the radius of curvature of
the offset.
^ Offset from the original segment, positive is
on the right of the curve, negative is on the
left.
^ Original segment
^ Resulting located (at the offset) trail.
Split segments.
Offset with handles scaled based on curvature.
We have some curvature
We want the multiplicative factor that takes us from the original
r + sr = x * sr
Do the right thing.
> import Diagrams.TwoD.Offset
>
> showExample :: Segment Closed V2 Double -> Diagram SVG
> where
> d = strokeP . fromSegments $ [s]
>
> colors = cycle [green, red]
>
> cubicOffsetExample :: Diagram SVG
> cubicOffsetExample = hcat . map showExample $
> ]
Similar to (=<<). This is when we want to map a function across something
located, but the result of the mapping will be transformable so we can
collapse the Located into the result. This assumes that Located has the
meaning of merely taking something that cannot be translated and lifting
it into a space with translation.
While we build offsets and expansions we will use the [Located (Segment Closed v)]
| Offset a 'Trail' with options and by a given radius. This generates a new
trail that is always radius 'r' away from the given 'Trail' (depending on
the line join option) on the right.
The styles applied to an outside corner can be seen here (with the original
trail in blue and the result of 'offsetTrail'' in green):
<<diagrams/src_Diagrams_TwoD_Offset_offsetTrailExample.svg#diagram=offsetTrailExample&width=600>>
When a negative radius is given, the offset trail will be on the left:
<<diagrams/src_Diagrams_TwoD_Offset_offsetTrailLeftExample.svg#diagram=offsetTrailLeftExample&width=200>>
When offseting a counter-clockwise loop a positive radius gives an outer loop
while a negative radius gives an inner loop (both counter-clockwise).
<<diagrams/src_Diagrams_TwoD_Offset_offsetTrailOuterExample.svg#diagram=offsetTrailOuterExample&width=300>>
^ Radius of offset. A negative value gives an offset on
the left for a line and on the inside for a counter-clockwise
loop.
| Offset a 'Trail' with the default options and a given radius. See 'offsetTrail''.
| Offset a 'Path' by applying 'offsetTrail'' to each trail in the path.
| Offset a 'Path' with the default options and given radius. See 'offsetPath''.
TODO: Include arrowheads on examples to indicate direction so the "left" and
"right" make sense.
> import Diagrams.TwoD.Offset
> import Data.Default.Class
>
>
> offsetTrailExample :: Diagram SVG
> . map (uncurry showStyle)
> $ [ (LineJoinMiter, "LineJoinMiter")
> ]
> where
>
> offsetTrailLeftExample :: Diagram SVG
> $ (trailLike c # lc blue)
> <> (lc green . trailLike
> where
> c = reflectY corner
>
> offsetTrailOuterExample :: Diagram SVG
> $ (trailLike c # lc blue)
> <> (lc green . trailLike
> where
| Expand a 'Trail' with the given options and radius 'r' around a given 'Trail'.
Expanding can be thought of as generating the loop that, when filled, represents
stroking the trail with a radius 'r' brush.
The cap styles applied to an outside corner can be seen here (with the original
trail in white and the result of 'expandTrail'' filled in green):
<<diagrams/src_Diagrams_TwoD_Offset_expandTrailExample.svg#diagram=expandTrailExample&width=600>>
Loops result in a path with an inner and outer loop:
<<diagrams/src_Diagrams_TwoD_Offset_expandLoopExample.svg#diagram=expandLoopExample&width=300>>
^ Radius of offset. Only non-negative values allowed.
For a line this gives a loop of the offset. For a
and the inner clockwise.
TODO: consider just reversing the path instead of this error.
| Expand a 'Trail' with the given radius and default options. See 'expandTrail''.
| Expand a 'Path' using 'expandTrail'' on each trail in the path.
| Expand a 'Path' with the given radius and default options. See 'expandPath''.
> import Diagrams.TwoD.Offset
> import Data.Default.Class
>
> expandTrailExample :: Diagram SVG
> . map (uncurry showStyle)
> , (LineCapSquare, "LineCapSquare")
> ]
> where
> (def & expandJoin .~ LineJoinRound
> & expandCap .~ c
> # lw none # fc green)
>
> expandLoopExample :: Diagram SVG
> where
| When we expand a line (the original line runs through the center of offset
lines at r and -r) there is some choice in what the ends will look like.
Similar caps could be made for square brushes or simply stopping exactly at
the end with a straight line (a perpendicular line brush).
caps takes the radius and the start and end points of the original line and
the offset trails going out and coming back. The result is a new list of
trails with the caps included.
| Builds a cap that directly connects the ends.
| Builds a cap with a square centered on the end.
| Builds an arc to fit with a given radius, center, start, and end points.
A Negative r means a counter-clockwise arc
| Join together a list of located trails with the given join style. The
style is given as a function to compute the join given the local information
of the original vertex, the previous trail, and the next trail. The result
is a single located trail. A join radius is also given to aid in arc joins.
Note: this is not a general purpose join and assumes that we are joining an
offset trail. For instance, a fixed radius arc will not fit between arbitrary
trails without trimming or extending.
| Take a join style and give the join function to be used by joinSegments.
TODO: The joinSegmentCut option is not in our standard line joins. I don't know
how useful it is graphically, I mostly had it as it was useful for debugging
| Join with segments going back to the original corner .
| Join with segments going back to the original corner.
| Join by directly connecting the end points. On an inside corner this
creates negative space for even-odd fill. Here is where we would want to
use an arc or something else in the future.
| Join with a radius arc. On an inside corner this will loop around the interior
of the offset trail. With a winding fill this will not be visible.
| Join to the intersection of the incoming trails projected tangent to their ends.
If the intersection is beyond the miter limit times the radius, stop at the limit.
clip join when we excede the miter limit. We could instead
Join at exactly the miter limit, but standard behavior seems
to be clipping.
If trace gave us garbage... | # LANGUAGE FlexibleContexts #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
# OPTIONS_GHC -fno - warn - unused - imports #
for Data . Semigroup
Copyright : ( c ) 2013 diagrams - lib team ( see LICENSE )
Compute offsets to segments in two dimensions . More details can be
module Diagrams.TwoD.Offset
(
offsetSegment
, OffsetOpts(..), offsetJoin, offsetMiterLimit, offsetEpsilon
, offsetTrail
, offsetTrail'
, offsetPath
, offsetPath'
, ExpandOpts(..), expandJoin, expandMiterLimit, expandCap, expandEpsilon
, expandTrail
, expandTrail'
, expandPath
, expandPath'
) where
import Control.Applicative
import Control.Lens hiding (at)
import Prelude
import Data.Maybe (catMaybes)
import Data.Monoid
import Data.Monoid.Inf
import Data.Default.Class
import Diagrams.Core
import Diagrams.Attributes
import Diagrams.Direction
import Diagrams.Located
import Diagrams.Parametric
import Diagrams.Path
import Diagrams.Segment
import Diagrams.Trail hiding (isLoop, offset)
import Diagrams.TrailLike
import Diagrams.TwoD.Arc
import Diagrams.TwoD.Curvature
import Diagrams.TwoD.Path ()
import Diagrams.TwoD.Types
import Diagrams.TwoD.Vector hiding (e)
import Linear.Affine
import Linear.Metric
import Linear.Vector
unitPerp :: OrderedField n => V2 n -> V2 n
unitPerp = signorm . perp
perpAtParam :: OrderedField n => Segment Closed V2 n -> n -> V2 n
perpAtParam (Linear (OffsetClosed a)) _ = negated $ unitPerp a
perpAtParam cubic t = negated $ unitPerp a
where
(Cubic a _ _) = snd $ splitAtParam cubic t
curve that is a fixed distance from the original curve . For linear
Cubic segments require a search for a subdivision of cubic segments that
degree of the curve increases ) . Cubics do , however , approach constant
< < diagrams / src_Diagrams_TwoD_Offset_cubicOffsetExample.svg#diagram = cubicOffsetExample&width=600 > >
there can be two cusps in the offset curve .
data OffsetOpts d = OffsetOpts
{ _offsetJoin :: LineJoin
, _offsetMiterLimit :: d
, _offsetEpsilon :: d
}
deriving instance Eq d => Eq (OffsetOpts d)
deriving instance Show d => Show (OffsetOpts d)
makeLensesWith (lensRules & generateSignatures .~ False) ''OffsetOpts
offsetJoin :: Lens' (OffsetOpts d) LineJoin
offsetMiterLimit :: Lens' (OffsetOpts d) d
offsetEpsilon :: Lens' (OffsetOpts d) d
| The default offset options use the default ' LineJoin ' ( ' LineJoinMiter ' ) , a
miter limit of 10 , and epsilon factor of 0.01 .
instance Fractional d => Default (OffsetOpts d) where
def = OffsetOpts def 10 0.01
data ExpandOpts d = ExpandOpts
{ _expandJoin :: LineJoin
, _expandMiterLimit :: d
, _expandCap :: LineCap
, _expandEpsilon :: d
} deriving (Eq, Show)
makeLensesWith (lensRules & generateSignatures .~ False) ''ExpandOpts
expandJoin :: Lens' (ExpandOpts d) LineJoin
expandMiterLimit :: Lens' (ExpandOpts d) d
expandCap :: Lens' (ExpandOpts d) LineCap
expandEpsilon :: Lens' (ExpandOpts d) d
| The default ' ExpandOpts ' is the default ' LineJoin ' ( ' LineJoinMiter ' ) ,
miter limit of 10 , default ' ' ( ' LineCapButt ' ) , and epsilon factor
of 0.01 .
instance (Fractional d) => Default (ExpandOpts d) where
def = ExpandOpts def 10 def 0.01
offsetSegment :: RealFloat n
offsetSegment _ r s@(Linear (OffsetClosed a)) = trailFromSegments [s] `at` origin .+^ va
where va = (-r) *^ unitPerp a
offsetSegment epsilon r s@(Cubic a b (OffsetClosed c)) = t `at` origin .+^ va
where
t = trailFromSegments (go (radiusOfCurvature s 0.5))
Perpendiculars to handles .
va = (-r) *^ unitPerp a
vc = (-r) *^ unitPerp (c ^-^ b)
ss = (\(x,y) -> [x,y]) $ splitAtParam s 0.5
subdivided = concatMap (trailSegments . unLoc . offsetSegment epsilon r) ss
offset factor = bezier3 (a^*factor) ((b ^-^ c)^*factor ^+^ c ^+^ vc ^-^ va) (c ^+^ vc ^-^ va)
We observe a corner . Subdivide right away .
go (Finite 0) = subdivided
go roc
| close = [o]
| otherwise = subdivided
where
segment 's radius of curvature roc , to roc + r.
o = offset $ case roc of
Finite sr -> 1 + r / sr
close = and [epsilon * abs r > norm (p o ^+^ va ^-^ p s ^-^ pp s)
| t' <- [0.25, 0.5, 0.75]
, let p = (`atParam` t')
, let pp = (r *^) . (`perpAtParam` t')
]
> showExample s = pad 1.1 . centerXY $ d # lc blue # lw thick < > d ' # lw thick
> d ' = mconcat . . map strokeP .
> $ offsetSegment 0.1 ( -1 ) s
> [ bezier3 ( 10 ^ & 0 ) ( 5 ^ & 18 ) ( 10 ^ & 20 )
> , bezier3 ( 0 ^ & 20 ) ( 10 ^ & 10 ) ( 5 ^ & 10 )
> , bezier3 ( 10 ^ & 20 ) ( 0 ^ & 10 ) ( 10 ^ & 0 )
> , bezier3 ( 10 ^ & 20 ) ( ( -5 ) ^ & 10 ) ( 10 ^ & 0 )
bindLoc :: (Transformable b, V a ~ V b, N a ~ N b, V a ~ V2, N a ~ n, Num n) => (a -> b) -> Located a -> b
bindLoc f = join' . mapLoc f
where
join' (viewLoc -> (p,a)) = translate (p .-. origin) a
and [ Located ( Trail V2 n ) ] intermediate representations .
locatedTrailSegments :: OrderedField n
=> Located (Trail V2 n) -> [Located (Segment Closed V2 n)]
locatedTrailSegments t = zipWith at (trailSegments (unLoc t)) (trailPoints t)
offsetTrail' :: RealFloat n
=> OffsetOpts n
-> Located (Trail V2 n)
-> Located (Trail V2 n)
offsetTrail' opts r t = joinSegments eps j isLoop (opts^.offsetMiterLimit) r ends . offset $ t
where
eps = opts^.offsetEpsilon
offset = map (bindLoc (offsetSegment eps r)) . locatedTrailSegments
ends | isLoop = (\(a:as) -> as ++ [a]) . trailPoints $ t
| otherwise = tail . trailPoints $ t
j = fromLineJoin (opts^.offsetJoin)
isLoop = withTrail (const False) (const True) (unLoc t)
offsetTrail :: RealFloat n => n -> Located (Trail V2 n) -> Located (Trail V2 n)
offsetTrail = offsetTrail' def
offsetPath' :: RealFloat n => OffsetOpts n -> n -> Path V2 n -> Path V2 n
offsetPath' opts r = mconcat
. map (bindLoc (trailLike . offsetTrail' opts r) . (`at` origin))
. op Path
offsetPath :: RealFloat n => n -> Path V2 n -> Path V2 n
offsetPath = offsetPath' def
> corner : : ( OrderedField n ) = > Located ( Trail V2 n )
> corner = fromVertices ( map p2 [ ( 0 , 0 ) , ( 10 , 0 ) , ( 5 , 6 ) ] ) ` at ` origin
> offsetTrailExample = pad 1.1 . centerXY . lwO 3 . hcat ' ( def & sep .~ 1 )
> , ( LineJoinRound , " LineJoinRound " )
> , ( LineJoinBevel , " LineJoinBevel " )
> j s = centerXY ( trailLike corner # lc blue
> < > trailLike ( offsetTrail ' ( def & offsetJoin .~ j ) 2 corner ) # lc green )
> = = = ( strutY 3 < > text s # font " Helvetica " # bold )
> offsetTrailLeftExample = pad 1.1 . centerXY . lwO 3
> . ' ( def & offsetJoin .~ LineJoinRound ) ( -2 ) $ c )
> offsetTrailOuterExample = pad 1.1 . centerXY . lwO 3
> . ' ( def & offsetJoin .~ LineJoinRound ) 2 $ c )
> c = hexagon 5
withTrailL :: (Located (Trail' Line V2 n) -> r) -> (Located (Trail' Loop V2 n) -> r) -> Located (Trail V2 n) -> r
withTrailL f g l = withTrail (f . (`at` p)) (g . (`at` p)) (unLoc l)
where
p = loc l
expandTrail' :: (OrderedField n, RealFloat n, RealFrac n)
=> ExpandOpts n
loop this gives two loops , the outer counter - clockwise
-> Located (Trail V2 n)
-> Path V2 n
expandTrail' o r t
| r < 0 = error "expandTrail' with negative radius"
| otherwise = withTrailL (pathFromLocTrail . expandLine o r) (expandLoop o r) t
expandLine :: RealFloat n => ExpandOpts n -> n -> Located (Trail' Line V2 n) -> Located (Trail V2 n)
expandLine opts r (mapLoc wrapLine -> t) = caps cap r s e (f r) (f $ -r)
where
eps = opts^.expandEpsilon
offset r' = map (bindLoc (offsetSegment eps r')) . locatedTrailSegments
f r' = joinSegments eps (fromLineJoin (opts^.expandJoin)) False (opts^.expandMiterLimit) r' ends
. offset r' $ t
ends = tail . trailPoints $ t
s = atStart t
e = atEnd t
cap = fromLineCap (opts^.expandCap)
expandLoop :: RealFloat n => ExpandOpts n -> n -> Located (Trail' Loop V2 n) -> Path V2 n
expandLoop opts r (mapLoc wrapLoop -> t) = trailLike (f r) <> (trailLike . reverseDomain . f $ -r)
where
eps = opts^.expandEpsilon
offset r' = map (bindLoc (offsetSegment eps r')) . locatedTrailSegments
f r' = joinSegments eps (fromLineJoin (opts^.expandJoin)) True (opts^.expandMiterLimit) r' ends
. offset r' $ t
ends = (\(a:as) -> as ++ [a]) . trailPoints $ t
expandTrail :: RealFloat n => n -> Located (Trail V2 n) -> Path V2 n
expandTrail = expandTrail' def
expandPath' :: RealFloat n => ExpandOpts n -> n -> Path V2 n -> Path V2 n
expandPath' opts r = mconcat
. map (bindLoc (expandTrail' opts r) . (`at` origin))
. op Path
expandPath :: RealFloat n => n -> Path V2 n -> Path V2 n
expandPath = expandPath' def
> expandTrailExample = pad 1.1 . centerXY . hcat ' ( def & sep .~ 1 )
> $ [ ( LineCapButt , " LineCapButt " )
> , ( LineCapRound , " LineCapRound " )
> showStyle c s = centerXY ( trailLike corner # lc white # lw
> < > stroke ( '
> ) 2 corner )
> = = = ( strutY 3 < > text s # font " Helvetica " # bold )
> expandLoopExample = pad 1.1 . centerXY $ ( ( strokeLocT t # lw veryThick # lc white )
> < > ( stroke t ' # lw none # fc green ) )
> t = mapLoc fromVertices ( map p2 [ ( 0 , 0 ) , ( 5 , 0 ) , ( 10 , 5 ) , ( 10 , 10 ) , ( 0 , 0 ) ] )
> t ' = expandTrail ' ( def & expandJoin .~ LineJoinRound ) 1 t
If we are using a circle brush we should see a half circle at each end .
caps :: RealFloat n => (n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n)
-> n -> Point V2 n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Located (Trail V2 n)
caps cap r s e fs bs = mapLoc glueTrail $ mconcat
[ cap r s (atStart bs) (atStart fs)
, unLoc fs
, cap r e (atEnd fs) (atEnd bs)
, reverseDomain (unLoc bs)
] `at` atStart bs
| Take a style and give a function for building the cap from
fromLineCap :: RealFloat n => LineCap -> n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n
fromLineCap c = case c of
LineCapButt -> capCut
LineCapRound -> capArc
LineCapSquare -> capSquare
capCut :: RealFloat n => n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n
capCut _r _c a b = fromSegments [straight (b .-. a)]
capSquare :: RealFloat n => n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n
capSquare _r c a b = unLoc $ fromVertices [ a, a .+^ v, b .+^ v, b ]
where
v = perp (a .-. c)
capArc :: RealFloat n => n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n
capArc r c a b = trailLike . moveTo c $ fs
where
fs | r < 0 = scale (-r) $ arcCW (dirBetween c a) (dirBetween c b)
| otherwise = scale r $ arcCCW (dirBetween c a) (dirBetween c b)
joinSegments :: RealFloat n
=> n
-> (n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n)
-> Bool
-> n
-> n
-> [Point V2 n]
-> [Located (Trail V2 n)]
-> Located (Trail V2 n)
joinSegments _ _ _ _ _ _ [] = mempty `at` origin
joinSegments _ _ _ _ _ [] _ = mempty `at` origin
joinSegments epsilon j isLoop ml r es ts@(t:_) = t'
where
t' | isLoop = mapLoc (glueTrail . (<> f (take (length ts * 2 - 1) $ ss es (ts ++ [t])))) t
| otherwise = mapLoc (<> f (ss es ts)) t
ss es' ts' = concat [[test a b $ j ml r e a b, Just $ unLoc b] | (e,(a,b)) <- zip es' . (zip <*> tail) $ ts']
test a b tj
| atStart b `distance` atEnd a > epsilon = Just tj
| otherwise = Nothing
f = mconcat . catMaybes
fromLineJoin
:: RealFloat n => LineJoin -> n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
fromLineJoin j = case j of
LineJoinMiter -> joinSegmentIntersect
LineJoinRound -> joinSegmentArc
LineJoinBevel -> joinSegmentClip
joinSegmentCut : : ( OrderedField n ) = > n - > n - > Point V2 n - > Located ( Trail V2 n ) - > Located ( Trail V2 n ) - > Trail V2 n
joinSegmentCut _ _ e a b = fromSegments
[ straight ( e .- . atEnd a )
, straight ( atStart b .- . e )
]
joinSegmentCut :: (OrderedField n) => n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
joinSegmentCut _ _ e a b = fromSegments
[ straight (e .-. atEnd a)
, straight (atStart b .-. e)
]
-}
joinSegmentClip :: RealFloat n
=> n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
joinSegmentClip _ _ _ a b = fromSegments [straight $ atStart b .-. atEnd a]
joinSegmentArc :: RealFloat n
=> n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
joinSegmentArc _ r e a b = capArc r e (atEnd a) (atStart b)
joinSegmentIntersect
:: RealFloat n => n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
joinSegmentIntersect miterLimit r e a b =
if cross < 0.000001
then clip
else case traceP pa va t of
Nothing -> clip
Just p
| p `distance` pb > abs (miterLimit * r) -> clip
| otherwise -> unLoc $ fromVertices [ pa, p, pb ]
where
t = straight (miter vb) `at` pb
va = unitPerp (pa .-. e)
vb = negated $ unitPerp (pb .-. e)
pa = atEnd a
pb = atStart b
miter v = abs (miterLimit * r) *^ v
clip = joinSegmentClip miterLimit r e a b
cross = let (xa,ya) = unr2 va; (xb,yb) = unr2 vb in abs (xa * yb - xb * ya)
|
701db83779b3c0224436a117235e75f13726a5c3db0346a48f5bbeec33528358 | CyberCat-Institute/open-game-engine | RuntimeAST.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE DeriveFunctor #
module OpenGames.Preprocessor.RuntimeAST where
import Data.List (intercalate)
import Language.Haskell.TH
newtype Variables p = Variables {vars :: [p]} deriving (Eq)
newtype Expressions e = Expressions {exps :: [e]} deriving (Eq, Functor)
tuple :: [String] -> String
tuple [x] = x
tuple xs = "(" ++ intercalate ", " xs ++ ")"
instance Show (Variables String) where show = tuple . vars
instance Show (Expressions String) where show = tuple . exps
-- newtype AtomExpression = AtomExpression String
--
instance Show AtomExpression where
show ( AtomExpression e ) = concat [ " ( " , e , " ) " ]
Function expressions are expressions used as inputs to fromLens ( from the class OG )
\x - > x
\x - > ( x , x )
\(x1 , ... , xm ) - > ( e1 , ... , en )
\(x1 , ... , xm ) - > ( ( x1 , ... , xm ) , ( e1 , ... , en ) )
| Multiplex (Variables p) (Variables p) -- \((x1, ..., xm), (y1, ..., yn)) -> (x1, ..., xm, y1, ..., yn)
| Curry (FunctionExpression p e) -- curry f
deriving (Eq, Functor)
flattenVariables :: [Variables p] -> Variables p
flattenVariables = Variables . concat . map vars
instance Show (FunctionExpression String String) where
show Identity = "\\x -> x"
show Copy = "\\x -> (x, x)"
show (Lambda x e) = concat ["\\", show x, " -> ", show e]
show (CopyLambda x e) = concat ["\\", show x, " -> (", show x, ", ", show e, ")"]
show (Multiplex x y) = concat ["\\(", show x, ", ", show y, ") -> ", show (flattenVariables [x, y])]
show (Curry f) = concat ["curry (", show f, ")"]
-- The main abstract datatype targeted by the compiler
data FreeOpenGame p e = Atom e
| Lens (FunctionExpression p e) (FunctionExpression p e)
| Function (FunctionExpression p e) (FunctionExpression p e)
| Counit
| Sequential (FreeOpenGame p e) (FreeOpenGame p e)
| Simultaneous (FreeOpenGame p e) (FreeOpenGame p e)
deriving (Eq, Functor)
instance Show (FreeOpenGame String String) where
show (Atom e) = concat [")", e, ")"]
show (Lens v u) = concat ["fromLens (", show v, ") (", show u, ")"]
show (Function f g) = concat ["fromFunctions (", show f, ") (", show g, ")"]
show Counit = "counit"
show (Sequential g h) = concat ["(", show g, ") >>> (", show h, ")"]
show (Simultaneous g h) = concat ["(", show g, ") &&& (", show h, ")"]
instance Show (FreeOpenGame String Exp) where
show game = show $ fmap show game
| null | https://raw.githubusercontent.com/CyberCat-Institute/open-game-engine/86031c42bf13178554c21cd7ab9e9d18f1ca6963/src/OpenGames/Preprocessor/RuntimeAST.hs | haskell | newtype AtomExpression = AtomExpression String
\((x1, ..., xm), (y1, ..., yn)) -> (x1, ..., xm, y1, ..., yn)
curry f
The main abstract datatype targeted by the compiler | # LANGUAGE FlexibleInstances #
# LANGUAGE DeriveFunctor #
module OpenGames.Preprocessor.RuntimeAST where
import Data.List (intercalate)
import Language.Haskell.TH
newtype Variables p = Variables {vars :: [p]} deriving (Eq)
newtype Expressions e = Expressions {exps :: [e]} deriving (Eq, Functor)
tuple :: [String] -> String
tuple [x] = x
tuple xs = "(" ++ intercalate ", " xs ++ ")"
instance Show (Variables String) where show = tuple . vars
instance Show (Expressions String) where show = tuple . exps
instance Show AtomExpression where
show ( AtomExpression e ) = concat [ " ( " , e , " ) " ]
Function expressions are expressions used as inputs to fromLens ( from the class OG )
\x - > x
\x - > ( x , x )
\(x1 , ... , xm ) - > ( e1 , ... , en )
\(x1 , ... , xm ) - > ( ( x1 , ... , xm ) , ( e1 , ... , en ) )
deriving (Eq, Functor)
flattenVariables :: [Variables p] -> Variables p
flattenVariables = Variables . concat . map vars
instance Show (FunctionExpression String String) where
show Identity = "\\x -> x"
show Copy = "\\x -> (x, x)"
show (Lambda x e) = concat ["\\", show x, " -> ", show e]
show (CopyLambda x e) = concat ["\\", show x, " -> (", show x, ", ", show e, ")"]
show (Multiplex x y) = concat ["\\(", show x, ", ", show y, ") -> ", show (flattenVariables [x, y])]
show (Curry f) = concat ["curry (", show f, ")"]
data FreeOpenGame p e = Atom e
| Lens (FunctionExpression p e) (FunctionExpression p e)
| Function (FunctionExpression p e) (FunctionExpression p e)
| Counit
| Sequential (FreeOpenGame p e) (FreeOpenGame p e)
| Simultaneous (FreeOpenGame p e) (FreeOpenGame p e)
deriving (Eq, Functor)
instance Show (FreeOpenGame String String) where
show (Atom e) = concat [")", e, ")"]
show (Lens v u) = concat ["fromLens (", show v, ") (", show u, ")"]
show (Function f g) = concat ["fromFunctions (", show f, ") (", show g, ")"]
show Counit = "counit"
show (Sequential g h) = concat ["(", show g, ") >>> (", show h, ")"]
show (Simultaneous g h) = concat ["(", show g, ") &&& (", show h, ")"]
instance Show (FreeOpenGame String Exp) where
show game = show $ fmap show game
|
8bb7ea3acc62a88ea155ae7b72703f1f23fde02511401467e4c7b94ea32f4cdf | CompSciCabal/SMRTYPRTY | greg-3.rkt | #lang racket
(require racket/pretty)
(print-as-expression #f)
(pretty-print-abbreviate-read-macros #f)
3.1
(let* ((x 6)
(y (* x x)))
(+ x y))
((lambda (x)
((lambda (y)
(+ x y))
(* x x)))
6)
3.2
(cons 1 2)
(list* 1 2)
3.3
(define (print-dotted d)
(cond ((pair? d) (display "(")
(print-dotted (car d))
(display " . ")
(print-dotted (cdr d))
(display ")"))
(else (write d))))
(print-dotted '(one (2 3 (4 "five" . 6) 7) 8 nine))
(newline)
3.4
(define (print-nicely d)
(cond ((pair? d) (display "(")
(let print* ((a (car d)) (d (cdr d)))
(print-nicely a)
(cond ((pair? d) (display " ") (print* (car d) (cdr d)))
((null? d) (void))
(else (display " . ") (print-nicely d))))
(display ")"))
(else (write d))))
(print-nicely '(one (2 3 (4 "five" . 6) 7) 8 nine))
(newline)
3.9
( define ( len xs ) ( foldr ( lambda ( _ l ) ( + l 1 ) ) 0 xs ) )
(define (len xs) (foldl (lambda (_ l) (+ l 1)) 0 xs))
(len '(1 2 3 4 5))
| null | https://raw.githubusercontent.com/CompSciCabal/SMRTYPRTY/4a5550789c997c20fb7256b81469de1f1fce3514/paip/gregr/greg-3.rkt | racket | #lang racket
(require racket/pretty)
(print-as-expression #f)
(pretty-print-abbreviate-read-macros #f)
3.1
(let* ((x 6)
(y (* x x)))
(+ x y))
((lambda (x)
((lambda (y)
(+ x y))
(* x x)))
6)
3.2
(cons 1 2)
(list* 1 2)
3.3
(define (print-dotted d)
(cond ((pair? d) (display "(")
(print-dotted (car d))
(display " . ")
(print-dotted (cdr d))
(display ")"))
(else (write d))))
(print-dotted '(one (2 3 (4 "five" . 6) 7) 8 nine))
(newline)
3.4
(define (print-nicely d)
(cond ((pair? d) (display "(")
(let print* ((a (car d)) (d (cdr d)))
(print-nicely a)
(cond ((pair? d) (display " ") (print* (car d) (cdr d)))
((null? d) (void))
(else (display " . ") (print-nicely d))))
(display ")"))
(else (write d))))
(print-nicely '(one (2 3 (4 "five" . 6) 7) 8 nine))
(newline)
3.9
( define ( len xs ) ( foldr ( lambda ( _ l ) ( + l 1 ) ) 0 xs ) )
(define (len xs) (foldl (lambda (_ l) (+ l 1)) 0 xs))
(len '(1 2 3 4 5))
| |
0defefaf42694865144be328d56267b15b9cf0d3d87438ec67632328ec1e9d1a | binghe/PCL | kcl-patches.lisp | -*-Mode : LISP ; Package:(PCL LISP 1000 ) ; ; Syntax : Common - lisp -*-
;;;
;;; *************************************************************************
Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation .
;;; All rights reserved.
;;;
;;; Use and copying of this software and preparation of derivative works
;;; based upon this software are permitted. Any distribution of this
software or derivative works must comply with all applicable United
;;; States export control laws.
;;;
This software is made available AS IS , and Xerox Corporation makes no
;;; warranty about the software, its performance or its conformity to any
;;; specification.
;;;
;;; Any person obtaining a copy of this software is requested to send their
;;; name and post office or electronic mail address to:
CommonLoops Coordinator
Xerox PARC
3333 Coyote Hill Rd .
Palo Alto , CA 94304
( or send Arpanet mail to )
;;;
;;; Suggestions, comments and requests for improvements are also welcome.
;;; *************************************************************************
;;;
(in-package "COMPILER")
#+akcl
(eval-when (compile load eval)
(when (<= system::*akcl-version* 609)
(pushnew :pre_akcl_610 *features*))
(if (and (boundp 'si::*akcl-version*)
(>= si::*akcl-version* 604))
(progn
(pushnew :turbo-closure *features*)
(pushnew :turbo-closure-env-size *features*))
(when (fboundp 'si::allocate-growth)
(pushnew :turbo-closure *features*)))
;; patch around compiler bug.
(when (<= si::*akcl-version* 609)
(let ((vcs "static int Vcs;
"))
(unless (search vcs compiler::*cmpinclude-string*)
(setq compiler::*cmpinclude-string*
(concatenate 'string vcs compiler::*cmpinclude-string*)))))
(let ((rset "int Rset;
"))
(unless (search rset compiler::*cmpinclude-string*)
(setq compiler::*cmpinclude-string*
(concatenate 'string rset compiler::*cmpinclude-string*))))
(when (get 'si::basic-wrapper 'si::s-data)
(pushnew :new-kcl-wrapper *features*)
(pushnew :structure-wrapper *features*))
)
#+akcl
(progn
(unless (fboundp 'real-c2lambda-expr-with-key)
(setf (symbol-function 'real-c2lambda-expr-with-key)
(symbol-function 'c2lambda-expr-with-key)))
(defun c2lambda-expr-with-key (lambda-list body)
(declare (special *sup-used*))
(setq *sup-used* t)
(real-c2lambda-expr-with-key lambda-list body))
;There is a bug in the implementation of *print-circle* that
;causes some akcl debugging commands (including :bt and :bl)
to cause the following error when PCL is being used :
;Unrecoverable error: value stack overflow.
When a CLOS object is printed , travel_push_object ends up
;traversing almost the whole class structure, thereby overflowing
;the value-stack.
from lsp / debug.lsp .
* print - circle * is badly implemented in kcl .
it has two separate problems that should be fixed :
1 . it traverses the printed object putting all objects found
; on the value stack (rather than in a hash table or some
; other structure; this is a problem because the size of the value stack
; is fixed, and a potentially unbounded number of objects
; need to be traversed), and
2 . it blindly traverses all slots of any
; kind of structure including std-object structures.
; This is safe, but not always necessary, and is very time-consuming
for CLOS objects ( because it will always traverse every class ) .
;For now, avoid using *print-circle* T when it will cause problems.
(eval-when (compile eval)
(defmacro si::f (op &rest args)
`(the fixnum (,op ,@ (mapcar #'(lambda (x) `(the fixnum ,x)) args) )))
(defmacro si::fb (op &rest args)
`(,op ,@ (mapcar #'(lambda (x) `(the fixnum ,x)) args) ))
)
(defun si::display-env (n env)
(do ((v (reverse env) (cdr v)))
((or (not (consp v)) (si::fb > (fill-pointer si::*display-string*) n)))
(or (and (consp (car v))
(listp (cdar v)))
(return))
(let ((*print-circle* (can-use-print-circle-p (cadar v))))
(format si::*display-string* "~s=~s~@[,~]" (caar v) (cadar v) (cdr v)))))
(defun si::display-compiled-env ( plength ihs &aux
(base (si::ihs-vs ihs))
(end (min (si::ihs-vs (1+ ihs)) (si::vs-top))))
(format si::*display-string* "")
(do ((i base )
(v (get (si::ihs-fname ihs) 'si::debug) (cdr v)))
((or (si::fb >= i end)(si::fb > (fill-pointer si::*display-string*) plength)))
(let ((*print-circle* (can-use-print-circle-p (si::vs i))))
(format si::*display-string* "~a~@[~d~]=~s~@[,~]"
(or (car v) 'si::loc) (if (not (car v)) (si::f - i base)) (si::vs i)
(si::fb < (setq i (si::f + i 1)) end)))))
(clines "#define objnull_p(x) ((x==OBJNULL)?Ct:Cnil)")
(defentry objnull-p (object) (object "objnull_p"))
(defun can-use-print-circle-p (x)
(catch 'can-use-print-circle-p
(can-use-print-circle-p1 x nil)))
(defun can-use-print-circle-p1 (x so-far)
(and (not (objnull-p x)) ; because of deficiencies in the compiler, maybe?
(if (member x so-far)
(throw 'can-use-print-circle-p t)
(let ((so-far (cons x so-far)))
(flet ((can-use-print-circle-p (x)
(can-use-print-circle-p1 x so-far)))
(typecase x
(vector (or (not (eq 't (array-element-type x)))
(every #'can-use-print-circle-p x)))
(cons (and (can-use-print-circle-p (car x))
(can-use-print-circle-p (cdr x))))
(array (or (not (eq 't (array-element-type x)))
(let* ((rank (array-rank x))
(dimensions (make-list rank)))
(dotimes (i rank)
(setf (nth i dimensions) (array-dimension x i)))
(or (member 0 dimensions)
(do ((cursor (make-list rank :initial-element 0)))
(nil)
(declare (:dynamic-extent cursor))
(unless (can-use-print-circle-p
(apply #'aref x cursor))
(return nil))
(when (si::increment-cursor cursor dimensions)
(return t)))))))
(t (or (not (si:structurep x))
(let* ((def (si:structure-def x))
(name (si::s-data-name def))
(len (si::s-data-length def))
(pfun (si::s-data-print-function def)))
(and (null pfun)
(dotimes (i len t)
(unless (can-use-print-circle-p
(si:structure-ref x name i))
(return nil)))))))))))))
(defun si::apply-display-fun (display-fun n lis)
(let ((*print-length* si::*debug-print-level*)
(*print-level* si::*debug-print-level*)
(*print-pretty* nil)
(*PRINT-CASE* :downcase)
(*print-circle* nil)
)
(setf (fill-pointer si::*display-string*) 0)
(format si::*display-string* "{")
(funcall display-fun n lis)
(when (si::fb > (fill-pointer si::*display-string*) n)
(setf (fill-pointer si::*display-string*) n)
(format si::*display-string* "..."))
(format si::*display-string* "}")
)
si::*display-string*
)
;The old definition of this had a bug:
;sometimes it returned without calling mv-values.
(defun si::next-stack-frame (ihs &aux line-info li i k na)
(cond ((si::fb < ihs si::*ihs-base*)
(si::mv-values nil nil nil nil nil))
((let (fun)
;; next lower visible ihs
(si::mv-setq (fun i) (si::get-next-visible-fun ihs))
(setq na fun)
(cond ((and (setq line-info (get fun 'si::line-info))
(do ((j (si::f + ihs 1) (si::f - j 1))
(form ))
((<= j i) nil)
(setq form (si::ihs-fun j))
(cond ((setq li (si::get-line-of-form form line-info))
(return-from si::next-stack-frame
(si::mv-values
i fun li
;; filename
(car (aref line-info 0))
;;environment
(list (si::vs (setq k (si::ihs-vs j)))
(si::vs (1+ k))
(si::vs (+ k 2)))))))))))))
((and (not (special-form-p na))
(not (get na 'si::dbl-invisible))
(fboundp na))
(si::mv-values i na nil nil
(if (si::ihs-not-interpreted-env i)
nil
(let ((i (si::ihs-vs i)))
(list (si::vs i) (si::vs (1+ i)) (si::vs (si::f + i 2)))))))
(t (si::mv-values nil nil nil nil nil))))
)
#+pre_akcl_610
(progn
( proclaim ' ( optimize ( safety 0 ) ( speed 3 ) ( space 1 ) ) )
;Not needed... make-top-level-form generates defuns now.
( setq compiler::*compile - ordinaries * t )
(eval-when (compile load eval)
(unless (fboundp 'original-co1typep)
(setf (symbol-function 'original-co1typep) #'co1typep))
)
(defun new-co1typep (f args)
(or (original-co1typep f args)
(let ((x (car args))
(type (cadr args)))
(when (constantp type)
(let ((ntype (si::normalize-type (eval type))))
(when (and (eq (car ntype) 'satisfies)
(cadr ntype)
(symbolp (cadr ntype))
(symbol-package (cadr ntype)))
(c1expr `(the boolean (,(cadr ntype) ,x)))))))))
(setf (symbol-function 'co1typep) #'new-co1typep)
)
#-(or akcl xkcl)
(progn
(in-package 'system)
This makes DEFMACRO take & WHOLE and & ENVIRONMENT args anywhere
in the lambda - list . The former allows deviation from the CL spec ,
;;; but what the heck.
(eval-when (compile) (proclaim '(optimize (safety 2) (space 3))))
(defvar *old-defmacro*)
(defun new-defmacro (whole env)
(flet ((call-old-definition (new-whole)
(funcall *old-defmacro* new-whole env)))
(if (not (and (consp whole)
(consp (cdr whole))
(consp (cddr whole))
(consp (cdddr whole))))
(call-old-definition whole)
(let* ((ll (caddr whole))
(env-tail (do ((tail ll (cdr tail)))
((not (consp tail)) nil)
(when (eq '&environment (car tail))
(return tail)))))
(if env-tail
(call-old-definition (list* (car whole)
(cadr whole)
(append (list '&environment
(cadr env-tail))
(ldiff ll env-tail)
(cddr env-tail))
(cdddr whole)))
(call-old-definition whole))))))
(eval-when (load eval)
(unless (boundp '*old-defmacro*)
(setq *old-defmacro* (macro-function 'defmacro))
(setf (macro-function 'defmacro) #'new-defmacro)))
;;;
setf patches
;;;
(defun get-setf-method (form)
(multiple-value-bind (vars vals stores store-form access-form)
(get-setf-method-multiple-value form)
(unless (listp vars)
(error
"The temporary variables component, ~s,
of the setf-method for ~s is not a list."
vars form))
(unless (listp vals)
(error
"The values forms component, ~s,
of the setf-method for ~s is not a list."
vals form))
(unless (listp stores)
(error
"The store variables component, ~s,
of the setf-method for ~s is not a list."
stores form))
(unless (= (list-length stores) 1)
(error "Multiple store-variables are not allowed."))
(values vars vals stores store-form access-form)))
(defun get-setf-method-multiple-value (form)
(cond ((symbolp form)
(let ((store (gensym)))
(values nil nil (list store) `(setq ,form ,store) form)))
((or (not (consp form)) (not (symbolp (car form))))
(error "Cannot get the setf-method of ~S." form))
((get (car form) 'setf-method)
(apply (get (car form) 'setf-method) (cdr form)))
((get (car form) 'setf-update-fn)
(let ((vars (mapcar #'(lambda (x)
(declare (ignore x))
(gensym))
(cdr form)))
(store (gensym)))
(values vars (cdr form) (list store)
`(,(get (car form) 'setf-update-fn)
,@vars ,store)
(cons (car form) vars))))
((get (car form) 'setf-lambda)
(let* ((vars (mapcar #'(lambda (x)
(declare (ignore x))
(gensym))
(cdr form)))
(store (gensym))
(l (get (car form) 'setf-lambda))
(f `(lambda ,(car l)
(funcall #'(lambda ,(cadr l) ,@(cddr l))
',store))))
(values vars (cdr form) (list store)
(apply f vars)
(cons (car form) vars))))
((macro-function (car form))
(get-setf-method-multiple-value (macroexpand-1 form)))
(t
(error "Cannot expand the SETF form ~S." form))))
)
| null | https://raw.githubusercontent.com/binghe/PCL/7021c061c5eef1466e563c4abb664ab468ee0d80/impl/kcl/kcl-patches.lisp | lisp | Package:(PCL LISP 1000 ) ; ; Syntax : Common - lisp -*-
*************************************************************************
All rights reserved.
Use and copying of this software and preparation of derivative works
based upon this software are permitted. Any distribution of this
States export control laws.
warranty about the software, its performance or its conformity to any
specification.
Any person obtaining a copy of this software is requested to send their
name and post office or electronic mail address to:
Suggestions, comments and requests for improvements are also welcome.
*************************************************************************
patch around compiler bug.
There is a bug in the implementation of *print-circle* that
causes some akcl debugging commands (including :bt and :bl)
Unrecoverable error: value stack overflow.
traversing almost the whole class structure, thereby overflowing
the value-stack.
on the value stack (rather than in a hash table or some
other structure; this is a problem because the size of the value stack
is fixed, and a potentially unbounded number of objects
need to be traversed), and
kind of structure including std-object structures.
This is safe, but not always necessary, and is very time-consuming
For now, avoid using *print-circle* T when it will cause problems.
because of deficiencies in the compiler, maybe?
The old definition of this had a bug:
sometimes it returned without calling mv-values.
next lower visible ihs
filename
environment
Not needed... make-top-level-form generates defuns now.
but what the heck.
| Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation .
software or derivative works must comply with all applicable United
This software is made available AS IS , and Xerox Corporation makes no
CommonLoops Coordinator
Xerox PARC
3333 Coyote Hill Rd .
Palo Alto , CA 94304
( or send Arpanet mail to )
(in-package "COMPILER")
#+akcl
(eval-when (compile load eval)
(when (<= system::*akcl-version* 609)
(pushnew :pre_akcl_610 *features*))
(if (and (boundp 'si::*akcl-version*)
(>= si::*akcl-version* 604))
(progn
(pushnew :turbo-closure *features*)
(pushnew :turbo-closure-env-size *features*))
(when (fboundp 'si::allocate-growth)
(pushnew :turbo-closure *features*)))
(when (<= si::*akcl-version* 609)
"))
(unless (search vcs compiler::*cmpinclude-string*)
(setq compiler::*cmpinclude-string*
(concatenate 'string vcs compiler::*cmpinclude-string*)))))
"))
(unless (search rset compiler::*cmpinclude-string*)
(setq compiler::*cmpinclude-string*
(concatenate 'string rset compiler::*cmpinclude-string*))))
(when (get 'si::basic-wrapper 'si::s-data)
(pushnew :new-kcl-wrapper *features*)
(pushnew :structure-wrapper *features*))
)
#+akcl
(progn
(unless (fboundp 'real-c2lambda-expr-with-key)
(setf (symbol-function 'real-c2lambda-expr-with-key)
(symbol-function 'c2lambda-expr-with-key)))
(defun c2lambda-expr-with-key (lambda-list body)
(declare (special *sup-used*))
(setq *sup-used* t)
(real-c2lambda-expr-with-key lambda-list body))
to cause the following error when PCL is being used :
When a CLOS object is printed , travel_push_object ends up
from lsp / debug.lsp .
* print - circle * is badly implemented in kcl .
it has two separate problems that should be fixed :
1 . it traverses the printed object putting all objects found
2 . it blindly traverses all slots of any
for CLOS objects ( because it will always traverse every class ) .
(eval-when (compile eval)
(defmacro si::f (op &rest args)
`(the fixnum (,op ,@ (mapcar #'(lambda (x) `(the fixnum ,x)) args) )))
(defmacro si::fb (op &rest args)
`(,op ,@ (mapcar #'(lambda (x) `(the fixnum ,x)) args) ))
)
(defun si::display-env (n env)
(do ((v (reverse env) (cdr v)))
((or (not (consp v)) (si::fb > (fill-pointer si::*display-string*) n)))
(or (and (consp (car v))
(listp (cdar v)))
(return))
(let ((*print-circle* (can-use-print-circle-p (cadar v))))
(format si::*display-string* "~s=~s~@[,~]" (caar v) (cadar v) (cdr v)))))
(defun si::display-compiled-env ( plength ihs &aux
(base (si::ihs-vs ihs))
(end (min (si::ihs-vs (1+ ihs)) (si::vs-top))))
(format si::*display-string* "")
(do ((i base )
(v (get (si::ihs-fname ihs) 'si::debug) (cdr v)))
((or (si::fb >= i end)(si::fb > (fill-pointer si::*display-string*) plength)))
(let ((*print-circle* (can-use-print-circle-p (si::vs i))))
(format si::*display-string* "~a~@[~d~]=~s~@[,~]"
(or (car v) 'si::loc) (if (not (car v)) (si::f - i base)) (si::vs i)
(si::fb < (setq i (si::f + i 1)) end)))))
(clines "#define objnull_p(x) ((x==OBJNULL)?Ct:Cnil)")
(defentry objnull-p (object) (object "objnull_p"))
(defun can-use-print-circle-p (x)
(catch 'can-use-print-circle-p
(can-use-print-circle-p1 x nil)))
(defun can-use-print-circle-p1 (x so-far)
(if (member x so-far)
(throw 'can-use-print-circle-p t)
(let ((so-far (cons x so-far)))
(flet ((can-use-print-circle-p (x)
(can-use-print-circle-p1 x so-far)))
(typecase x
(vector (or (not (eq 't (array-element-type x)))
(every #'can-use-print-circle-p x)))
(cons (and (can-use-print-circle-p (car x))
(can-use-print-circle-p (cdr x))))
(array (or (not (eq 't (array-element-type x)))
(let* ((rank (array-rank x))
(dimensions (make-list rank)))
(dotimes (i rank)
(setf (nth i dimensions) (array-dimension x i)))
(or (member 0 dimensions)
(do ((cursor (make-list rank :initial-element 0)))
(nil)
(declare (:dynamic-extent cursor))
(unless (can-use-print-circle-p
(apply #'aref x cursor))
(return nil))
(when (si::increment-cursor cursor dimensions)
(return t)))))))
(t (or (not (si:structurep x))
(let* ((def (si:structure-def x))
(name (si::s-data-name def))
(len (si::s-data-length def))
(pfun (si::s-data-print-function def)))
(and (null pfun)
(dotimes (i len t)
(unless (can-use-print-circle-p
(si:structure-ref x name i))
(return nil)))))))))))))
(defun si::apply-display-fun (display-fun n lis)
(let ((*print-length* si::*debug-print-level*)
(*print-level* si::*debug-print-level*)
(*print-pretty* nil)
(*PRINT-CASE* :downcase)
(*print-circle* nil)
)
(setf (fill-pointer si::*display-string*) 0)
(format si::*display-string* "{")
(funcall display-fun n lis)
(when (si::fb > (fill-pointer si::*display-string*) n)
(setf (fill-pointer si::*display-string*) n)
(format si::*display-string* "..."))
(format si::*display-string* "}")
)
si::*display-string*
)
(defun si::next-stack-frame (ihs &aux line-info li i k na)
(cond ((si::fb < ihs si::*ihs-base*)
(si::mv-values nil nil nil nil nil))
((let (fun)
(si::mv-setq (fun i) (si::get-next-visible-fun ihs))
(setq na fun)
(cond ((and (setq line-info (get fun 'si::line-info))
(do ((j (si::f + ihs 1) (si::f - j 1))
(form ))
((<= j i) nil)
(setq form (si::ihs-fun j))
(cond ((setq li (si::get-line-of-form form line-info))
(return-from si::next-stack-frame
(si::mv-values
i fun li
(car (aref line-info 0))
(list (si::vs (setq k (si::ihs-vs j)))
(si::vs (1+ k))
(si::vs (+ k 2)))))))))))))
((and (not (special-form-p na))
(not (get na 'si::dbl-invisible))
(fboundp na))
(si::mv-values i na nil nil
(if (si::ihs-not-interpreted-env i)
nil
(let ((i (si::ihs-vs i)))
(list (si::vs i) (si::vs (1+ i)) (si::vs (si::f + i 2)))))))
(t (si::mv-values nil nil nil nil nil))))
)
#+pre_akcl_610
(progn
( proclaim ' ( optimize ( safety 0 ) ( speed 3 ) ( space 1 ) ) )
( setq compiler::*compile - ordinaries * t )
(eval-when (compile load eval)
(unless (fboundp 'original-co1typep)
(setf (symbol-function 'original-co1typep) #'co1typep))
)
(defun new-co1typep (f args)
(or (original-co1typep f args)
(let ((x (car args))
(type (cadr args)))
(when (constantp type)
(let ((ntype (si::normalize-type (eval type))))
(when (and (eq (car ntype) 'satisfies)
(cadr ntype)
(symbolp (cadr ntype))
(symbol-package (cadr ntype)))
(c1expr `(the boolean (,(cadr ntype) ,x)))))))))
(setf (symbol-function 'co1typep) #'new-co1typep)
)
#-(or akcl xkcl)
(progn
(in-package 'system)
This makes DEFMACRO take & WHOLE and & ENVIRONMENT args anywhere
in the lambda - list . The former allows deviation from the CL spec ,
(eval-when (compile) (proclaim '(optimize (safety 2) (space 3))))
(defvar *old-defmacro*)
(defun new-defmacro (whole env)
(flet ((call-old-definition (new-whole)
(funcall *old-defmacro* new-whole env)))
(if (not (and (consp whole)
(consp (cdr whole))
(consp (cddr whole))
(consp (cdddr whole))))
(call-old-definition whole)
(let* ((ll (caddr whole))
(env-tail (do ((tail ll (cdr tail)))
((not (consp tail)) nil)
(when (eq '&environment (car tail))
(return tail)))))
(if env-tail
(call-old-definition (list* (car whole)
(cadr whole)
(append (list '&environment
(cadr env-tail))
(ldiff ll env-tail)
(cddr env-tail))
(cdddr whole)))
(call-old-definition whole))))))
(eval-when (load eval)
(unless (boundp '*old-defmacro*)
(setq *old-defmacro* (macro-function 'defmacro))
(setf (macro-function 'defmacro) #'new-defmacro)))
setf patches
(defun get-setf-method (form)
(multiple-value-bind (vars vals stores store-form access-form)
(get-setf-method-multiple-value form)
(unless (listp vars)
(error
"The temporary variables component, ~s,
of the setf-method for ~s is not a list."
vars form))
(unless (listp vals)
(error
"The values forms component, ~s,
of the setf-method for ~s is not a list."
vals form))
(unless (listp stores)
(error
"The store variables component, ~s,
of the setf-method for ~s is not a list."
stores form))
(unless (= (list-length stores) 1)
(error "Multiple store-variables are not allowed."))
(values vars vals stores store-form access-form)))
(defun get-setf-method-multiple-value (form)
(cond ((symbolp form)
(let ((store (gensym)))
(values nil nil (list store) `(setq ,form ,store) form)))
((or (not (consp form)) (not (symbolp (car form))))
(error "Cannot get the setf-method of ~S." form))
((get (car form) 'setf-method)
(apply (get (car form) 'setf-method) (cdr form)))
((get (car form) 'setf-update-fn)
(let ((vars (mapcar #'(lambda (x)
(declare (ignore x))
(gensym))
(cdr form)))
(store (gensym)))
(values vars (cdr form) (list store)
`(,(get (car form) 'setf-update-fn)
,@vars ,store)
(cons (car form) vars))))
((get (car form) 'setf-lambda)
(let* ((vars (mapcar #'(lambda (x)
(declare (ignore x))
(gensym))
(cdr form)))
(store (gensym))
(l (get (car form) 'setf-lambda))
(f `(lambda ,(car l)
(funcall #'(lambda ,(cadr l) ,@(cddr l))
',store))))
(values vars (cdr form) (list store)
(apply f vars)
(cons (car form) vars))))
((macro-function (car form))
(get-setf-method-multiple-value (macroexpand-1 form)))
(t
(error "Cannot expand the SETF form ~S." form))))
)
|
885a635e5fd3d979f67e7ff076924bff9fc3040c847bb6bf6a4ded53a26a9985 | the-dr-lazy/cascade | Options.hs | |
Module : Cascade . CLI.Data . Contract . Shell . Options
Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! !
Copyright : ( c ) 2020 - 2021 Cascade
License : MPL 2.0
Maintainer : < > ( the-dr-lazy.github.io )
Stability : Stable
Portability : POSIX
! ! ! INSERT MODULE LONG DESCRIPTION ! ! !
Module : Cascade.CLI.Data.Contract.Shell.Options
Description : !!! INSERT MODULE SHORT DESCRIPTION !!!
Copyright : (c) 2020-2021 Cascade
License : MPL 2.0
Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io)
Stability : Stable
Portability : POSIX
!!! INSERT MODULE LONG DESCRIPTION !!!
-}
module Cascade.CLI.Data.Contract.Shell.Options
( readConfig
) where
import qualified Cascade.CLI.Data.Contract.Shell.Environment.Var as Environment.Var
import Cascade.CLI.Data.Model.Config ( ConfigP (..) )
import qualified Cascade.CLI.Data.Model.Config as Config
import qualified Cascade.CLI.Data.Model.Config.Default as Config.Default
import Data.Version ( showVersion )
import Development.GitRev ( gitCommitDate, gitHash )
import Options.Applicative
( Mod, Parser, ParserInfo, auto, execParser, fullDesc, help, helper, info, infoOption, long,
metavar, option, progDesc, short, str )
import qualified Paths_cascade_cli as Meta ( version )
data Postgres = Postgres { host :: Maybe String
, port :: Maybe Word16
, user :: Maybe String
, password :: Maybe String
, database :: Maybe String
}
data Options = Options { httpPort :: Maybe Word16
, postgres :: Postgres
}
helpWithDefault :: String -> String -> Mod f a
helpWithDefault s def = help <| s <> " (default: " <> def <> ")"
postgresOptionsP :: Parser Postgres
postgresOptionsP = do
host <-
optional
. option str
. mconcat
<| [long "postgres-host", metavar Environment.Var.cascadePostgresHost, helpWithDefault "PostgreSQL host" Config.Default.postgresHost]
port <-
optional
. option auto
. mconcat
<| [ long "postgres-port"
, metavar Environment.Var.cascadePostgresPort
, helpWithDefault "PostgresSQL port" (show Config.Default.postgresPort)
]
user <-
optional
. option str
. mconcat
<| [long "postgres-user", metavar Environment.Var.cascadePostgresUser, helpWithDefault "PostgreSQL user" Config.Default.postgresUser]
password <-
optional
. option str
. mconcat
<| [ long "postgres-password"
, metavar Environment.Var.cascadePostgresPassword
, helpWithDefault "PostgreSQL passowrd" Config.Default.postgresPassword
]
database <-
optional
. option str
. mconcat
<| [ long "postgres-database"
, metavar Environment.Var.cascadePostgresDatabase
, helpWithDefault "PostgreSQL database" Config.Default.postgresDatabase
]
pure Postgres { .. }
optionsP :: Parser Options
optionsP = do
httpPort <-
optional
. option auto
. mconcat
<| [long "http-port", metavar Environment.Var.cascadeHttpPort, helpWithDefault "Port number of Cascade Api" (show Config.Default.httpPort)]
postgres <- postgresOptionsP
pure Options { .. }
cascadeVersion :: String
cascadeVersion = intercalate "\n" [cVersion, cHash, cDate]
where
cVersion, cHash, cDate :: String
cVersion = "Cascade CLI v" <> showVersion Meta.version
cHash = "Git revision: " <> $(gitHash)
cDate = "Last commit: " <> $(gitCommitDate)
versionP :: Parser (a -> a)
versionP = infoOption cascadeVersion <| mconcat [long "version", short 'v', help "Show cascade's version"]
cliP :: ParserInfo Options
cliP = info (helper <*> versionP <*> optionsP) <| fullDesc <> progDesc "Cascade CLI"
toPartialConfig :: Options -> Config.Partial
toPartialConfig Options {..} = Config
{ httpPort = Last httpPort
, postgres = let Postgres {..} = postgres
in Config.Postgres { host = Last host, port = Last port, user = Last user, password = Last password, database = Last database }
}
readConfig :: IO Config.Partial
readConfig = toPartialConfig <$> execParser cliP
| null | https://raw.githubusercontent.com/the-dr-lazy/cascade/014a5589a2763ce373e8c84a211cddc479872b44/cascade-cli/src/Cascade/CLI/Data/Contract/Shell/Options.hs | haskell | |
Module : Cascade . CLI.Data . Contract . Shell . Options
Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! !
Copyright : ( c ) 2020 - 2021 Cascade
License : MPL 2.0
Maintainer : < > ( the-dr-lazy.github.io )
Stability : Stable
Portability : POSIX
! ! ! INSERT MODULE LONG DESCRIPTION ! ! !
Module : Cascade.CLI.Data.Contract.Shell.Options
Description : !!! INSERT MODULE SHORT DESCRIPTION !!!
Copyright : (c) 2020-2021 Cascade
License : MPL 2.0
Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io)
Stability : Stable
Portability : POSIX
!!! INSERT MODULE LONG DESCRIPTION !!!
-}
module Cascade.CLI.Data.Contract.Shell.Options
( readConfig
) where
import qualified Cascade.CLI.Data.Contract.Shell.Environment.Var as Environment.Var
import Cascade.CLI.Data.Model.Config ( ConfigP (..) )
import qualified Cascade.CLI.Data.Model.Config as Config
import qualified Cascade.CLI.Data.Model.Config.Default as Config.Default
import Data.Version ( showVersion )
import Development.GitRev ( gitCommitDate, gitHash )
import Options.Applicative
( Mod, Parser, ParserInfo, auto, execParser, fullDesc, help, helper, info, infoOption, long,
metavar, option, progDesc, short, str )
import qualified Paths_cascade_cli as Meta ( version )
data Postgres = Postgres { host :: Maybe String
, port :: Maybe Word16
, user :: Maybe String
, password :: Maybe String
, database :: Maybe String
}
data Options = Options { httpPort :: Maybe Word16
, postgres :: Postgres
}
helpWithDefault :: String -> String -> Mod f a
helpWithDefault s def = help <| s <> " (default: " <> def <> ")"
postgresOptionsP :: Parser Postgres
postgresOptionsP = do
host <-
optional
. option str
. mconcat
<| [long "postgres-host", metavar Environment.Var.cascadePostgresHost, helpWithDefault "PostgreSQL host" Config.Default.postgresHost]
port <-
optional
. option auto
. mconcat
<| [ long "postgres-port"
, metavar Environment.Var.cascadePostgresPort
, helpWithDefault "PostgresSQL port" (show Config.Default.postgresPort)
]
user <-
optional
. option str
. mconcat
<| [long "postgres-user", metavar Environment.Var.cascadePostgresUser, helpWithDefault "PostgreSQL user" Config.Default.postgresUser]
password <-
optional
. option str
. mconcat
<| [ long "postgres-password"
, metavar Environment.Var.cascadePostgresPassword
, helpWithDefault "PostgreSQL passowrd" Config.Default.postgresPassword
]
database <-
optional
. option str
. mconcat
<| [ long "postgres-database"
, metavar Environment.Var.cascadePostgresDatabase
, helpWithDefault "PostgreSQL database" Config.Default.postgresDatabase
]
pure Postgres { .. }
optionsP :: Parser Options
optionsP = do
httpPort <-
optional
. option auto
. mconcat
<| [long "http-port", metavar Environment.Var.cascadeHttpPort, helpWithDefault "Port number of Cascade Api" (show Config.Default.httpPort)]
postgres <- postgresOptionsP
pure Options { .. }
cascadeVersion :: String
cascadeVersion = intercalate "\n" [cVersion, cHash, cDate]
where
cVersion, cHash, cDate :: String
cVersion = "Cascade CLI v" <> showVersion Meta.version
cHash = "Git revision: " <> $(gitHash)
cDate = "Last commit: " <> $(gitCommitDate)
versionP :: Parser (a -> a)
versionP = infoOption cascadeVersion <| mconcat [long "version", short 'v', help "Show cascade's version"]
cliP :: ParserInfo Options
cliP = info (helper <*> versionP <*> optionsP) <| fullDesc <> progDesc "Cascade CLI"
toPartialConfig :: Options -> Config.Partial
toPartialConfig Options {..} = Config
{ httpPort = Last httpPort
, postgres = let Postgres {..} = postgres
in Config.Postgres { host = Last host, port = Last port, user = Last user, password = Last password, database = Last database }
}
readConfig :: IO Config.Partial
readConfig = toPartialConfig <$> execParser cliP
| |
3d2870d79c6841a124ec54a02756ea743325a38a24e4fccb89b3e9904479aca9 | azimut/shiny | cc.lisp | (in-package :shiny)
(bbuffer-load "/home/sendai/clips/arvo1.wav")
(bbplay "arvo1.wav" :amp .2)
(put-phrase "sound" "arvo1.wav" 3 4.4)
(put-phrase "kill" "arvo1.wav" 25 3.5)
(put-phrase "free" "arvo1.wav" 53 3.5)
(put-phrase "art" "arvo1.wav" 57 3)
(put-phrase "but" "arvo1.wav" 61 3)
(put-phrase "necessary" "arvo1.wav" 64 2.5)
(word-play "sound" :amp .2)
(word-play "kill" :amp .2)
(word-play "free" :amp .2)
(word-play "art" :amp .2)
(word-play "but" :amp .2)
(word-play "necessary" :amp .2)
(bbuffer-load "/home/sendai/clips/obsession.wav")
(put-phrase "obsessed" "obsession.wav" 1.8 .4)
(put-phrase "mind" "obsession.wav" .4 2.8)
(put-phrase "filter" "obsession.wav" 3.5 4)
(bbuffer-load "/home/sendai/clips/go.wav")
(bbplay "go.wav" :amp .2)
(put-phrase "cosmos" "go.wav" 0 5)
(put-phrase "simple" "go.wav" 6.45 3.95)
(put-phrase "endless" "go.wav" 11 3.6)
(word-play "cosmos" :amp .2 :downsamp 8 :beat-length 4)
(word-play "simple" :amp .2 :downsamp 6 :beat-length 4)
(word-play "endless" :amp .2 :downsamp 8 :beat-length 4)
(word-play "mind" :amp .5 :downsamp 6)
(word-play "filter" :amp .5 :downsamp 6)
(aat (tempo-sync #[4 b]) #'f it 0 -12 20)
(aat (tempo-sync #[4 b]) #'f it 1 0 100)
(aat (tempo-sync #[4 b]) #'f it 2 12 64)
(aat (tempo-sync #[4 b]) #'f it 2 24 64)
(fp 2 1)
(fp 0 37)
(fg 1f0)
(defparameter *golang*
(new cycle
:of '("cosmos" "simple" "endless")
:repeat 1))
(defparameter *art*
(new cycle
:of '("art" "but" "necessary")
:repeat 1))
(fg .5)
(defparameter *c0* 0)
(defun f ())
(let* ((d (pval *c0*))
(s (ov-scale :C3 :phrygian))
(n (nths '(4 2 1 3 2) s))
(c (nths '(0 5 6 7) s))
(p (new weighting
:of
`((,c :weight 1)
(,n :weight ,d)
((0) :weight .25 :max 1))))
(q (make-weighting
(list 1/16 1/8 (make-cycle 1/32 2)))))
(defun f (time chan offset pan)
(unless (= chan 0)
(let ((r (rhythm (next q) 20))
(note (pickl (next p))))
(when (not (= note 0))
(and (odds .1) (incf *c0* .01))
(when (= chan 0)
(unless (node-alive 38)
(when (odds .1) (word-play (next *golang*) :id 38 :amp .4 :pan (pick .2 .5 .8))))
(if (member note n)
(viseq:push-cvideo
:pi "/home/sendai/clips/pi.mp4"
: pos 23
)
(viseq:push-cvideo
:pi "/home/sendai/clips/pi.mp4"
:pos 22
:rotation (between 10f0 40f0)
:xpos 50
:ypos 50
))
(at (+ time #[1 b]) #'viseq:delete-cvideo :pi))
(when (= chan 1)
(if (member note n)
(viseq:push-cvideo
:pi2 "/home/sendai/clips/pi-rest.mp4"
:pos 40
:repeat (pick 2 4)
:is-negative t)
(viseq:push-cvideo
:pi2 "/home/sendai/clips/pi-rest.mp4"
:pos (between 10 40)
))
(at (+ time #[2 b]) #'viseq:delete-cvideo :pi2))
(when (and (odds .1) (= chan 2))
(unless (node-alive 38)
(when (word-play (pick "art" "necessary" "kill" "sound" "free")
:downsamp (pick 4 8)
:id 38 :amp .4 :pan (pick .2 .5 .8))
(viseq:push-ctext :obs (pick "car" "la") (between 20 50) (between 20 50))
(at (+ time #[3 b]) #'viseq:delete-ctext :obs))))
(p
time
(cm:transpose note offset)
(rcosr 43 3 4)
r
chan
:pan pan))
(aat (+ time #[r b]) #'f it chan offset pan)))))
| null | https://raw.githubusercontent.com/azimut/shiny/774381a9bde21c4ec7e7092c7516dd13a5a50780/compositions/cc.lisp | lisp | (in-package :shiny)
(bbuffer-load "/home/sendai/clips/arvo1.wav")
(bbplay "arvo1.wav" :amp .2)
(put-phrase "sound" "arvo1.wav" 3 4.4)
(put-phrase "kill" "arvo1.wav" 25 3.5)
(put-phrase "free" "arvo1.wav" 53 3.5)
(put-phrase "art" "arvo1.wav" 57 3)
(put-phrase "but" "arvo1.wav" 61 3)
(put-phrase "necessary" "arvo1.wav" 64 2.5)
(word-play "sound" :amp .2)
(word-play "kill" :amp .2)
(word-play "free" :amp .2)
(word-play "art" :amp .2)
(word-play "but" :amp .2)
(word-play "necessary" :amp .2)
(bbuffer-load "/home/sendai/clips/obsession.wav")
(put-phrase "obsessed" "obsession.wav" 1.8 .4)
(put-phrase "mind" "obsession.wav" .4 2.8)
(put-phrase "filter" "obsession.wav" 3.5 4)
(bbuffer-load "/home/sendai/clips/go.wav")
(bbplay "go.wav" :amp .2)
(put-phrase "cosmos" "go.wav" 0 5)
(put-phrase "simple" "go.wav" 6.45 3.95)
(put-phrase "endless" "go.wav" 11 3.6)
(word-play "cosmos" :amp .2 :downsamp 8 :beat-length 4)
(word-play "simple" :amp .2 :downsamp 6 :beat-length 4)
(word-play "endless" :amp .2 :downsamp 8 :beat-length 4)
(word-play "mind" :amp .5 :downsamp 6)
(word-play "filter" :amp .5 :downsamp 6)
(aat (tempo-sync #[4 b]) #'f it 0 -12 20)
(aat (tempo-sync #[4 b]) #'f it 1 0 100)
(aat (tempo-sync #[4 b]) #'f it 2 12 64)
(aat (tempo-sync #[4 b]) #'f it 2 24 64)
(fp 2 1)
(fp 0 37)
(fg 1f0)
(defparameter *golang*
(new cycle
:of '("cosmos" "simple" "endless")
:repeat 1))
(defparameter *art*
(new cycle
:of '("art" "but" "necessary")
:repeat 1))
(fg .5)
(defparameter *c0* 0)
(defun f ())
(let* ((d (pval *c0*))
(s (ov-scale :C3 :phrygian))
(n (nths '(4 2 1 3 2) s))
(c (nths '(0 5 6 7) s))
(p (new weighting
:of
`((,c :weight 1)
(,n :weight ,d)
((0) :weight .25 :max 1))))
(q (make-weighting
(list 1/16 1/8 (make-cycle 1/32 2)))))
(defun f (time chan offset pan)
(unless (= chan 0)
(let ((r (rhythm (next q) 20))
(note (pickl (next p))))
(when (not (= note 0))
(and (odds .1) (incf *c0* .01))
(when (= chan 0)
(unless (node-alive 38)
(when (odds .1) (word-play (next *golang*) :id 38 :amp .4 :pan (pick .2 .5 .8))))
(if (member note n)
(viseq:push-cvideo
:pi "/home/sendai/clips/pi.mp4"
: pos 23
)
(viseq:push-cvideo
:pi "/home/sendai/clips/pi.mp4"
:pos 22
:rotation (between 10f0 40f0)
:xpos 50
:ypos 50
))
(at (+ time #[1 b]) #'viseq:delete-cvideo :pi))
(when (= chan 1)
(if (member note n)
(viseq:push-cvideo
:pi2 "/home/sendai/clips/pi-rest.mp4"
:pos 40
:repeat (pick 2 4)
:is-negative t)
(viseq:push-cvideo
:pi2 "/home/sendai/clips/pi-rest.mp4"
:pos (between 10 40)
))
(at (+ time #[2 b]) #'viseq:delete-cvideo :pi2))
(when (and (odds .1) (= chan 2))
(unless (node-alive 38)
(when (word-play (pick "art" "necessary" "kill" "sound" "free")
:downsamp (pick 4 8)
:id 38 :amp .4 :pan (pick .2 .5 .8))
(viseq:push-ctext :obs (pick "car" "la") (between 20 50) (between 20 50))
(at (+ time #[3 b]) #'viseq:delete-ctext :obs))))
(p
time
(cm:transpose note offset)
(rcosr 43 3 4)
r
chan
:pan pan))
(aat (+ time #[r b]) #'f it chan offset pan)))))
| |
ac049687b14876e48845e152366f29fd72d082026ef1fa65349c850e7391578d | kronkltd/jiksnu | sentry.clj | (ns jiksnu.sentry
(:require [ciste.config :refer [config config* describe-config]]
[taoensso.timbre :as timbre])
(:import com.getsentry.raven.Raven
com.getsentry.raven.RavenFactory
com.getsentry.raven.event.Event$Level
com.getsentry.raven.event.EventBuilder
com.getsentry.raven.event.interfaces.ExceptionInterface))
(describe-config
[:jiksnu :sentry :dsn]
String
"Private DSN from sentry server")
(describe-config
[:jiksnu :sentry :key]
String
"Sentry access key")
(describe-config
[:jiksnu :sentry :secret]
String
"Sentry secret")
(describe-config
[:jiksnu :sentry :scheme]
String
"Sentry server scheme"
:default "http")
(describe-config
[:jiksnu :sentry :host]
String
"Hostname of the Sentry server"
:default "localhost")
(describe-config
[:jiksnu :sentry :port]
Integer
"Port of the Sentry server"
:default 80)
(describe-config
[:jiksnu :sentry :project]
Integer
"Sentry project number")
(defn get-dsn
"Returns a DSN for connecting to a Sentry server from configuration parts"
[]
(or
;; Use DSN if provided
(config* :jiksnu :sentry :dsn)
;; Otherwise, build from parts
(let [key (config :jiksnu :sentry :key)
secret (config :jiksnu :sentry :secret)
host (config :jiksnu :sentry :host)
port (config :jiksnu :sentry :port)
project (config :jiksnu :sentry :project)
scheme (config* :jiksnu :sentry :scheme)]
(format "%s:%s@%s:%s/%s" scheme key secret host port project))))
(defn raven-formatter
"Sends error logging to a Sentry server"
[{:keys [?err_] :as data}]
(when-let [^Exception e (force ?err_)]
(try
(let [^Raven raven (RavenFactory/ravenInstance ^String (get-dsn))
^EventBuilder builder (.. (EventBuilder.)
(withMessage (.getMessage e))
(withLevel Event$Level/ERROR)
(withLogger ^String (:?ns-str data))
(withSentryInterface (ExceptionInterface. e)))]
(.runBuilderHelpers raven builder)
(.sendEvent raven (.build builder)))
(catch Exception ex
(timbre/warn ex "Could not send error to Sentry server")))))
(def raven-appender
{:enabled? true
:async? false
:min-level nil
:rate-limit nil
:output-fn :inherit
:fn raven-formatter})
| null | https://raw.githubusercontent.com/kronkltd/jiksnu/8c91e9b1fddcc0224b028e573f7c3ca2f227e516/src/jiksnu/sentry.clj | clojure | Use DSN if provided
Otherwise, build from parts | (ns jiksnu.sentry
(:require [ciste.config :refer [config config* describe-config]]
[taoensso.timbre :as timbre])
(:import com.getsentry.raven.Raven
com.getsentry.raven.RavenFactory
com.getsentry.raven.event.Event$Level
com.getsentry.raven.event.EventBuilder
com.getsentry.raven.event.interfaces.ExceptionInterface))
(describe-config
[:jiksnu :sentry :dsn]
String
"Private DSN from sentry server")
(describe-config
[:jiksnu :sentry :key]
String
"Sentry access key")
(describe-config
[:jiksnu :sentry :secret]
String
"Sentry secret")
(describe-config
[:jiksnu :sentry :scheme]
String
"Sentry server scheme"
:default "http")
(describe-config
[:jiksnu :sentry :host]
String
"Hostname of the Sentry server"
:default "localhost")
(describe-config
[:jiksnu :sentry :port]
Integer
"Port of the Sentry server"
:default 80)
(describe-config
[:jiksnu :sentry :project]
Integer
"Sentry project number")
(defn get-dsn
"Returns a DSN for connecting to a Sentry server from configuration parts"
[]
(or
(config* :jiksnu :sentry :dsn)
(let [key (config :jiksnu :sentry :key)
secret (config :jiksnu :sentry :secret)
host (config :jiksnu :sentry :host)
port (config :jiksnu :sentry :port)
project (config :jiksnu :sentry :project)
scheme (config* :jiksnu :sentry :scheme)]
(format "%s:%s@%s:%s/%s" scheme key secret host port project))))
(defn raven-formatter
"Sends error logging to a Sentry server"
[{:keys [?err_] :as data}]
(when-let [^Exception e (force ?err_)]
(try
(let [^Raven raven (RavenFactory/ravenInstance ^String (get-dsn))
^EventBuilder builder (.. (EventBuilder.)
(withMessage (.getMessage e))
(withLevel Event$Level/ERROR)
(withLogger ^String (:?ns-str data))
(withSentryInterface (ExceptionInterface. e)))]
(.runBuilderHelpers raven builder)
(.sendEvent raven (.build builder)))
(catch Exception ex
(timbre/warn ex "Could not send error to Sentry server")))))
(def raven-appender
{:enabled? true
:async? false
:min-level nil
:rate-limit nil
:output-fn :inherit
:fn raven-formatter})
|
3784e3d182de3dac7c069b94fced346e2c36ca3b1c314cb669a4bee2f0ad31b4 | input-output-hk/cardano-wallet-legacy | Hspec.hs | | Wrappers around hspec functionality that uses ' Buildable ' instead of
' Show ' to better fit in with the rest of the Cardano codebase
--
Intended as a drop - in replacement for " Test . HSpec " .
module Util.Buildable.Hspec (
* Wrappers around Test . HSpec . Expectations
shouldSatisfy
, shouldBe
, shouldNotBe
, shouldReturn
, shouldMatchList
-- * Working with Validated
, valid
, shouldBeValidated
, shouldReturnValidated
-- * Re-exports
, H.Expectation
, H.Spec
, H.around
, H.describe
, H.hspec
, H.it
, H.beforeAll
, H.parallel
, H.runIO
) where
import qualified Test.Hspec as H
import Universum
import Data.Validated
import Util.Buildable
------------------------------------------------------------------------------
Wrappers around Test . HSpec . Expectations
------------------------------------------------------------------------------
Wrappers around Test.HSpec.Expectations
-------------------------------------------------------------------------------}
infix 1 `shouldSatisfy`, `shouldBe`, `shouldReturn`, `shouldMatchList`
shouldSatisfy :: (HasCallStack, Buildable a)
=> a -> (a -> Bool) -> H.Expectation
shouldSatisfy a f = H.shouldSatisfy (STB a) (f . unSTB)
shouldBe :: (HasCallStack, Buildable a, Eq a)
=> a -> a -> H.Expectation
shouldBe a a' = H.shouldBe (STB a) (STB a')
shouldNotBe :: (HasCallStack, Buildable a, Eq a)
=> a -> a -> H.Expectation
shouldNotBe a a' = H.shouldNotBe (STB a) (STB a')
shouldReturn :: (HasCallStack, Buildable a, Eq a)
=> IO a -> a -> H.Expectation
shouldReturn act a = H.shouldReturn (STB <$> act) (STB a)
shouldMatchList :: (HasCallStack, Buildable a, Eq a)
=> [a] -> [a] -> H.Expectation
shouldMatchList a b = H.shouldMatchList (map STB a) (map STB b)
{-------------------------------------------------------------------------------
Wrappers around Validated
-------------------------------------------------------------------------------}
valid :: (HasCallStack, Buildable e, Buildable a)
=> String -> Validated e a -> H.Spec
valid s = H.it s . shouldBeValidated
shouldBeValidated :: (HasCallStack, Buildable e, Buildable a)
=> Validated e a -> H.Expectation
shouldBeValidated ma = shouldSatisfy ma isValidated
shouldReturnValidated :: (HasCallStack, Buildable a, Buildable e)
=> IO (Validated e a) -> IO ()
shouldReturnValidated act = shouldBeValidated =<< act
| null | https://raw.githubusercontent.com/input-output-hk/cardano-wallet-legacy/143e6d0dac0b28b3274600c6c49ec87e42ec9f37/test/unit/Util/Buildable/Hspec.hs | haskell |
* Working with Validated
* Re-exports
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
------------------------------------------------------------------------------
Wrappers around Validated
------------------------------------------------------------------------------ | | Wrappers around hspec functionality that uses ' Buildable ' instead of
' Show ' to better fit in with the rest of the Cardano codebase
Intended as a drop - in replacement for " Test . HSpec " .
module Util.Buildable.Hspec (
* Wrappers around Test . HSpec . Expectations
shouldSatisfy
, shouldBe
, shouldNotBe
, shouldReturn
, shouldMatchList
, valid
, shouldBeValidated
, shouldReturnValidated
, H.Expectation
, H.Spec
, H.around
, H.describe
, H.hspec
, H.it
, H.beforeAll
, H.parallel
, H.runIO
) where
import qualified Test.Hspec as H
import Universum
import Data.Validated
import Util.Buildable
Wrappers around Test . HSpec . Expectations
Wrappers around Test.HSpec.Expectations
infix 1 `shouldSatisfy`, `shouldBe`, `shouldReturn`, `shouldMatchList`
shouldSatisfy :: (HasCallStack, Buildable a)
=> a -> (a -> Bool) -> H.Expectation
shouldSatisfy a f = H.shouldSatisfy (STB a) (f . unSTB)
shouldBe :: (HasCallStack, Buildable a, Eq a)
=> a -> a -> H.Expectation
shouldBe a a' = H.shouldBe (STB a) (STB a')
shouldNotBe :: (HasCallStack, Buildable a, Eq a)
=> a -> a -> H.Expectation
shouldNotBe a a' = H.shouldNotBe (STB a) (STB a')
shouldReturn :: (HasCallStack, Buildable a, Eq a)
=> IO a -> a -> H.Expectation
shouldReturn act a = H.shouldReturn (STB <$> act) (STB a)
shouldMatchList :: (HasCallStack, Buildable a, Eq a)
=> [a] -> [a] -> H.Expectation
shouldMatchList a b = H.shouldMatchList (map STB a) (map STB b)
valid :: (HasCallStack, Buildable e, Buildable a)
=> String -> Validated e a -> H.Spec
valid s = H.it s . shouldBeValidated
shouldBeValidated :: (HasCallStack, Buildable e, Buildable a)
=> Validated e a -> H.Expectation
shouldBeValidated ma = shouldSatisfy ma isValidated
shouldReturnValidated :: (HasCallStack, Buildable a, Buildable e)
=> IO (Validated e a) -> IO ()
shouldReturnValidated act = shouldBeValidated =<< act
|
8d357bddd4270e41055a35b68ed793c7a9325adcd9ad7ed53f734ec5f51a7e9a | e-bigmoon/haskell-blog | Connection_Manager2.hs | #!/usr/bin/env stack
-- stack script --resolver lts-17.3
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.ByteString.Lazy.Char8 as L8
import Network.HTTP.Client
import Network.HTTP.Client.TLS
import Network.HTTP.Simple
main :: IO ()
main = do
manager <- newManager $ managerSetProxy noProxy tlsManagerSettings
setGlobalManager manager
let request = ""
response <- httpLBS request
putStrLn $ "The status code was: " ++
show (getResponseStatusCode response)
print $ getResponseHeader "Content-Type" response
L8.putStrLn $ getResponseBody response | null | https://raw.githubusercontent.com/e-bigmoon/haskell-blog/5c9e7c25f31ea6856c5d333e8e991dbceab21c56/sample-code/yesod/appendix/ap4/Connection_Manager2.hs | haskell | stack script --resolver lts-17.3
# LANGUAGE OverloadedStrings # | #!/usr/bin/env stack
import qualified Data.ByteString.Lazy.Char8 as L8
import Network.HTTP.Client
import Network.HTTP.Client.TLS
import Network.HTTP.Simple
main :: IO ()
main = do
manager <- newManager $ managerSetProxy noProxy tlsManagerSettings
setGlobalManager manager
let request = ""
response <- httpLBS request
putStrLn $ "The status code was: " ++
show (getResponseStatusCode response)
print $ getResponseHeader "Content-Type" response
L8.putStrLn $ getResponseBody response |
30d417025fa7adc57deef7a6c8f27d108d8ca68ca7cd1f2ee97fb66cd1d645c4 | dainiusjocas/lucene-grep | parser.clj | (ns lmgrep.cli.parser
(:require [clojure.string :as str]
[jsonista.core :as json]))
(def format-options #{:edn :json :string})
(def tokenizers #{:keyword :letter :standard :unicode-whitespace :whitespace})
(def stemmers #{:kp
:portuguese
:lithuanian
:german2
:porter
:danish
:norwegian
:catalan
:irish
:romanian
:basque
:russian
:dutch
:estonian
:finnish
:turkish
:italian
:english
:lovins
:swedish
:german
:spanish
:french
:arabic
:hungarian
:armenian})
(defn options-to-str [options]
(print-str (mapv name (sort options))))
(def query-parsers #{:classic :complex-phrase :surround :simple :standard})
(def presearchers #{:no-filtering :term-filtered :multipass-term-filtered})
(defn read-json [json-string]
(json/read-value json-string json/keyword-keys-object-mapper))
(def cli-options
[["-q" "--query QUERY"
"Lucene query string(s). If specified then all the positional arguments are interpreted as files."
:multi true
:update-fn conj]
[nil "--query-parser QUERY_PARSER" (str "Which query parser to use, one of: " (options-to-str query-parsers))
:parse-fn #(keyword (str/lower-case %))
:validate [#(contains? query-parsers %) (str "Query parser must be one of: " (options-to-str query-parsers))]]
[nil "--queries-file QUERIES_FILE"
"A file path to the Lucene query strings with their config. If specified then all the positional arguments are interpreted as files."]
[nil "--queries-index-dir QUERIES_INDEX_DIR"
"A directory where Lucene Monitor queries are stored."]
[nil "--tokenizer TOKENIZER" (str "Tokenizer to use, one of: " (options-to-str tokenizers))
:parse-fn #(keyword (str/lower-case %))
:validate [#(contains? tokenizers %) (str "Tokenizer must be one of: " (options-to-str tokenizers))]]
[nil "--case-sensitive? CASE_SENSITIVE" "If text should be case sensitive"
:parse-fn #(Boolean/parseBoolean %)]
[nil "--ascii-fold? ASCII_FOLDED" "If text should be ascii folded"
:parse-fn #(Boolean/parseBoolean %)]
[nil "--stem? STEMMED" "If text should be stemmed"
:parse-fn #(Boolean/parseBoolean %)]
[nil "--stemmer STEMMER" (str "Which stemmer to use for token stemming, one of: " (options-to-str stemmers))
:parse-fn #(keyword (str/lower-case %))
:validate [#(contains? stemmers %) (str "Stemmer must be one of: " (options-to-str stemmers))]]
[nil "--presearcher PRESEARCHER" (str "Which Lucene Monitor Presearcher to use, one of: " (options-to-str presearchers))
:parse-fn #(keyword (str/lower-case %))
:validate [#(contains? presearchers %) (str "Query parser must be one of: " (options-to-str presearchers))]
:default "no-filtering"]
[nil "--with-score" "If the matching score should be computed"]
[nil "--format FORMAT" (str "How the output should be formatted, one of: " (options-to-str format-options))
:parse-fn #(keyword (str/lower-case %))
:validate [#(contains? format-options %) (str "Format must be one of: " (options-to-str format-options))]]
[nil "--template TEMPLATE" "The template for the output string, e.g.: file={{file}} line-number={{line-number}} line={{line}}"]
[nil "--pre-tags PRE_TAGS" "A string that the highlighted text is wrapped in, use in conjunction with --post-tags"]
[nil "--post-tags POST_TAGS" "A string that the highlighted text is wrapped in, use in conjunction with --pre-tags"]
[nil "--excludes EXCLUDES" "A GLOB that filters out files that were matched with a GLOB"]
[nil "--skip-binary-files" "If a file that is detected to be binary should be skipped. Available for Linux and MacOS only."
:default false]
[nil "--[no-]hidden" "Search in hidden files. Default: true."
:default true]
[nil "--max-depth N" "In case of a recursive GLOB, how deep to search for input files."
:parse-fn #(Integer/parseInt %)]
[nil "--with-empty-lines" "When provided on the input that does not match write an empty line to STDOUT."
:default false]
[nil "--with-scored-highlights" "ALPHA: Instructs to highlight with scoring."
:default false]
[nil "--[no-]split" "If a file (or STDIN) should be split by newline."
:default true]
[nil "--hyperlink" "If a file should be printed as hyperlinks."
:default false]
[nil "--with-details" "For JSON and EDN output adds raw highlights list."
:default false]
[nil "--word-delimiter-graph-filter WDGF" "WordDelimiterGraphFilter configurationFlags as per -common/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilter.html"
:parse-fn #(Integer/parseInt %)]
[nil "--show-analysis-components" "Just print-out the available analysis components in JSON."
:default false]
[nil "--only-analyze" "When provided output will be analyzed text."
:default false]
[nil "--explain" "Modifies --only-analyze. Output is detailed token info, similar to Elasticsearch Analyze API."]
[nil "--graph" "Modifies --only-analyze. Output is a string that can be fed to the `dot` program."]
[nil "--analysis ANALYSIS" "The analysis chain configuration"
:parse-fn read-json
:default {}]
[nil "--query-parser-conf CONF" "The configuration for the query parser."
:parse-fn read-json]
[nil "--concurrency CONCURRENCY" "How many concurrent threads to use for processing."
:parse-fn #(Integer/parseInt %)
:validate [(fn [value] (< 0 value)) "Must be > 0"]
:default 8]
[nil "--queue-size SIZE" "Number of lines read before being processed"
:parse-fn #(Integer/parseInt %)
:validate [(fn [value] (< 0 value)) "Must be > 0"]
:default 1024]
[nil "--reader-buffer-size BUFFER_SIZE" "Buffer size of the BufferedReader in bytes."
:parse-fn #(Integer/parseInt %)]
[nil "--writer-buffer-size BUFFER_SIZE" "Buffer size of the BufferedWriter in bytes."
:parse-fn #(Integer/parseInt %)]
[nil "--[no-]preserve-order" "If the input order should be preserved."
:default true]
[nil "--config-dir DIR" "A base directory from which to load text analysis resources, e.g. synonym files. Default: current dir."]
[nil "--analyzers-file FILE"
"A file that contains definitions of text analyzers. Works in combinations with --config-dir flag."
:multi true
:update-fn conj]
[nil "--query-update-buffer-size NUMBER" "Number of queries to be buffered in memory before being committed to the queryindex. Default 100000."]
[nil "--streamed" "Listens on STDIN for json with both query and a piece of text to be analyzed" :default false]
["-h" "--help"]])
| null | https://raw.githubusercontent.com/dainiusjocas/lucene-grep/26c5a8043265678877ccb1151bbe89f760e74abe/src/lmgrep/cli/parser.clj | clojure | (ns lmgrep.cli.parser
(:require [clojure.string :as str]
[jsonista.core :as json]))
(def format-options #{:edn :json :string})
(def tokenizers #{:keyword :letter :standard :unicode-whitespace :whitespace})
(def stemmers #{:kp
:portuguese
:lithuanian
:german2
:porter
:danish
:norwegian
:catalan
:irish
:romanian
:basque
:russian
:dutch
:estonian
:finnish
:turkish
:italian
:english
:lovins
:swedish
:german
:spanish
:french
:arabic
:hungarian
:armenian})
(defn options-to-str [options]
(print-str (mapv name (sort options))))
(def query-parsers #{:classic :complex-phrase :surround :simple :standard})
(def presearchers #{:no-filtering :term-filtered :multipass-term-filtered})
(defn read-json [json-string]
(json/read-value json-string json/keyword-keys-object-mapper))
(def cli-options
[["-q" "--query QUERY"
"Lucene query string(s). If specified then all the positional arguments are interpreted as files."
:multi true
:update-fn conj]
[nil "--query-parser QUERY_PARSER" (str "Which query parser to use, one of: " (options-to-str query-parsers))
:parse-fn #(keyword (str/lower-case %))
:validate [#(contains? query-parsers %) (str "Query parser must be one of: " (options-to-str query-parsers))]]
[nil "--queries-file QUERIES_FILE"
"A file path to the Lucene query strings with their config. If specified then all the positional arguments are interpreted as files."]
[nil "--queries-index-dir QUERIES_INDEX_DIR"
"A directory where Lucene Monitor queries are stored."]
[nil "--tokenizer TOKENIZER" (str "Tokenizer to use, one of: " (options-to-str tokenizers))
:parse-fn #(keyword (str/lower-case %))
:validate [#(contains? tokenizers %) (str "Tokenizer must be one of: " (options-to-str tokenizers))]]
[nil "--case-sensitive? CASE_SENSITIVE" "If text should be case sensitive"
:parse-fn #(Boolean/parseBoolean %)]
[nil "--ascii-fold? ASCII_FOLDED" "If text should be ascii folded"
:parse-fn #(Boolean/parseBoolean %)]
[nil "--stem? STEMMED" "If text should be stemmed"
:parse-fn #(Boolean/parseBoolean %)]
[nil "--stemmer STEMMER" (str "Which stemmer to use for token stemming, one of: " (options-to-str stemmers))
:parse-fn #(keyword (str/lower-case %))
:validate [#(contains? stemmers %) (str "Stemmer must be one of: " (options-to-str stemmers))]]
[nil "--presearcher PRESEARCHER" (str "Which Lucene Monitor Presearcher to use, one of: " (options-to-str presearchers))
:parse-fn #(keyword (str/lower-case %))
:validate [#(contains? presearchers %) (str "Query parser must be one of: " (options-to-str presearchers))]
:default "no-filtering"]
[nil "--with-score" "If the matching score should be computed"]
[nil "--format FORMAT" (str "How the output should be formatted, one of: " (options-to-str format-options))
:parse-fn #(keyword (str/lower-case %))
:validate [#(contains? format-options %) (str "Format must be one of: " (options-to-str format-options))]]
[nil "--template TEMPLATE" "The template for the output string, e.g.: file={{file}} line-number={{line-number}} line={{line}}"]
[nil "--pre-tags PRE_TAGS" "A string that the highlighted text is wrapped in, use in conjunction with --post-tags"]
[nil "--post-tags POST_TAGS" "A string that the highlighted text is wrapped in, use in conjunction with --pre-tags"]
[nil "--excludes EXCLUDES" "A GLOB that filters out files that were matched with a GLOB"]
[nil "--skip-binary-files" "If a file that is detected to be binary should be skipped. Available for Linux and MacOS only."
:default false]
[nil "--[no-]hidden" "Search in hidden files. Default: true."
:default true]
[nil "--max-depth N" "In case of a recursive GLOB, how deep to search for input files."
:parse-fn #(Integer/parseInt %)]
[nil "--with-empty-lines" "When provided on the input that does not match write an empty line to STDOUT."
:default false]
[nil "--with-scored-highlights" "ALPHA: Instructs to highlight with scoring."
:default false]
[nil "--[no-]split" "If a file (or STDIN) should be split by newline."
:default true]
[nil "--hyperlink" "If a file should be printed as hyperlinks."
:default false]
[nil "--with-details" "For JSON and EDN output adds raw highlights list."
:default false]
[nil "--word-delimiter-graph-filter WDGF" "WordDelimiterGraphFilter configurationFlags as per -common/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilter.html"
:parse-fn #(Integer/parseInt %)]
[nil "--show-analysis-components" "Just print-out the available analysis components in JSON."
:default false]
[nil "--only-analyze" "When provided output will be analyzed text."
:default false]
[nil "--explain" "Modifies --only-analyze. Output is detailed token info, similar to Elasticsearch Analyze API."]
[nil "--graph" "Modifies --only-analyze. Output is a string that can be fed to the `dot` program."]
[nil "--analysis ANALYSIS" "The analysis chain configuration"
:parse-fn read-json
:default {}]
[nil "--query-parser-conf CONF" "The configuration for the query parser."
:parse-fn read-json]
[nil "--concurrency CONCURRENCY" "How many concurrent threads to use for processing."
:parse-fn #(Integer/parseInt %)
:validate [(fn [value] (< 0 value)) "Must be > 0"]
:default 8]
[nil "--queue-size SIZE" "Number of lines read before being processed"
:parse-fn #(Integer/parseInt %)
:validate [(fn [value] (< 0 value)) "Must be > 0"]
:default 1024]
[nil "--reader-buffer-size BUFFER_SIZE" "Buffer size of the BufferedReader in bytes."
:parse-fn #(Integer/parseInt %)]
[nil "--writer-buffer-size BUFFER_SIZE" "Buffer size of the BufferedWriter in bytes."
:parse-fn #(Integer/parseInt %)]
[nil "--[no-]preserve-order" "If the input order should be preserved."
:default true]
[nil "--config-dir DIR" "A base directory from which to load text analysis resources, e.g. synonym files. Default: current dir."]
[nil "--analyzers-file FILE"
"A file that contains definitions of text analyzers. Works in combinations with --config-dir flag."
:multi true
:update-fn conj]
[nil "--query-update-buffer-size NUMBER" "Number of queries to be buffered in memory before being committed to the queryindex. Default 100000."]
[nil "--streamed" "Listens on STDIN for json with both query and a piece of text to be analyzed" :default false]
["-h" "--help"]])
| |
b43737a6eee8d71968a70e273061ab6dd486179cdb66356730e3f12edcb6bbc8 | autolwe/autolwe | nondet.mli | * Nondeterministic computations ( aka lazy lists )
(* ** Imports *)
open Util
* * Nondeterminism -----------------------------------------------------------------------
* ----------------------------------------------------------------------- *)
type 'a stream
type 'a nondet
val ret : 'a -> 'a nondet
val mempty : 'a nondet
(** Combine results returned by [a] with results returned by [b].
[mplus] preserves order, i.e., results from [a] occur before
results from [b]. *)
val mplus : 'a nondet -> 'a nondet -> 'a nondet
val fmap : ('a -> 'b) -> 'a nondet -> 'b nondet
val bind : 'a nondet -> ('a -> 'b nondet) -> 'b nondet
val guard : bool -> unit nondet
* Execute and get first [ n ] results as list , use [ n=-1 ] to get all values .
val run : int -> 'a nondet -> 'a list
(* ** Useful functions
* ----------------------------------------------------------------------- *)
* Apply function [ f ] to the first n values , use [ n=-1 ] to apply [ f ] to all values .
val iter : int -> 'a nondet -> ('a -> unit) -> unit
val sequence : ('a nondet) list -> ('a list) nondet
val mapM : ('a -> 'b nondet) -> 'a list -> ('b list) nondet
val foreachM : 'a list -> ('a -> 'b nondet) -> ('b list) nondet
val mconcat : 'a list -> 'a nondet
val msum : ('a nondet) list -> 'a nondet
val (>>=) : 'a nondet -> ('a -> 'b nondet) -> 'b nondet
* Return all subsets $ S$ of $ m$ such that $ |S| \leq k$.
val pick_set : int -> 'a nondet -> ('a list) nondet
* Return all subsets $ S$ of $ m$ such that $ |S| = k$.
val pick_set_exact : int -> 'a nondet -> ('a list) nondet
* Return the cartesian product of $ m1 $ and $ m2$.
val cart : 'a nondet -> 'b nondet -> ('a * 'b) nondet
* Return the cartesian product of $ m$.
val prod : 'a nondet -> ('a * 'a) nondet
(** Return the $n$-fold cartesian product of $ms$. *)
val ncart : 'a nondet list -> ('a list) nondet
* Return the $ n$-fold cartesian product of $ m$.
val nprod : 'a nondet -> int -> ('a list) nondet
val insertions : 'a list -> 'a -> 'a list -> 'a list nondet
val permutations : 'a list -> 'a list nondet
val is_nil : 'a nondet -> bool
val pull : 'a nondet -> ((string lazy_t) option, ('a * 'a nondet)) either
val first : 'a nondet -> 'a
val mfail : string lazy_t -> 'a nondet
| null | https://raw.githubusercontent.com/autolwe/autolwe/3452c3dae06fc8e9815d94133fdeb8f3b8315f32/src/Util/nondet.mli | ocaml | ** Imports
* Combine results returned by [a] with results returned by [b].
[mplus] preserves order, i.e., results from [a] occur before
results from [b].
** Useful functions
* -----------------------------------------------------------------------
* Return the $n$-fold cartesian product of $ms$. | * Nondeterministic computations ( aka lazy lists )
open Util
* * Nondeterminism -----------------------------------------------------------------------
* ----------------------------------------------------------------------- *)
type 'a stream
type 'a nondet
val ret : 'a -> 'a nondet
val mempty : 'a nondet
val mplus : 'a nondet -> 'a nondet -> 'a nondet
val fmap : ('a -> 'b) -> 'a nondet -> 'b nondet
val bind : 'a nondet -> ('a -> 'b nondet) -> 'b nondet
val guard : bool -> unit nondet
* Execute and get first [ n ] results as list , use [ n=-1 ] to get all values .
val run : int -> 'a nondet -> 'a list
* Apply function [ f ] to the first n values , use [ n=-1 ] to apply [ f ] to all values .
val iter : int -> 'a nondet -> ('a -> unit) -> unit
val sequence : ('a nondet) list -> ('a list) nondet
val mapM : ('a -> 'b nondet) -> 'a list -> ('b list) nondet
val foreachM : 'a list -> ('a -> 'b nondet) -> ('b list) nondet
val mconcat : 'a list -> 'a nondet
val msum : ('a nondet) list -> 'a nondet
val (>>=) : 'a nondet -> ('a -> 'b nondet) -> 'b nondet
* Return all subsets $ S$ of $ m$ such that $ |S| \leq k$.
val pick_set : int -> 'a nondet -> ('a list) nondet
* Return all subsets $ S$ of $ m$ such that $ |S| = k$.
val pick_set_exact : int -> 'a nondet -> ('a list) nondet
* Return the cartesian product of $ m1 $ and $ m2$.
val cart : 'a nondet -> 'b nondet -> ('a * 'b) nondet
* Return the cartesian product of $ m$.
val prod : 'a nondet -> ('a * 'a) nondet
val ncart : 'a nondet list -> ('a list) nondet
* Return the $ n$-fold cartesian product of $ m$.
val nprod : 'a nondet -> int -> ('a list) nondet
val insertions : 'a list -> 'a -> 'a list -> 'a list nondet
val permutations : 'a list -> 'a list nondet
val is_nil : 'a nondet -> bool
val pull : 'a nondet -> ((string lazy_t) option, ('a * 'a nondet)) either
val first : 'a nondet -> 'a
val mfail : string lazy_t -> 'a nondet
|
22e5788fd6e3c8f678fe5a068f3871a0936557ea232fb24618ee853198bb2447 | quil-lang/quilc | clozure.lisp | ;;;; clozure.lisp
(in-package #:quilc)
(defun disable-debugger ()
(setf ccl::*batch-flag* t))
(defun enable-debugger ()
(setf ccl::*batch-flag* nil))
(deftype interactive-interrupt ()
'ccl:interrupt-signal-condition)
| null | https://raw.githubusercontent.com/quil-lang/quilc/3f3260aaa65cdde25a4f9c0027959e37ceef9d64/app/src/impl/clozure.lisp | lisp | clozure.lisp |
(in-package #:quilc)
(defun disable-debugger ()
(setf ccl::*batch-flag* t))
(defun enable-debugger ()
(setf ccl::*batch-flag* nil))
(deftype interactive-interrupt ()
'ccl:interrupt-signal-condition)
|
aaec720baa2f6487cb54912a4c3d59973cf72e62dd8efd95f8ba5ef21c9a1d46 | alavrik/piqi | piqi_pp.ml |
Copyright 2009 , 2010 , 2011 , 2012 , 2013 , 2014 , 2015 under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015 Anton Lavrik
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module C = Piqi_common
open C
let prettyprint_ast ch ast =
Piq_gen.to_channel ch ast
let rec prettyprint_list ch ast_list =
let rec aux = function
| [] -> ()
| [x] -> prettyprint_ast ch x
| h::t ->
prettyprint_ast ch h;
output_char ch '\n';
aux t
in aux ast_list
simplify piqi ast :
let simplify_piqi_ast (ast:piq_ast) =
let tr = Piq_ast.transform_ast in
(* map typedef.x -> x *)
let rm_typedef =
tr [] (
function
| `named {Piq_ast.Named.name = "typedef"; Piq_ast.Named.value = v} -> [v]
| x -> [x]
)
(* del .../mode.required *)
map ... / mode x - > x
and tr_field_mode path =
tr path (
function
| `named {Piq_ast.Named.name = "mode"; Piq_ast.Named.value = `name "required"} -> []
| `named {Piq_ast.Named.name = "mode"; Piq_ast.Named.value = (`name _) as x} -> [x]
| x -> [x]
)
(* map extend/.piqi-any x -> x *)
(* TODO: this method of specifying extensions will be eventually deprecated *)
and tr_extend_piq_any =
tr ["extend"] (
function
| `named {Piq_ast.Named.name = "piqi-any"; Piq_ast.Named.value = v} -> [v]
| x -> [x]
)
(* map extend/.what x -> x *)
and tr_extend_what =
tr ["extend"] (
function
| `named {Piq_ast.Named.name = "what"; Piq_ast.Named.value = v} -> [v]
| x -> [x]
)
(* map ../record.x -> x *)
(* map ../name.x -> x *)
and rm_param_extra path =
tr path (
function
| `named {Piq_ast.Named.name = "record"; Piq_ast.Named.value = v} -> [v]
| `named {Piq_ast.Named.name = "name"; Piq_ast.Named.value = v} -> [v]
| x -> [x]
)
(* strip :<type> from a field's default value *)
and tr_field_default_value path =
tr path (
function
| `typed {Piq_ast.Typed.value = v} -> [v]
| x -> [x]
)
in
let (|>) a f = f a in
let simplify_function_param param ast =
ast
|> rm_param_extra ["function"; param]
|> tr_field_mode ["function"; param; "field"]
|> tr_field_default_value ["function"; param; "field"; "default"]
in
ast
|> rm_typedef
|> tr_field_mode ["record"; "field"]
|> tr_field_default_value ["record"; "field"; "default"]
|> tr_extend_piq_any
|> tr_extend_what
(* functions *)
|> simplify_function_param "input"
|> simplify_function_param "output"
|> simplify_function_param "error"
let compare_piqi_items a b =
let name_of = function
| `name x -> x
| `named x -> x.Piq_ast.Named.name
| `typename x -> x
| `typed x -> x.Piq_ast.Typed.typename
| _ -> assert false
in
let rank x =
match name_of x with
| "module" -> 0
| "protobuf-package" -> 1
| "include" -> 2
| "import" -> 3
| "typedef" -> 4
| "function" -> 5
| "extend" -> 6
| _ -> 100
in
rank a - rank b
let sort_piqi_items (ast:piq_ast) =
match ast with
| `list l ->
let l = List.stable_sort compare_piqi_items l in
`list l
| _ -> assert false
let prettify_piqi_ast ast =
let ast = sort_piqi_items ast in
simplify_piqi_ast ast
let prettyprint_piqi_ast ch ast =
let ast = prettify_piqi_ast ast in
match ast with
| `list l -> prettyprint_list ch l
| _ -> assert false
let prettyprint_piqi ch (piqi:T.piqi) =
let ast = Piqi.piqi_to_ast piqi in
prettyprint_piqi_ast ch ast
| null | https://raw.githubusercontent.com/alavrik/piqi/bcea4d44997966198dc295df0609591fa787b1d2/piqilib/piqi_pp.ml | ocaml | map typedef.x -> x
del .../mode.required
map extend/.piqi-any x -> x
TODO: this method of specifying extensions will be eventually deprecated
map extend/.what x -> x
map ../record.x -> x
map ../name.x -> x
strip :<type> from a field's default value
functions |
Copyright 2009 , 2010 , 2011 , 2012 , 2013 , 2014 , 2015 under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015 Anton Lavrik
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module C = Piqi_common
open C
let prettyprint_ast ch ast =
Piq_gen.to_channel ch ast
let rec prettyprint_list ch ast_list =
let rec aux = function
| [] -> ()
| [x] -> prettyprint_ast ch x
| h::t ->
prettyprint_ast ch h;
output_char ch '\n';
aux t
in aux ast_list
simplify piqi ast :
let simplify_piqi_ast (ast:piq_ast) =
let tr = Piq_ast.transform_ast in
let rm_typedef =
tr [] (
function
| `named {Piq_ast.Named.name = "typedef"; Piq_ast.Named.value = v} -> [v]
| x -> [x]
)
map ... / mode x - > x
and tr_field_mode path =
tr path (
function
| `named {Piq_ast.Named.name = "mode"; Piq_ast.Named.value = `name "required"} -> []
| `named {Piq_ast.Named.name = "mode"; Piq_ast.Named.value = (`name _) as x} -> [x]
| x -> [x]
)
and tr_extend_piq_any =
tr ["extend"] (
function
| `named {Piq_ast.Named.name = "piqi-any"; Piq_ast.Named.value = v} -> [v]
| x -> [x]
)
and tr_extend_what =
tr ["extend"] (
function
| `named {Piq_ast.Named.name = "what"; Piq_ast.Named.value = v} -> [v]
| x -> [x]
)
and rm_param_extra path =
tr path (
function
| `named {Piq_ast.Named.name = "record"; Piq_ast.Named.value = v} -> [v]
| `named {Piq_ast.Named.name = "name"; Piq_ast.Named.value = v} -> [v]
| x -> [x]
)
and tr_field_default_value path =
tr path (
function
| `typed {Piq_ast.Typed.value = v} -> [v]
| x -> [x]
)
in
let (|>) a f = f a in
let simplify_function_param param ast =
ast
|> rm_param_extra ["function"; param]
|> tr_field_mode ["function"; param; "field"]
|> tr_field_default_value ["function"; param; "field"; "default"]
in
ast
|> rm_typedef
|> tr_field_mode ["record"; "field"]
|> tr_field_default_value ["record"; "field"; "default"]
|> tr_extend_piq_any
|> tr_extend_what
|> simplify_function_param "input"
|> simplify_function_param "output"
|> simplify_function_param "error"
let compare_piqi_items a b =
let name_of = function
| `name x -> x
| `named x -> x.Piq_ast.Named.name
| `typename x -> x
| `typed x -> x.Piq_ast.Typed.typename
| _ -> assert false
in
let rank x =
match name_of x with
| "module" -> 0
| "protobuf-package" -> 1
| "include" -> 2
| "import" -> 3
| "typedef" -> 4
| "function" -> 5
| "extend" -> 6
| _ -> 100
in
rank a - rank b
let sort_piqi_items (ast:piq_ast) =
match ast with
| `list l ->
let l = List.stable_sort compare_piqi_items l in
`list l
| _ -> assert false
let prettify_piqi_ast ast =
let ast = sort_piqi_items ast in
simplify_piqi_ast ast
let prettyprint_piqi_ast ch ast =
let ast = prettify_piqi_ast ast in
match ast with
| `list l -> prettyprint_list ch l
| _ -> assert false
let prettyprint_piqi ch (piqi:T.piqi) =
let ast = Piqi.piqi_to_ast piqi in
prettyprint_piqi_ast ch ast
|
b72dc30e60ddf11ad169ba36769056175fa9f0dc19cb2283f871e30da46a35df | typeclasses/dsv | NumberViews.hs | # LANGUAGE DerivingStrategies , DeriveAnyClass #
# LANGUAGE NoImplicitPrelude , ScopedTypeVariables #
{-# LANGUAGE OverloadedStrings #-}
module DSV.NumberViews
( InvalidNat (..), byteStringNatView, textNatView
, byteStringNatView_, textNatView_
, InvalidRational (..), byteStringRationalView, textRationalView
, byteStringRationalView_, textRationalView_
, InvalidDollars (..), byteStringDollarsView, textDollarsView
, byteStringDollarsView_, textDollarsView_
) where
import DSV.AttoView
import DSV.ByteString
import DSV.IO
import DSV.Numbers
import DSV.Prelude
import DSV.Text
import DSV.TextReaderView
import DSV.UTF8
import DSV.Validation
import DSV.ViewType
attoparsec
import qualified Data.Attoparsec.ByteString.Char8
data InvalidNat = InvalidNat
deriving stock (Eq, Show)
deriving anyclass Exception
byteStringNatView :: View InvalidNat ByteString Natural
byteStringNatView = attoByteStringView InvalidNat p
where
p = Data.Attoparsec.ByteString.Char8.decimal
byteStringNatView_ :: View () ByteString Natural
byteStringNatView_ = discardViewError byteStringNatView
textNatView :: View InvalidNat Text Natural
textNatView = textReaderView InvalidNat textReadDecimal
textNatView_ :: View () Text Natural
textNatView_ = discardViewError textNatView
data InvalidRational = InvalidRational
deriving stock (Eq, Show)
deriving anyclass Exception
|
Read a rational number written in decimal notation .
= = = Examples
> > > : set -XOverloadedStrings
> > > applyView byteStringRationalView " 1234 "
Success ( 1234 % 1 )
> > > applyView byteStringRationalView " 1234.567 "
Success ( 1234567 % 1000 )
> > > applyView byteStringRationalView " 12.3.4 "
Failure InvalidRational
Read a rational number written in decimal notation.
=== Examples
>>> :set -XOverloadedStrings
>>> applyView byteStringRationalView "1234"
Success (1234 % 1)
>>> applyView byteStringRationalView "1234.567"
Success (1234567 % 1000)
>>> applyView byteStringRationalView "12.3.4"
Failure InvalidRational
-}
byteStringRationalView :: View InvalidRational ByteString Rational
byteStringRationalView =
textRationalView .
overViewError (\InvalidUtf8 -> InvalidRational) utf8TextView
byteStringRationalView_ :: View () ByteString Rational
byteStringRationalView_ = discardViewError byteStringRationalView
|
Read a rational number written in decimal notation .
= = = Examples
> > > : set -XOverloadedStrings
> > > applyView textRationalView " 1234 "
Success ( 1234 % 1 )
> > > applyView textRationalView " 1234.567 "
Success ( 1234567 % 1000 )
> > > applyView textRationalView " 12.3.4 "
Failure InvalidRational
Read a rational number written in decimal notation.
=== Examples
>>> :set -XOverloadedStrings
>>> applyView textRationalView "1234"
Success (1234 % 1)
>>> applyView textRationalView "1234.567"
Success (1234567 % 1000)
>>> applyView textRationalView "12.3.4"
Failure InvalidRational
-}
textRationalView :: View InvalidRational Text Rational
textRationalView = textReaderView InvalidRational textReadRational
textRationalView_ :: View () Text Rational
textRationalView_ = discardViewError textRationalView
data InvalidDollars = InvalidDollars
deriving stock (Eq, Show)
deriving anyclass Exception
| Read a dollar amount .
= = = Examples
> > > applyView byteStringDollarsView " $ 1234.567 "
Success ( 1234567 % 1000 )
> > > applyView byteStringDollarsView " 1234.567 "
Failure InvalidDollars
=== Examples
>>> applyView byteStringDollarsView "$1234.567"
Success (1234567 % 1000)
>>> applyView byteStringDollarsView "1234.567"
Failure InvalidDollars
-}
byteStringDollarsView :: View InvalidDollars ByteString Rational
byteStringDollarsView =
textDollarsView .
overViewError (\InvalidUtf8 -> InvalidDollars) utf8TextView
byteStringDollarsView_ :: View () ByteString Rational
byteStringDollarsView_ = discardViewError byteStringDollarsView
| Read a dollar amount .
= = = Examples
> > > applyView textDollarsView " $ 1234.567 "
Success ( 1234567 % 1000 )
> > > applyView textDollarsView " 1234.567 "
Failure InvalidDollars
=== Examples
>>> applyView textDollarsView "$1234.567"
Success (1234567 % 1000)
>>> applyView textDollarsView "1234.567"
Failure InvalidDollars
-}
textDollarsView :: View InvalidDollars Text Rational
textDollarsView =
overViewError
(\InvalidRational -> InvalidDollars)
textRationalView
.
View (
maybe (Failure InvalidDollars) Success .
textStripPrefix "$"
)
textDollarsView_ :: View () Text Rational
textDollarsView_ = discardViewError textDollarsView
| null | https://raw.githubusercontent.com/typeclasses/dsv/ae4eb823e27e4c569c4f9b097441985cf865fbab/dsv/library/DSV/NumberViews.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE DerivingStrategies , DeriveAnyClass #
# LANGUAGE NoImplicitPrelude , ScopedTypeVariables #
module DSV.NumberViews
( InvalidNat (..), byteStringNatView, textNatView
, byteStringNatView_, textNatView_
, InvalidRational (..), byteStringRationalView, textRationalView
, byteStringRationalView_, textRationalView_
, InvalidDollars (..), byteStringDollarsView, textDollarsView
, byteStringDollarsView_, textDollarsView_
) where
import DSV.AttoView
import DSV.ByteString
import DSV.IO
import DSV.Numbers
import DSV.Prelude
import DSV.Text
import DSV.TextReaderView
import DSV.UTF8
import DSV.Validation
import DSV.ViewType
attoparsec
import qualified Data.Attoparsec.ByteString.Char8
data InvalidNat = InvalidNat
deriving stock (Eq, Show)
deriving anyclass Exception
byteStringNatView :: View InvalidNat ByteString Natural
byteStringNatView = attoByteStringView InvalidNat p
where
p = Data.Attoparsec.ByteString.Char8.decimal
byteStringNatView_ :: View () ByteString Natural
byteStringNatView_ = discardViewError byteStringNatView
textNatView :: View InvalidNat Text Natural
textNatView = textReaderView InvalidNat textReadDecimal
textNatView_ :: View () Text Natural
textNatView_ = discardViewError textNatView
data InvalidRational = InvalidRational
deriving stock (Eq, Show)
deriving anyclass Exception
|
Read a rational number written in decimal notation .
= = = Examples
> > > : set -XOverloadedStrings
> > > applyView byteStringRationalView " 1234 "
Success ( 1234 % 1 )
> > > applyView byteStringRationalView " 1234.567 "
Success ( 1234567 % 1000 )
> > > applyView byteStringRationalView " 12.3.4 "
Failure InvalidRational
Read a rational number written in decimal notation.
=== Examples
>>> :set -XOverloadedStrings
>>> applyView byteStringRationalView "1234"
Success (1234 % 1)
>>> applyView byteStringRationalView "1234.567"
Success (1234567 % 1000)
>>> applyView byteStringRationalView "12.3.4"
Failure InvalidRational
-}
byteStringRationalView :: View InvalidRational ByteString Rational
byteStringRationalView =
textRationalView .
overViewError (\InvalidUtf8 -> InvalidRational) utf8TextView
byteStringRationalView_ :: View () ByteString Rational
byteStringRationalView_ = discardViewError byteStringRationalView
|
Read a rational number written in decimal notation .
= = = Examples
> > > : set -XOverloadedStrings
> > > applyView textRationalView " 1234 "
Success ( 1234 % 1 )
> > > applyView textRationalView " 1234.567 "
Success ( 1234567 % 1000 )
> > > applyView textRationalView " 12.3.4 "
Failure InvalidRational
Read a rational number written in decimal notation.
=== Examples
>>> :set -XOverloadedStrings
>>> applyView textRationalView "1234"
Success (1234 % 1)
>>> applyView textRationalView "1234.567"
Success (1234567 % 1000)
>>> applyView textRationalView "12.3.4"
Failure InvalidRational
-}
textRationalView :: View InvalidRational Text Rational
textRationalView = textReaderView InvalidRational textReadRational
textRationalView_ :: View () Text Rational
textRationalView_ = discardViewError textRationalView
data InvalidDollars = InvalidDollars
deriving stock (Eq, Show)
deriving anyclass Exception
| Read a dollar amount .
= = = Examples
> > > applyView byteStringDollarsView " $ 1234.567 "
Success ( 1234567 % 1000 )
> > > applyView byteStringDollarsView " 1234.567 "
Failure InvalidDollars
=== Examples
>>> applyView byteStringDollarsView "$1234.567"
Success (1234567 % 1000)
>>> applyView byteStringDollarsView "1234.567"
Failure InvalidDollars
-}
byteStringDollarsView :: View InvalidDollars ByteString Rational
byteStringDollarsView =
textDollarsView .
overViewError (\InvalidUtf8 -> InvalidDollars) utf8TextView
byteStringDollarsView_ :: View () ByteString Rational
byteStringDollarsView_ = discardViewError byteStringDollarsView
| Read a dollar amount .
= = = Examples
> > > applyView textDollarsView " $ 1234.567 "
Success ( 1234567 % 1000 )
> > > applyView textDollarsView " 1234.567 "
Failure InvalidDollars
=== Examples
>>> applyView textDollarsView "$1234.567"
Success (1234567 % 1000)
>>> applyView textDollarsView "1234.567"
Failure InvalidDollars
-}
textDollarsView :: View InvalidDollars Text Rational
textDollarsView =
overViewError
(\InvalidRational -> InvalidDollars)
textRationalView
.
View (
maybe (Failure InvalidDollars) Success .
textStripPrefix "$"
)
textDollarsView_ :: View () Text Rational
textDollarsView_ = discardViewError textDollarsView
|
8afa0b6974f994c38f0ecf1d3f3e4c20563987a6b40988a1f8271ea4958d7d2c | disteph/cdsat | master.mli | (*********************************************************************)
Main plugin , implementing the combination of decision procedures
with concurrency , as provided by Async library .
This is a master - slaves architecture .
Each slave thread runs the code written in worker.ml , controlling
the ( purely sequential ) execution of a decision procedure , and
exchanging messages with the master thread , whose code is below .
with concurrency, as provided by Jane Street's Async library.
This is a master-slaves architecture.
Each slave thread runs the code written in worker.ml, controlling
the (purely sequential) execution of a decision procedure, and
exchanging messages with the master thread, whose code is below. *)
(*********************************************************************)
open Async
open Kernel
open Top.Messages
open Theories.Register
open Interfaces
open General.Sums
module Make(WBEH: WhiteBoard4Master) : sig
open WBEH
open WBE
val master : H.t -> DS.Assign.t -> (unsat t, sat_ans) sum Deferred.t
end
| null | https://raw.githubusercontent.com/disteph/cdsat/1b569f3eae59802148f4274186746a9ed3e667ed/src/portfolio/plugins.mld/concur.mld/master.mli | ocaml | *******************************************************************
******************************************************************* | Main plugin , implementing the combination of decision procedures
with concurrency , as provided by Async library .
This is a master - slaves architecture .
Each slave thread runs the code written in worker.ml , controlling
the ( purely sequential ) execution of a decision procedure , and
exchanging messages with the master thread , whose code is below .
with concurrency, as provided by Jane Street's Async library.
This is a master-slaves architecture.
Each slave thread runs the code written in worker.ml, controlling
the (purely sequential) execution of a decision procedure, and
exchanging messages with the master thread, whose code is below. *)
open Async
open Kernel
open Top.Messages
open Theories.Register
open Interfaces
open General.Sums
module Make(WBEH: WhiteBoard4Master) : sig
open WBEH
open WBE
val master : H.t -> DS.Assign.t -> (unsat t, sat_ans) sum Deferred.t
end
|
3872b3e71e5755de17d2829e8177f64f669828f00031f406174b1b1997385eac | awslabs/s2n-bignum | bignum_amontifier.ml |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
(* ========================================================================= *)
(* Almost-Montgomerifier computation. *)
(* ========================================================================= *)
(**** print_literal_from_elf "arm/generic/bignum_amontifier.o";;
****)
let bignum_amontifier_mc =
define_assert_from_elf "bignum_amontifier_mc" "arm/generic/bignum_amontifier.o"
[
arm_CBZ X0 ( word 792 )
arm_MOV X4 XZR
arm_LDR X9 X2 ( Shiftreg_Offset X4 3 )
arm_STR ( Shiftreg_Offset X4 3 )
arm_ADD X4 X4 ( rvalue ( word 1 ) )
arm_CMP
arm_BCC ( word 2097136 )
arm_SUBS ( rvalue ( word 1 ) )
arm_BEQ ( word 52 )
arm_MOV X5 XZR
arm_CMP X9 XZR
arm_MOV X7 XZR
arm_MOV X9 X7
arm_LDR X7 X3 ( Shiftreg_Offset X5 3 )
0x9a870129; (* arm_CSEL X9 X9 X7 Condition_EQ *)
arm_STR ( Shiftreg_Offset X5 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X11 X5 X0
arm_CBNZ X11 ( word 2097128 )
arm_SUBS X4 X4 ( rvalue ( word 1 ) )
arm_BNE ( word 2097108 )
0xdac01129; (* arm_CLZ X9 X9 *)
arm_MOV X10 XZR
arm_MOV X4 XZR
arm_TST X9 ( rvalue ( word 63 ) )
arm_CSETM X8 Condition_NE
arm_NEG X11 X9
arm_LDR X5 X3 ( Shiftreg_Offset X4 3 )
arm_LSL X7 X5 X9
arm_ORR X7 X7 X10
arm_LSR X10 X5 X11
arm_AND X10 X10 X8
arm_STR X7 X3 ( Shiftreg_Offset X4 3 )
arm_ADD X4 X4 ( rvalue ( word 1 ) )
arm_CMP
arm_BCC ( word 2097120 )
arm_SUB X6 X0 ( rvalue ( word 1 ) )
arm_LDR X6 X3 ( Shiftreg_Offset X6 3 )
arm_MOV X11 ( rvalue ( word 1 ) )
arm_NEG X10 X6
arm_MOV X4 ( rvalue ( word 62 ) )
arm_ADD X11 X11 X11
arm_MOV X7 X6
arm_SUB X7 X7 X10
arm_CMP X10 X7
0xda9f33e7; (* arm_CSETM X7 Condition_CS *)
arm_SUB X11 X11 X7
arm_ADD X10 X10 X10
arm_AND X7 X7 X6
arm_SUB X10 X10 X7
arm_SUBS X4 X4 ( rvalue ( word 1 ) )
arm_BNE ( word 2097112 )
arm_CMP X10 X6
arm_CSINC X11 X11 X11 Condition_NE
arm_MOV X9 XZR
arm_ADDS X4 XZR XZR
arm_LDR X7 X3 ( Shiftreg_Offset X4 3 )
arm_MUL X8 X11 X7
arm_ADCS X8 X8 X9
arm_UMULH X9 X11 X7
arm_STR X8 X1 ( Shiftreg_Offset X4 3 )
arm_ADD X4 X4 ( rvalue ( word 1 ) )
arm_SUB X7 X4 X0
arm_CBNZ X7 ( word 2097124 )
arm_ADC XZR
arm_MOVZ X7 ( word 16384 ) 48
arm_SUBS X9 X9 X7
arm_CSETM X11
arm_NEGS X4 XZR
arm_LDR X7 X3 ( Shiftreg_Offset X4 3 )
arm_LDR X10 X1 ( Shiftreg_Offset X4 3 )
arm_AND X7 X7 X11
arm_SBCS X7 X7 X10
arm_STR X7 X1 ( Shiftreg_Offset X4 3 )
arm_ADD X4 X4 ( rvalue ( word 1 ) )
arm_SUB X7 X4 X0
arm_CBNZ X7 ( word 2097124 )
arm_MOV X9 XZR
arm_NEGS X5 XZR
arm_LDR X7 X1 ( Shiftreg_Offset X5 3 )
arm_EXTR X9 X7 X9 ( rvalue ( word 63 ) )
arm_LDR X10 X3 ( Shiftreg_Offset X5 3 )
arm_SBCS X9 X9 X10
arm_STR X9 X1 ( Shiftreg_Offset X5 3 )
arm_MOV X9 X7
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097120 )
arm_LSR ( rvalue ( word 63 ) )
arm_SBC XZR
arm_ADDS X5 XZR XZR
arm_LDR X7 X1 ( Shiftreg_Offset X5 3 )
arm_LDR X10 X3 ( Shiftreg_Offset X5 3 )
arm_AND X10 X10 X9
arm_ADCS X7 X7 X10
arm_STR X7 X1 ( Shiftreg_Offset X5 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097124 )
arm_MOV X9 XZR
arm_NEGS X5 XZR
arm_LDR X7 X1 ( Shiftreg_Offset X5 3 )
arm_EXTR X9 X7 X9 ( rvalue ( word 63 ) )
arm_LDR X10 X3 ( Shiftreg_Offset X5 3 )
arm_SBCS X9 X9 X10
arm_STR X9 X1 ( Shiftreg_Offset X5 3 )
arm_MOV X9 X7
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097120 )
arm_LSR ( rvalue ( word 63 ) )
arm_SBC XZR
arm_ADDS X5 XZR XZR
arm_LDR X7 X1 ( Shiftreg_Offset X5 3 )
arm_LDR X10 X3 ( Shiftreg_Offset X5 3 )
arm_AND X10 X10 X9
arm_ADCS X7 X7 X10
arm_STR X7 X1 ( Shiftreg_Offset X5 3 )
arm_STR X7 X3 ( Shiftreg_Offset X5 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097120 )
arm_MOV X6 XZR
arm_MOV
arm_MOV X5 XZR
arm_MOV X10 XZR
arm_ADDS X9 XZR XZR
arm_LDR X7 X1 ( Shiftreg_Offset X5 3 )
arm_MUL X8 X6 X7
arm_ADCS X10 X10 X9
arm_UMULH X9 X6 X7
arm_ADC XZR
arm_ADDS X8 X10 X8
arm_LDR X10 X3 ( Shiftreg_Offset X5 3 )
arm_STR X8 X3 ( Shiftreg_Offset X5 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
0xb5fffec7; (* arm_CBNZ X7 (word 2097112) *)
arm_ADCS X6 X10 X9
0xda9f33e8; (* arm_CSETM X8 Condition_CS *)
arm_ADDS X5 XZR XZR
arm_LDR X7 X3 ( Shiftreg_Offset X5 3 )
arm_LDR X10 X1 ( Shiftreg_Offset X5 3 )
arm_AND X10 X10 X8
arm_ADCS X7 X7 X10
arm_STR X7 X3 ( Shiftreg_Offset X5 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097124 )
arm_ADC X6 X6 XZR
arm_SUBS X4 X4 ( rvalue ( word 1 ) )
arm_BNE ( word 2097044 )
0xf9400047; (* arm_LDR X7 X2 (Immediate_Offset (word 0)) *)
arm_LSL X11 X7 ( rvalue ( word 2 ) )
arm_SUB X11 X7 X11
arm_EOR X11 X11 ( rvalue ( word 2 ) )
arm_MOV X8 ( rvalue ( word 1 ) )
arm_MADD X9 X7 X11 X8
arm_MUL X10
arm_MADD X11 X9 X11 X11
arm_MUL X9 X10 X10
arm_MADD X11 X10 X11 X11
arm_MUL X10
arm_MADD X11 X9 X11 X11
arm_MADD X11 X10 X11 X11
arm_LDR X10 X3 ( Immediate_Offset ( word 0 ) )
0x9b0b7d4b; (* arm_MUL X11 X10 X11 *)
arm_MUL X8 X11 X7
arm_UMULH X9 X11 X7
arm_MOV X5 ( rvalue ( word 1 ) )
arm_SUB X7 X0 ( rvalue ( word 1 ) )
arm_CMN X10 X8
arm_CBZ X7 ( word 52 )
arm_LDR X7 X2 ( Shiftreg_Offset X5 3 )
arm_LDR X10 X3 ( Shiftreg_Offset X5 3 )
arm_MUL X8 X11 X7
arm_ADCS X10 X10 X9
arm_UMULH X9 X11 X7
arm_ADC XZR
arm_ADDS X10 X10 X8
arm_SUB X7 X5 ( rvalue ( word 1 ) )
arm_STR X10 X3 ( Shiftreg_Offset X7 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097108 )
arm_ADCS X6 X6 X9
0xda9f33e8; (* arm_CSETM X8 Condition_CS *)
arm_SUB X7 X0 ( rvalue ( word 1 ) )
arm_STR X6 X3 ( Shiftreg_Offset X7 3 )
arm_NEGS X5 XZR
arm_LDR X7 X3 ( Shiftreg_Offset X5 3 )
arm_LDR X10 X2 ( Shiftreg_Offset X5 3 )
arm_AND X10 X10 X8
arm_SBCS X7 X7 X10
arm_STR X7 X1 ( Shiftreg_Offset X5 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097124 )
arm_RET X30
];;
let BIGNUM_AMONTIFIER_EXEC = ARM_MK_EXEC_RULE bignum_amontifier_mc;;
(* ------------------------------------------------------------------------- *)
(* Proof. *)
(* ------------------------------------------------------------------------- *)
* * This actually works mod 32 but if anything this is more convenient * *
let WORD_NEGMODINV_SEED_LEMMA_16 = prove
(`!a x:int64.
ODD a /\
word_xor (word_sub (word a) (word_shl (word a) 2)) (word 2) = x
==> (a * val x + 1 == 0) (mod 16)`,
REPEAT STRIP_TAC THEN REWRITE_TAC[CONG; MOD_0] THEN
TRANS_TAC EQ_TRANS
`(val(word a:int64) MOD 16 * val(x:int64) MOD 16 + 1) MOD 16` THEN
REWRITE_TAC[ARITH_RULE `16 = 2 EXP 4`] THEN CONJ_TAC THENL
[REWRITE_TAC[VAL_WORD; DIMINDEX_64; MOD_MOD_EXP_MIN] THEN
CONV_TAC NUM_REDUCE_CONV THEN CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
REWRITE_TAC[VAL_MOD; NUMSEG_LT; ARITH_EQ; ARITH]] THEN
SUBGOAL_THEN `bit 0 (word a:int64)` MP_TAC THENL
[ASM_REWRITE_TAC[BIT_LSB_WORD];
EXPAND_TAC "x" THEN POP_ASSUM_LIST(K ALL_TAC) THEN DISCH_TAC] THEN
CONV_TAC(ONCE_DEPTH_CONV EXPAND_NSUM_CONV) THEN
CONV_TAC(TOP_DEPTH_CONV BIT_WORD_CONV) THEN
MAP_EVERY ASM_CASES_TAC
[`bit 1 (word a:int64)`;`bit 2 (word a:int64)`;`bit 3 (word a:int64)`] THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC NUM_REDUCE_CONV);;
(*** Copied from bignum_shl_small proof, similar logic to bitloop ***)
let lemma1 = prove
(`!n c. word_and (word_jushr (word n) (word_neg (word c)))
(word_neg (word (bitval (~(c MOD 64 = 0))))):int64 =
word_ushr (word n) (64 - c MOD 64)`,
REPEAT GEN_TAC THEN REWRITE_TAC[WORD_AND_MASK; COND_SWAP] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[] THENL
[CONV_TAC SYM_CONV THEN REWRITE_TAC[GSYM VAL_EQ_0; VAL_WORD_USHR] THEN
REWRITE_TAC[SUB_0] THEN MATCH_MP_TAC DIV_LT THEN REWRITE_TAC[VAL_BOUND_64];
W(MP_TAC o PART_MATCH (lhand o rand) WORD_JUSHR_NEG o lhand o snd) THEN
ASM_REWRITE_TAC[DIMINDEX_64; MOD_64_CLAUSES] THEN
DISCH_THEN MATCH_MP_TAC THEN CONV_TAC NUM_REDUCE_CONV THEN
CONV_TAC DIVIDES_CONV]);;
(*** This is for the rather specific remainder computation below ***)
let remalemma = prove
(`!x n q b.
(x <= q * n <=> b) /\ ~(n divides x) /\ abs(&x - &q * &n:real) <= &n
==> &(x MOD n):real = &(bitval b) * &n + &x - &q * &n`,
REPEAT GEN_TAC THEN
REWRITE_TAC[GSYM int_of_num_th; GSYM int_sub_th; GSYM int_add_th;
GSYM int_mul_th; GSYM int_add_th; GSYM int_abs_th] THEN
REWRITE_TAC[GSYM int_le; GSYM int_eq] THEN
REWRITE_TAC[GSYM INT_OF_NUM_REM; num_divides] THEN
REWRITE_TAC[GSYM INT_OF_NUM_LE; GSYM INT_OF_NUM_MUL] THEN
ASM_CASES_TAC `b:bool` THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN
STRIP_TAC THEN MATCH_MP_TAC INT_REM_UNIQ THENL
[EXISTS_TAC `&q - &1:int`; EXISTS_TAC `&q:int`] THEN
REPLICATE_TAC 2 (CONJ_TAC THENL [ASM_INT_ARITH_TAC; ALL_TAC]) THEN
REWRITE_TAC[INT_ABS_NUM; INT_MUL_LZERO; INT_MUL_LID; INT_ADD_LID] THEN
REWRITE_TAC[INT_ARITH `n + x - qn:int < n <=> x < qn`] THEN
REWRITE_TAC[INT_ARITH `x - q * n:int < n <=> x < (q + &1) * n`] THEN
REWRITE_TAC[INT_LT_LE] THEN
(CONJ_TAC THENL [ASM_INT_ARITH_TAC; DISCH_TAC]) THEN
UNDISCH_TAC `~((&n:int) divides (&x))` THEN
ASM_REWRITE_TAC[] THEN CONV_TAC INTEGER_RULE);;
let BIGNUM_AMONTIFIER_CORRECT = time prove
(`!k z m t n pc.
nonoverlapping (z,8 * val k) (t,8 * val k) /\
ALLPAIRS nonoverlapping [(z,8 * val k); (t,8 * val k)]
[(word pc,0x31c); (m,8 * val k)]
==> ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_amontifier_mc /\
read PC s = word pc /\
C_ARGUMENTS [k; z; m; t] s /\
bignum_from_memory (m,val k) s = n)
(\s. read PC s = word(pc + 0x318) /\
(ODD n
==> (bignum_from_memory (z,val k) s ==
2 EXP (128 * val k)) (mod n)))
(MAYCHANGE [PC; X4; X5; X6; X7; X8; X9; X10; X11] ,,
MAYCHANGE [memory :> bytes(z,8 * val k);
memory :> bytes(t,8 * val k)] ,,
MAYCHANGE SOME_FLAGS)`,
W64_GEN_TAC `k:num` THEN
MAP_EVERY X_GEN_TAC
[`z:int64`; `mm:int64`; `t:int64`; `m:num`; `pc:num`] THEN
REWRITE_TAC[ALL; ALLPAIRS; NONOVERLAPPING_CLAUSES] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
BIGNUM_TERMRANGE_TAC `k:num` `m:num` THEN
(*** Degenerate k = 0 case ***)
ASM_CASES_TAC `k = 0` THENL
[UNDISCH_THEN `k = 0` SUBST_ALL_TAC THEN
REPEAT(FIRST_X_ASSUM(SUBST_ALL_TAC o MATCH_MP (ARITH_RULE
`a < 2 EXP (64 * 0) ==> a = 0`))) THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC [1] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[ODD];
ALL_TAC] THEN
(*** Get a basic bound on k from the nonoverlapping assumptions ***)
FIRST_ASSUM(MP_TAC o MATCH_MP (ONCE_REWRITE_RULE[IMP_CONJ]
NONOVERLAPPING_IMP_SMALL_1)) THEN
ANTS_TAC THENL [CONV_TAC NUM_REDUCE_CONV; DISCH_TAC] THEN
(*** Initial copying into temporary buffer, "copyinloop" ***)
ENSURES_WHILE_PUP_TAC `k:num` `pc + 0x8` `pc + 0x14`
`\i s. (read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory(mm,k) s = m /\
read X4 s = word i /\
bignum_from_memory(word_add mm (word(8 * i)),k - i) s =
highdigits m i /\
bignum_from_memory(t,i) s = lowdigits m i) /\
(read X9 s = word(bigdigit m (i - 1)))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; LOWDIGITS_0] THEN
REWRITE_TAC[MULT_CLAUSES; WORD_ADD_0; SUB_0; HIGHDIGITS_0] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--3) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES; ADD_SUB] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2);
ASM_SIMP_TAC[LOWDIGITS_SELF]] THEN
(*** The digitwise normalization "normloop" ***)
ENSURES_SEQUENCE_TAC `pc + 0x54`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory(mm,k) s = m /\
m divides bignum_from_memory(t,k) s /\
read X9 s = word(bigdigit (bignum_from_memory(t,k) s) (k - 1)) /\
(ODD m ==> 2 EXP (64 * (k - 1)) <= bignum_from_memory(t,k) s)` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `k = 1` THENL
[UNDISCH_THEN `k = 1` SUBST_ALL_TAC THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--4) THEN
ASM_SIMP_TAC[LOWDIGITS_SELF; DIVIDES_REFL; SUB_REFL] THEN
REWRITE_TAC[ARITH_RULE `2 EXP (64 * 0) <= m <=> ~(m = 0)`] THEN
MESON_TAC[ODD];
ALL_TAC] THEN
MP_TAC(ARITH_RULE `k - 1 = 0 <=> k = 0 \/ k = 1`) THEN
ASM_REWRITE_TAC[] THEN DISCH_TAC THEN
ENSURES_WHILE_PUP_TAC `k - 1` `pc + 0x24` `pc + 0x50`
`\i s. (read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory(mm,k) s = m /\
read X4 s = word(k - 1 - i) /\
read X9 s = word(bigdigit (bignum_from_memory(t,k) s) (k - 1)) /\
m divides bignum_from_memory(t,k) s /\
(ODD m ==> 2 EXP (64 * i) <= bignum_from_memory(t,k) s)) /\
(read ZF s <=> i = k - 1)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[MP_TAC(ISPECL [`word k:int64`; `word 1:int64`] VAL_WORD_SUB_CASES) THEN
ASM_SIMP_TAC[VAL_WORD_1; LE_1] THEN DISCH_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--4) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[SUB_0] THEN
ASM_SIMP_TAC[DIVIDES_REFL; WORD_SUB; LE_1] THEN
REWRITE_TAC[ARITH_RULE `2 EXP (64 * 0) <= m <=> ~(m = 0)`] THEN
MESON_TAC[ODD];
ALL_TAC; (*** Do the main loop invariant below ***)
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC [1];
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC [1]] THEN
(*** Nested loop "shufloop" ***)
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `n:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `n:num` THEN
GLOBALIZE_PRECONDITION_TAC THEN
ABBREV_TAC `topz <=> bigdigit n (k - 1) = 0` THEN
ENSURES_WHILE_PUP_TAC `k:num` `pc + 0x30` `pc + 0x44`
`\j s. (read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
read X4 s = word (k - 1 - i) /\
read X5 s = word j /\
read X7 s = (if j = 0 then word 0 else word(bigdigit n (j - 1))) /\
(read ZF s <=> topz) /\
bignum_from_memory(word_add t (word(8 * j)),k - j) s =
highdigits n j /\
bignum_from_memory(t,j) s =
lowdigits (if topz then 2 EXP 64 * n else n) j) /\
(read X9 s =
word(bigdigit (bignum_from_memory(t,j) s) (j - 1)))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--3) THEN
REWRITE_TAC[VAL_WORD_SUB_EQ_0; VAL_WORD_0; HIGHDIGITS_0; SUB_0] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; BIGDIGIT_BOUND; DIMINDEX_64] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL; LOWDIGITS_0] THEN
ASM_REWRITE_TAC[WORD_ADD_0; MULT_CLAUSES; BIGNUM_FROM_MEMORY_BYTES];
ALL_TAC; (*** Inner loop invariant below ***)
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
VAL_INT64_TAC `k - 1` THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
RULE_ASSUM_TAC(REWRITE_RULE[VAL_WORD_SUB_EQ_0]) THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC [3] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> s) /\ q /\ r ==> p /\ q /\ r /\ s`) THEN
CONJ_TAC THENL
[REWRITE_TAC[ARITH_RULE `a - (i + 1) = a - i - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < k - 1 ==> 1 <= k - 1 - i`];
ALL_TAC] THEN
CONJ_TAC THENL
[DISCH_THEN SUBST1_TAC THEN
W(MP_TAC o PART_MATCH (lhand o rand) VAL_WORD_EQ o
lhand o lhand o snd) THEN
REWRITE_TAC[DIMINDEX_64] THEN ANTS_TAC THENL
[ALL_TAC; DISCH_THEN SUBST1_TAC] THEN
MAP_EVERY UNDISCH_TAC [`k < 2 EXP 64`; `i < k - 1`] THEN ARITH_TAC;
ALL_TAC] THEN
W(MP_TAC o PART_MATCH (lhand o rand) LOWDIGITS_SELF o
rand o lhand o snd) THEN
ANTS_TAC THENL
[EXPAND_TAC "topz" THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN
SUBGOAL_THEN `n = lowdigits n ((k - 1) + 1)` SUBST1_TAC THENL
[ASM_SIMP_TAC[SUB_ADD; LE_1; LOWDIGITS_SELF];
ASM_REWRITE_TAC[LOWDIGITS_CLAUSES; ADD_CLAUSES; MULT_CLAUSES]] THEN
SUBGOAL_THEN `64 * k = 64 + 64 * (k - 1)` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC; REWRITE_TAC[EXP_ADD]] THEN
SIMP_TAC[LT_MULT_LCANCEL; LOWDIGITS_BOUND; EXP_EQ_0; ARITH_EQ];
DISCH_THEN SUBST1_TAC] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[] THENL
[ASM_SIMP_TAC[DIVIDES_LMUL; EXP_ADD; LE_MULT_LCANCEL; EXP_EQ_0;
ARITH_EQ; ARITH_RULE `64 * (i + 1) = 64 + 64 * i`];
DISCH_TAC THEN TRANS_TAC LE_TRANS `2 EXP (64 * (k - 1))`] THEN
ASM_SIMP_TAC[LE_EXP; ARITH_EQ; ARITH_RULE
`i < k - 1 ==> 64 * (i + 1) <= 64 * (k - 1)`] THEN
SUBGOAL_THEN `n = lowdigits n ((k - 1) + 1)` SUBST1_TAC THENL
[ASM_SIMP_TAC[SUB_ADD; LE_1; LOWDIGITS_SELF];
ASM_REWRITE_TAC[LOWDIGITS_CLAUSES; ADD_CLAUSES; MULT_CLAUSES]] THEN
MATCH_MP_TAC(ARITH_RULE `e * 1 <= e * d ==> e <= e * d + c`) THEN
ASM_SIMP_TAC[LE_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ; LE_1]] THEN
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[ARITH_RULE `k - j = 0 <=> ~(j < k)`] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP; BIGDIGIT_BIGNUM_FROM_MEMORY] THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--5) THEN
ASM_REWRITE_TAC[ADD_SUB; GSYM WORD_ADD; ADD_EQ_0; ARITH_EQ] THEN
REWRITE_TAC[ARITH_RULE `j < j + 1`] THEN
UNDISCH_THEN `bigdigit n (k - 1) = 0 <=> topz` (SUBST_ALL_TAC o SYM) THEN
ASM_CASES_TAC `bigdigit n (k - 1) = 0` THEN ASM_REWRITE_TAC[] THEN
SIMP_TAC[LOWDIGITS_CLAUSES; VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THENL
[ALL_TAC; ARITH_TAC] THEN
ASM_CASES_TAC `j = 0` THEN ASM_REWRITE_TAC[MULT_CLAUSES; EXP] THEN
REWRITE_TAC[LOWDIGITS_0; VAL_WORD_0; ADD_CLAUSES] THEN
REWRITE_TAC[REWRITE_RULE[lowdigits] (GSYM LOWDIGITS_1)] THEN
REWRITE_TAC[MULT_CLAUSES; MOD_MULT] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
MATCH_MP_TAC(NUM_RING `x:num = y ==> a + e * x = e * y + a`) THEN
SUBGOAL_THEN `j = SUC(j - 1)`
(fun th -> GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [th])
THENL [UNDISCH_TAC `~(j = 0)` THEN ARITH_TAC; ALL_TAC] THEN
REWRITE_TAC[bigdigit; EXP_ADD; ARITH_RULE `64 * SUC j = 64 + 64 * j`] THEN
SIMP_TAC[DIV_MULT2; EXP_EQ_0; ARITH_EQ];
ALL_TAC] THEN
(*** Bitwise stage of normalization ***)
ENSURES_SEQUENCE_TAC `pc + 0x90`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory(mm,k) s = m /\
m divides bignum_from_memory(t,k) s /\
(ODD m ==> 2 EXP (64 * k - 1) <= bignum_from_memory(t,k) s)` THEN
CONJ_TAC THENL
[GHOST_INTRO_TAC `n:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `n:num` THEN GLOBALIZE_PRECONDITION_TAC THEN
(*** The "bitloop" loop ***)
ABBREV_TAC `c = 64 - bitsize(bigdigit n (k - 1))` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x6c` `pc + 0x88`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
read X4 s = word i /\
read X8 s = word_neg(word(bitval(~(c MOD 64 = 0)))) /\
read X9 s = word c /\
read X11 s = word_neg(word c) /\
bignum_from_memory(word_add t (word (8 * i)),k - i) s =
highdigits n i /\
2 EXP (64 * i) * val(read X10 s) + bignum_from_memory(t,i) s =
2 EXP (c MOD 64) * lowdigits n i` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--6) THEN
SIMP_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; BIGNUM_FROM_MEMORY_TRIVIAL] THEN
REWRITE_TAC[LOWDIGITS_0; DIV_0; VAL_WORD_0; MULT_CLAUSES; ADD_CLAUSES;
WORD_ADD_0; HIGHDIGITS_0; SUB_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[WORD_SUB_LZERO] THEN
SUBST1_TAC(SYM(WORD_REDUCE_CONV `word_not(word 0):int64`)) THEN
ONCE_REWRITE_TAC[GSYM COND_SWAP] THEN REWRITE_TAC[GSYM WORD_MASK] THEN
SUBST1_TAC(ARITH_RULE `63 = 2 EXP 6 - 1`) THEN
REWRITE_TAC[VAL_WORD_AND_MASK_WORD] THEN
CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[MOD_64_CLAUSES] THEN
SUBGOAL_THEN `word_clz(word(bigdigit n (k - 1)):int64) = c`
(fun th -> ASM_REWRITE_TAC[th]) THEN
REWRITE_TAC[WORD_CLZ_BITSIZE; DIMINDEX_64] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `b:int64` `read X10` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[ARITH_RULE `n - i = 0 <=> ~(i < n)`] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--7) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
SIMP_TAC[VAL_WORD_EQ; BIGDIGIT_BOUND; DIMINDEX_64] THEN
REWRITE_TAC[MOD_64_CLAUSES; LOWDIGITS_CLAUSES] THEN
REWRITE_TAC[EXP_ADD; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
FIRST_ASSUM(MATCH_MP_TAC o MATCH_MP (NUM_RING
`ee * b + m:num = c * l
==> e * d + y = c * z + b
==> (ee * e) * d + m + ee * y = c * (ee * z + l)`)) THEN
REWRITE_TAC[ADD_ASSOC; EQ_ADD_RCANCEL; lemma1] THEN
REWRITE_TAC[word_jshl; MOD_64_CLAUSES; DIMINDEX_64; VAL_WORD_USHR] THEN
W(MP_TAC o PART_MATCH (lhand o rand) VAL_WORD_OR_DISJOINT o
rand o lhand o snd) THEN
ANTS_TAC THENL
[REWRITE_TAC[WORD_EQ_BITS_ALT; BIT_WORD_0; BIT_WORD_AND] THEN
SIMP_TAC[BIT_WORD_SHL; DIMINDEX_64] THEN MATCH_MP_TAC(MESON[]
`(!i. q i ==> ~s i) ==> !i. p i ==> ~((q i /\ r i) /\ (s i))`) THEN
REWRITE_TAC[UPPER_BITS_ZERO] THEN
UNDISCH_THEN
`2 EXP (64 * i) * val(b:int64) + read (memory :> bytes (t,8 * i)) s7 =
2 EXP (c MOD 64) * lowdigits n i`
(MP_TAC o AP_TERM `\x. x DIV 2 EXP (64 * i)`) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
SIMP_TAC[DIV_MULT_ADD; EXP_EQ_0; ARITH_EQ] THEN
SIMP_TAC[DIV_LT; BIGNUM_FROM_MEMORY_BOUND; ADD_CLAUSES] THEN
DISCH_THEN SUBST1_TAC THEN
SIMP_TAC[RDIV_LT_EQ; EXP_EQ_0; ARITH_EQ] THEN
GEN_REWRITE_TAC RAND_CONV [MULT_SYM] THEN
REWRITE_TAC[LT_MULT_LCANCEL; LOWDIGITS_BOUND; EXP_EQ_0; ARITH_EQ];
DISCH_THEN SUBST1_TAC] THEN
SIMP_TAC[VAL_WORD_SHL; VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[ADD_ASSOC; EQ_ADD_RCANCEL] THEN
SUBGOAL_THEN `2 EXP 64 = 2 EXP (c MOD 64) * 2 EXP (64 - c MOD 64)`
SUBST1_TAC THENL
[REWRITE_TAC[GSYM EXP_ADD] THEN AP_TERM_TAC THEN ARITH_TAC;
REWRITE_TAC[MOD_MULT2; GSYM MULT_ASSOC; GSYM LEFT_ADD_DISTRIB]] THEN
REWRITE_TAC[DIVISION_SIMP];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2);
GHOST_INTRO_TAC `b:int64` `read X10` THEN
ASM_SIMP_TAC[LOWDIGITS_SELF] THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2)] THEN
FIRST_X_ASSUM(MP_TAC o MATCH_MP (ARITH_RULE
`e * b + z = cn
==> (e * b < e * 1 ==> e * b = 0)
==> cn < e ==> z = cn`)) THEN
ANTS_TAC THENL
[SIMP_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ; MULT_EQ_0] THEN ARITH_TAC;
ALL_TAC] THEN
ASM_CASES_TAC `n = 0` THENL
[ASM_REWRITE_TAC[MULT_CLAUSES; EXP_LT_0; ARITH_EQ] THEN
DISCH_THEN SUBST1_TAC THEN ASM_REWRITE_TAC[DIVIDES_0] THEN
DISCH_THEN(fun th -> FIRST_X_ASSUM(MP_TAC o C MATCH_MP th)) THEN
ASM_REWRITE_TAC[CONJUNCT1 LE; EXP_EQ_0; ARITH_EQ];
ALL_TAC] THEN
ANTS_TAC THENL
[SUBGOAL_THEN `64 * k = c MOD 64 + (64 * k - c MOD 64)` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC;
REWRITE_TAC[EXP_ADD; LT_MULT_LCANCEL; ARITH_EQ; EXP_EQ_0]] THEN
REWRITE_TAC[GSYM BITSIZE_LE] THEN
SUBGOAL_THEN
`n = 2 EXP (64 * (k - 1)) * highdigits n (k - 1) + lowdigits n (k - 1)`
SUBST1_TAC THENL [REWRITE_TAC[HIGH_LOW_DIGITS]; ALL_TAC] THEN
ASM_SIMP_TAC[HIGHDIGITS_TOP] THEN
UNDISCH_THEN `64 - bitsize (bigdigit n (k - 1)) = c`
(SUBST1_TAC o SYM) THEN
ASM_CASES_TAC `bigdigit n (k - 1) = 0` THENL
[ASM_REWRITE_TAC[BITSIZE_0; MULT_CLAUSES; ADD_CLAUSES] THEN
CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[BITSIZE_LE; SUB_0] THEN
TRANS_TAC LTE_TRANS `2 EXP (64 * (k - 1))` THEN
ASM_REWRITE_TAC[LOWDIGITS_BOUND; LE_EXP; ARITH_EQ] THEN ARITH_TAC;
ASM_SIMP_TAC[BITSIZE_MULT_ADD; LOWDIGITS_BOUND]] THEN
MATCH_MP_TAC(ARITH_RULE `a + c <= b ==> a <= b - c MOD 64`) THEN
MATCH_MP_TAC(ARITH_RULE
`~(k = 0) /\ b <= 64 ==> (64 * (k - 1) + b) + (64 - b) <= 64 * k`) THEN
ASM_REWRITE_TAC[BITSIZE_LE; BIGDIGIT_BOUND];
DISCH_THEN SUBST1_TAC] THEN
ASM_SIMP_TAC[DIVIDES_LMUL] THEN
DISCH_THEN(fun th -> FIRST_X_ASSUM(MP_TAC o C MATCH_MP th)) THEN
SUBGOAL_THEN `64 * k - 1 = c MOD 64 + (64 * k - 1 - c MOD 64)`
SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC;
REWRITE_TAC[EXP_ADD; LE_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ]] THEN
REWRITE_TAC[GSYM NOT_LT; GSYM BITSIZE_LE] THEN DISCH_TAC THEN
MATCH_MP_TAC(ARITH_RULE `~(b = 0) /\ a <= b + c ==> a - 1 - c < b`) THEN
ASM_REWRITE_TAC[BITSIZE_EQ_0] THEN
UNDISCH_THEN `64 - bitsize (bigdigit n (k - 1)) = c`
(SUBST1_TAC o SYM) THEN
ASM_SIMP_TAC[GSYM HIGHDIGITS_TOP; highdigits; BITSIZE_DIV] THEN
ASM_SIMP_TAC[MOD_LT; ARITH_RULE `b < a ==> 64 - (a - b) < 64`] THEN
UNDISCH_TAC `64 * (k - 1) < bitsize n` THEN ARITH_TAC;
ALL_TAC] THEN
(*** Introduce the multiple n, and abbreviations for high and low parts ***)
GHOST_INTRO_TAC `n:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `n:num` THEN
GLOBALIZE_PRECONDITION_TAC THEN
ABBREV_TAC `h = bigdigit n (k - 1)` THEN
ABBREV_TAC `l = lowdigits n (k - 1)` THEN
SUBGOAL_THEN
`h < 2 EXP 64 /\ l < 2 EXP (64 * (k - 1)) /\
2 EXP (64 * (k - 1)) * h + l = n /\
(ODD m ==> 2 EXP 63 <= h)`
STRIP_ASSUME_TAC THENL
[UNDISCH_THEN `bigdigit n (k - 1) = h` (SUBST1_TAC o SYM) THEN
UNDISCH_THEN `lowdigits n (k - 1) = l` (SUBST1_TAC o SYM) THEN
REWRITE_TAC[LOWDIGITS_BOUND; BIGDIGIT_BOUND] THEN
ASM_SIMP_TAC[GSYM HIGHDIGITS_TOP; HIGH_LOW_DIGITS] THEN
SIMP_TAC[highdigits; LE_RDIV_EQ; EXP_EQ_0; ARITH_EQ; GSYM EXP_ADD] THEN
ASM_SIMP_TAC[ARITH_RULE `~(k = 0) ==> 64 * (k - 1) + 63 = 64 * k - 1`];
ALL_TAC] THEN
(**** The somewhat stupid quotient loop ***)
ENSURES_SEQUENCE_TAC `pc + 0xd8`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
(ODD m ==> read X11 s = word(2 EXP 126 DIV h))` THEN
CONJ_TAC THENL
[ENSURES_WHILE_PUP_TAC `62` `pc + 0xa4` `pc + 0xcc`
`\i s. (read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
read X6 s = word h /\
read X4 s = word(62 - i) /\
val(read X11 s) < 2 EXP (i + 1) /\
(ODD m
==> val(read X11 s) * h + val(read X10 s) = 2 EXP (64 + i) /\
val(read X10 s) <= h)) /\
(read ZF s <=> i = 62)` THEN
REPEAT CONJ_TAC THENL
[ARITH_TAC;
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
MP_TAC(ISPECL [`k:num`; `t:int64`; `s0:armstate`; `k - 1`]
BIGDIGIT_BIGNUM_FROM_MEMORY) THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[ARITH_RULE `k - 1 < k <=> ~(k = 0)`] THEN
DISCH_THEN(MP_TAC o SYM) THEN
GEN_REWRITE_TAC LAND_CONV [VAL_WORD_GALOIS] THEN
REWRITE_TAC[DIMINDEX_64] THEN STRIP_TAC THEN
SUBGOAL_THEN `word_sub (word k) (word 1):int64 = word(k - 1)`
ASSUME_TAC THENL [ASM_SIMP_TAC[WORD_SUB; LE_1; VAL_WORD_1]; ALL_TAC] THEN
VAL_INT64_TAC `k - 1` THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
SIMP_TAC[VAL_WORD_1; EXP_1; ADD_CLAUSES; SUB_0; ARITH_RULE `1 < 2`] THEN
DISCH_THEN(fun th -> REPEAT(FIRST_X_ASSUM(ASSUME_TAC o C MP th))) THEN
REWRITE_TAC[WORD_SUB_LZERO; VAL_WORD_1; MULT_CLAUSES] THEN
REWRITE_TAC[VAL_WORD_NEG_CASES; DIMINDEX_64] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64] THEN
MAP_EVERY UNDISCH_TAC [`2 EXP 63 <= h`; `h < 2 EXP 64`] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN
GHOST_INTRO_TAC `q:num` `\s. val(read X11 s)` THEN
GHOST_INTRO_TAC `r:num` `\s. val(read X10 s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GLOBALIZE_PRECONDITION_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--10) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
SUBST1_TAC(SYM(WORD_REDUCE_CONV `word_not(word 0):int64`)) THEN
ONCE_REWRITE_TAC[GSYM COND_SWAP] THEN REWRITE_TAC[GSYM WORD_MASK] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[REWRITE_TAC[ARITH_RULE `a - (i + 1) = a - i - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < k ==> 1 <= k - i`];
DISCH_THEN SUBST1_TAC] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64;
ARITH_RULE `i < 62 ==> (62 - (i + 1) = 0 <=> i + 1 = 62)`;
ARITH_RULE `62 - i < 2 EXP 64`] THEN
REWRITE_TAC[WORD_RULE `word_sub x (word_neg y) = word_add x y`] THEN
REWRITE_TAC[NOT_LT; GSYM WORD_ADD] THEN CONJ_TAC THENL
[MATCH_MP_TAC VAL_WORD_LT THEN ONCE_REWRITE_TAC[EXP_ADD] THEN
MATCH_MP_TAC(ARITH_RULE
`q < i /\ b <= 1 ==> (q + q) + b < i * 2 EXP 1`) THEN
ASM_REWRITE_TAC[BITVAL_BOUND];
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MP th)))] THEN
SUBST1_TAC(ISPECL
[`word h:int64`; `word r:int64`] VAL_WORD_SUB_CASES) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64] THEN
ASM_SIMP_TAC[ARITH_RULE `r <= h ==> (h - r <= r <=> h <= 2 * r)`] THEN
REWRITE_TAC[WORD_AND_MASK; GSYM MULT_2] THEN
ASM_CASES_TAC `h <= 2 * r` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
REWRITE_TAC[WORD_SUB_0; GSYM MULT_2] THENL
[SUBGOAL_THEN
`word_sub (word (2 * r)) (word h):int64 = word(2 * r - h)`
SUBST1_TAC THENL [ASM_REWRITE_TAC[WORD_SUB]; ALL_TAC] THEN
SUBGOAL_THEN `2 * r - h < 2 EXP 64` ASSUME_TAC THENL
[MAP_EVERY UNDISCH_TAC [`r:num <= h`; `h < 2 EXP 64`] THEN ARITH_TAC;
ALL_TAC] THEN
SUBGOAL_THEN `2 * q + 1 < 2 EXP 64` ASSUME_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (ARITH_RULE
`q < 2 EXP (i + 1)
==> 2 EXP 1 * 2 EXP (i + 1) <= 2 EXP 64
==> 2 * q + 1 < 2 EXP 64`)) THEN
REWRITE_TAC[GSYM EXP_ADD; LE_EXP; ARITH_EQ] THEN
UNDISCH_TAC `i < 62` THEN ARITH_TAC;
ALL_TAC] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64] THEN
REWRITE_TAC[ADD_ASSOC] THEN ONCE_REWRITE_TAC[EXP_ADD] THEN
SIMPLE_ARITH_TAC;
RULE_ASSUM_TAC(REWRITE_RULE[NOT_LE]) THEN
ASM_SIMP_TAC[VAL_WORD_LE; LT_IMP_LE] THEN
SUBGOAL_THEN `2 * r < 2 EXP 64` ASSUME_TAC THENL
[MAP_EVERY UNDISCH_TAC [`2 * r < h`; `h < 2 EXP 64`] THEN ARITH_TAC;
ALL_TAC] THEN
SUBGOAL_THEN `2 * q < 2 EXP 64` ASSUME_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (ARITH_RULE
`q < 2 EXP (i + 1)
==> 2 EXP 1 * 2 EXP (i + 1) <= 2 EXP 64
==> 2 * q < 2 EXP 64`)) THEN
REWRITE_TAC[GSYM EXP_ADD; LE_EXP; ARITH_EQ] THEN
UNDISCH_TAC `i < 62` THEN ARITH_TAC;
ALL_TAC] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64] THEN
ASM_REWRITE_TAC[GSYM MULT_ASSOC; GSYM LEFT_ADD_DISTRIB] THEN
REWRITE_TAC[EXP_ADD] THEN ARITH_TAC];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC [1];
GHOST_INTRO_TAC `q:num` `\s. val(read X11 s)` THEN
GHOST_INTRO_TAC `r:num` `\s. val(read X10 s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GLOBALIZE_PRECONDITION_TAC THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--3) THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MP th))) THEN
ASM_SIMP_TAC[VAL_WORD_SUB_EQ_0; VAL_WORD_EQ; DIMINDEX_64] THEN
REWRITE_TAC[COND_SWAP; GSYM WORD_ADD] THEN
GEN_REWRITE_TAC LAND_CONV [GSYM COND_RAND] THEN
AP_TERM_TAC THEN CONV_TAC SYM_CONV THEN
MATCH_MP_TAC DIV_UNIQ THEN EXISTS_TAC `if r = h then 0 else r` THEN
UNDISCH_TAC `q * h + r = 2 EXP (64 + 62)` THEN
UNDISCH_TAC `r:num <= h` THEN REWRITE_TAC[LE_LT] THEN
UNDISCH_TAC `2 EXP 63 <= h` THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[LT_REFL] THEN ARITH_TAC];
ALL_TAC] THEN
* * Ghost the quotient estimate q = floor(2 ^ 126 / h ) * *
GHOST_INTRO_TAC `q:int64` `read X11` THEN GLOBALIZE_PRECONDITION_TAC THEN
(*** The "mulloop" doing q * n ***)
ENSURES_SEQUENCE_TAC `pc + 0x104`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
2 EXP (64 * k) * val(read X9 s) + bignum_from_memory(z,k) s =
val(q:int64) * n` THEN
CONJ_TAC THENL
[ENSURES_WHILE_UP_TAC `k:num` `pc + 0xe0` `pc + 0xf8`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
read X11 s = q /\
read X4 s = word i /\
bignum_from_memory(word_add t (word (8 * i)),k - i) s =
highdigits n i /\
2 EXP (64 * i) * (bitval(read CF s) + val(read X9 s)) +
bignum_from_memory(z,i) s =
val(q:int64) * lowdigits n i` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; SUB_0; VAL_WORD_0] THEN
REWRITE_TAC[BITVAL_CLAUSES; MULT_CLAUSES; WORD_ADD_0] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL; LOWDIGITS_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; HIGHDIGITS_0] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read X9` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [2;3] (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES; GSYM WORD_ADD] THEN
REWRITE_TAC[LEFT_ADD_DISTRIB; ADD_ASSOC] THEN FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [SYM th]) THEN
REWRITE_TAC[EXP_ADD; MULT_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read X9` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
RULE_ASSUM_TAC(REWRITE_RULE[VAL_WORD_SUB_EQ_0]) THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [3] [3] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
GEN_REWRITE_TAC (LAND_CONV o RAND_CONV) [ADD_SYM] THEN
DISCH_THEN(SUBST_ALL_TAC o SYM) THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (ARITH_RULE
`ee * (e * c + s) + z = qn
==> (ee * e * c < ee * e * 1 ==> ee * e * c = 0) /\ qn < e * ee
==> ee * s + z = qn`)) THEN
SIMP_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ; MULT_EQ_0] THEN
CONJ_TAC THENL [ARITH_TAC; MATCH_MP_TAC LT_MULT2] THEN
ASM_REWRITE_TAC[VAL_BOUND_64]];
ALL_TAC] THEN
(*** The "remloop" producing remainder by sign-correction ***)
* * We introduce an exclusion of m = 1 temporarily here . * *
ENSURES_SEQUENCE_TAC `pc + 0x134`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
(ODD m /\ ~(m = 1)
==> bignum_from_memory(z,k) s = 2 EXP (64 * k + 62) MOD n)` THEN
CONJ_TAC THENL
[GHOST_INTRO_TAC `rhi:num` `\s. val(read X9 s)` THEN
GHOST_INTRO_TAC `rlo:num` `bignum_from_memory (z,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `rlo:num` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GLOBALIZE_PRECONDITION_TAC THEN
ABBREV_TAC `b <=> 2 EXP (64 * k + 62) <= val(q:int64) * n` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x114` `pc + 0x12c`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X4 s = word i /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
read X11 s = word_neg(word(bitval b)) /\
bignum_from_memory(word_add t (word (8 * i)),k - i) s =
highdigits n i /\
bignum_from_memory(word_add z (word (8 * i)),k - i) s =
highdigits rlo i /\
&(bignum_from_memory(z,i) s):real =
&2 pow (64 * i) * &(bitval(~(read CF s))) +
(&(bitval b) * &(lowdigits n i) - &(lowdigits rlo i))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--4) THEN
REWRITE_TAC[SUB_0; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL; LOWDIGITS_0; HIGHDIGITS_0] THEN
REWRITE_TAC[ADD_CLAUSES; MULT_CLAUSES; WORD_ADD_0; BITVAL_CLAUSES] THEN
ASM_REWRITE_TAC[REAL_MUL_RZERO; BIGNUM_FROM_MEMORY_BYTES] THEN
CONV_TAC REAL_RAT_REDUCE_CONV THEN REWRITE_TAC[WORD_MASK] THEN
EXPAND_TAC "b" THEN REWRITE_TAC[GSYM NOT_LT; COND_SWAP] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64] THEN
CONV_TAC WORD_REDUCE_CONV THEN AP_THM_TAC THEN
AP_THM_TAC THEN AP_TERM_TAC THEN FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (RAND_CONV o LAND_CONV) [SYM th]) THEN
REWRITE_TAC[EXP_ADD] THEN
GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [ARITH_RULE `x = x + 0`] THEN
ASM_SIMP_TAC[LEXICOGRAPHIC_LT; EXP_LT_0; ARITH_EQ] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES; GSYM WORD_ADD] THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
REWRITE_TAC[REAL_POW_ADD; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
REWRITE_TAC[WORD_AND_MASK] THEN COND_CASES_TAC THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; VAL_WORD_0; MULT_CLAUSES] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `r:num` `bignum_from_memory (z,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `r:num` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GLOBALIZE_PRECONDITION_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
DISCH_THEN(CONJUNCTS_THEN2 MP_TAC ASSUME_TAC) THEN
DISCH_THEN(fun th -> ASSUME_TAC th THEN MP_TAC th) THEN
DISCH_THEN(fun th -> REPEAT(FIRST_X_ASSUM(ASSUME_TAC o C MP th)))] THEN
UNDISCH_TAC `2 EXP (64 * k - 1) <= n` THEN ASM_CASES_TAC `n = 0` THEN
ASM_REWRITE_TAC[CONJUNCT1 LE; EXP_EQ_0; ARITH_EQ] THEN DISCH_TAC THEN
SUBGOAL_THEN `val(q:int64) = 2 EXP 126 DIV h` SUBST_ALL_TAC THENL
[ASM_REWRITE_TAC[] THEN MATCH_MP_TAC VAL_WORD_EQ THEN
REWRITE_TAC[DIMINDEX_64] THEN MATCH_MP_TAC(ARITH_RULE
`x <= 2 EXP 126 DIV 2 EXP 63 ==> x < 2 EXP 64`) THEN
MATCH_MP_TAC DIV_MONO2 THEN ASM_REWRITE_TAC[] THEN ARITH_TAC;
UNDISCH_THEN `q:int64 = word(2 EXP 126 DIV h)` (K ALL_TAC)] THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC EQUAL_FROM_CONGRUENT_MOD_MOD THEN
MAP_EVERY EXISTS_TAC
[`64 * k`;
`&(bitval b) * &n +
(&2 pow (64 * k + 62) - &(2 EXP 126 DIV h) * &n):real`] THEN
ASM_REWRITE_TAC[] THEN CONJ_TAC THENL
[REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
UNDISCH_THEN `2 EXP (64 * k) * rhi + rlo = 2 EXP 126 DIV h * n`
(SUBST1_TAC o SYM) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; REAL_POW_ADD] THEN
REWRITE_TAC[ONCE_REWRITE_RULE[REAL_MUL_SYM] real_div] THEN
REWRITE_TAC[REAL_ADD_LDISTRIB; REAL_SUB_LDISTRIB; REAL_MUL_ASSOC] THEN
SIMP_TAC[REAL_MUL_LINV; REAL_POW_EQ_0; REAL_OF_NUM_EQ; ARITH_EQ] THEN
REAL_INTEGER_TAC;
ALL_TAC] THEN
ONCE_REWRITE_TAC[REAL_OF_NUM_POW] THEN MATCH_MP_TAC remalemma THEN
ASM_REWRITE_TAC[] THEN CONJ_TAC THENL
[DISCH_THEN(MP_TAC o SPEC `m:num` o MATCH_MP (NUMBER_RULE
`n divides x ==> !m:num. m divides n ==> m divides x`)) THEN
ASM_REWRITE_TAC[] THEN SIMP_TAC[DIVIDES_PRIMEPOW; PRIME_2] THEN
DISCH_THEN(X_CHOOSE_THEN `i:num` (SUBST_ALL_TAC o CONJUNCT2)) THEN
MAP_EVERY UNDISCH_TAC [`~(2 EXP i = 1)`; `ODD(2 EXP i)`] THEN
SIMP_TAC[ODD_EXP; ARITH; EXP];
ALL_TAC] THEN
MP_TAC(ASSUME `2 EXP (64 * (k - 1)) * h + l = n`) THEN DISCH_THEN(fun th ->
GEN_REWRITE_TAC (LAND_CONV o funpow 4 RAND_CONV) [SYM th]) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
SUBGOAL_THEN `64 * k + 62 = 64 * (k - 1) + 126` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC; REWRITE_TAC[REAL_POW_ADD]] THEN
REWRITE_TAC[REAL_ARITH
`ee * e - d * (ee * h + l):real = ee * (e - d * h) - d * l`] THEN
REWRITE_TAC[REAL_OF_NUM_POW; GSYM REAL_OF_NUM_MOD] THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
MATCH_MP_TAC(REAL_ARITH
`!x y:real. &0 <= x /\ &0 <= y /\ x <= e /\ y <= e
==> abs(x - y) <= e`) THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES; LE_0] THEN CONJ_TAC THENL
[MP_TAC(ASSUME `2 EXP (64 * (k - 1)) * h + l = n`) THEN
DISCH_THEN(fun th -> GEN_REWRITE_TAC RAND_CONV [SYM th]) THEN
MATCH_MP_TAC(ARITH_RULE `a:num < b ==> a <= b + c`) THEN
REWRITE_TAC[LT_MULT_LCANCEL; MOD_LT_EQ; EXP_EQ_0; ARITH_EQ] THEN
UNDISCH_TAC `2 EXP 63 <= h` THEN ARITH_TAC;
TRANS_TAC LE_TRANS `2 EXP 63 * 2 EXP (64 * (k - 1))` THEN CONJ_TAC THENL
[MATCH_MP_TAC LE_MULT2 THEN ASM_SIMP_TAC[LT_IMP_LE] THEN
SUBST1_TAC(ARITH_RULE `2 EXP 63 = 2 EXP 126 DIV 2 EXP 63`) THEN
MATCH_MP_TAC DIV_MONO2 THEN ASM_REWRITE_TAC[] THEN ARITH_TAC;
MP_TAC(ASSUME `2 EXP (64 * (k - 1)) * h + l = n`) THEN
DISCH_THEN(fun th -> GEN_REWRITE_TAC RAND_CONV [SYM th]) THEN
MATCH_MP_TAC(ARITH_RULE
`ee * e:num <= ee * h ==> e * ee <= ee * h + l`) THEN
ASM_REWRITE_TAC[LE_MULT_LCANCEL]]];
ALL_TAC] THEN
* * The first modular doubling , " dubloop1 " and " corrloop1 " * *
ENSURES_SEQUENCE_TAC `pc + 0x18c`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
(ODD m /\ ~(m = 1)
==> bignum_from_memory(z,k) s = 2 EXP (64 * k + 63) MOD n)` THEN
CONJ_TAC THENL
[GHOST_INTRO_TAC `p62:num` `bignum_from_memory (z,k)` THEN
GLOBALIZE_PRECONDITION_TAC THEN
BIGNUM_TERMRANGE_TAC `k:num` `p62:num` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x13c` `pc + 0x158`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
read X5 s = word i /\
(read X9 s =
if i = 0 then word 0 else word(bigdigit p62 (i - 1))) /\
bignum_from_memory (word_add z (word(8 * i)),k - i) s =
highdigits p62 i /\
bignum_from_memory (word_add t (word(8 * i)),k - i) s =
highdigits n i /\
&(bignum_from_memory(z,i) s):real =
&2 pow (64 * i) * &(bitval(~read CF s)) +
&(lowdigits (2 * p62) i) - &(lowdigits n i)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; BITVAL_CLAUSES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN REAL_ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--7) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[GSYM WORD_ADD; ADD_EQ_0; ARITH_EQ; ADD_SUB] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES] THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[ARITH_RULE `64 * (n + 1) = 64 * n + 64`; REAL_POW_ADD] THEN
MATCH_MP_TAC(REAL_RING
`ee * y:real = w - z
==> --e * c + s = y ==> z + ee * s = (ee * e) * c + w`) THEN
REWRITE_TAC[REAL_SUB_LDISTRIB; REAL_ARITH
`x - y:real = z <=> x = y + z`] THEN
CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN
REWRITE_TAC[REAL_ARITH `(x:real) * &2 pow k = &2 pow k * x`] THEN
AP_TERM_TAC THEN AP_TERM_TAC THEN
CONV_TAC(ONCE_DEPTH_CONV NUM_MOD_CONV) THEN
SIMP_TAC[VAL_WORD_SUBWORD_JOIN; DIMINDEX_64; LE_REFL] THEN
ONCE_REWRITE_TAC[COND_RAND] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND; VAL_WORD_0] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[ADD_CLAUSES] THENL
[REWRITE_TAC[ARITH_RULE `(2 EXP 64 * x) DIV 2 EXP 63 = 2 * x`] THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
TRANS_TAC EQ_TRANS
`(highdigits p62 (i - 1) DIV 2 EXP 63) MOD 2 EXP 64` THEN
CONJ_TAC THENL
[GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [HIGHDIGITS_STEP] THEN
ASM_SIMP_TAC[ARITH_RULE `~(i = 0) ==> i - 1 + 1 = i`; DIV_MOD] THEN
AP_THM_TAC THEN AP_TERM_TAC THEN REWRITE_TAC[GSYM CONG] THEN
MATCH_MP_TAC(NUMBER_RULE
`(a:num == a') (mod n)
==> (e * a + b == e * a' + b) (mod (n * e))`) THEN
REWRITE_TAC[bigdigit; highdigits; CONG; MOD_MOD_EXP_MIN] THEN
CONV_TAC NUM_REDUCE_CONV THEN REFL_TAC;
REWRITE_TAC[highdigits; DIV_DIV; GSYM EXP_ADD] THEN
ASM_SIMP_TAC[bigdigit; EXP; DIV_MULT2; ARITH_EQ; ARITH_RULE
`~(i = 0) ==> 64 * i = SUC(64 * (i - 1) + 63)`]];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF; HIGHDIGITS_ZERO; SUB_REFL] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL]] THEN
GHOST_INTRO_TAC `hi:bool` `read CF` THEN
GHOST_INTRO_TAC `lo:num` `bignum_from_memory(z,k)` THEN
GLOBALIZE_PRECONDITION_TAC THEN
BIGNUM_TERMRANGE_TAC `k:num` `lo:num` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x16c` `pc + 0x184`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
read X5 s = word i /\
bignum_from_memory (word_add z (word(8 * i)),k - i) s =
highdigits lo i /\
bignum_from_memory (word_add t (word(8 * i)),k - i) s =
highdigits n i /\
(p62 < n
==> read X9 s = word_neg(word(bitval(2 * p62 < n))) /\
&(bignum_from_memory(z,i) s):real =
(&(lowdigits lo i) +
&(bitval(2 * p62 < n)) * &(lowdigits n i)) -
&2 pow (64 * i) * &(bitval(read CF s)))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
RULE_ASSUM_TAC(REWRITE_RULE[VAL_WORD_SUB_EQ_0]) THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (3--5) THEN
ENSURES_FINAL_STATE_TAC THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; BITVAL_CLAUSES] THEN
REWRITE_TAC[REAL_MUL_RZERO; REAL_SUB_REFL; REAL_ADD_LID] THEN
DISCH_TAC THEN REWRITE_TAC[WORD_RULE
`word_sub a b = word_neg c <=> word_add c a = b`] THEN
MP_TAC(GEN `x:int64` (ISPEC `x:int64` WORD_USHR_MSB)) THEN
REWRITE_TAC[DIMINDEX_64] THEN CONV_TAC NUM_REDUCE_CONV THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
REWRITE_TAC[GSYM VAL_EQ; VAL_WORD_BITVAL; VAL_WORD_ADD_CASES] THEN
SIMP_TAC[DIMINDEX_64; BITVAL_BOUND; ARITH_RULE
`b <= 1 /\ c <= 1 ==> b + c < 2 EXP 64`] THEN
SUBGOAL_THEN `2 * p62 < 2 * n /\ 2 * p62 < 2 * 2 EXP (64 * k)`
MP_TAC THENL
[ASM_REWRITE_TAC[LT_MULT_LCANCEL; ARITH_EQ]; ALL_TAC] THEN
SUBGOAL_THEN
`2 * p62 = 2 EXP (64 * k) *
bitval(bit 63 (word(bigdigit p62 (k - 1)):int64)) +
lowdigits (2 * p62) k`
SUBST1_TAC THENL
[MP_TAC(SPECL [`2 * p62`; `k:num`] (CONJUNCT1 HIGH_LOW_DIGITS)) THEN
DISCH_THEN(fun th -> GEN_REWRITE_TAC LAND_CONV [SYM th]) THEN
AP_THM_TAC THEN AP_TERM_TAC THEN AP_TERM_TAC THEN
MP_TAC(ISPEC `word(bigdigit p62 (k - 1)):int64` WORD_USHR_MSB) THEN
REWRITE_TAC[DIMINDEX_64] THEN CONV_TAC NUM_REDUCE_CONV THEN
DISCH_THEN(MP_TAC o SYM o AP_TERM `val:int64->num`) THEN
REWRITE_TAC[VAL_WORD_BITVAL; VAL_WORD_USHR] THEN
DISCH_THEN SUBST1_TAC THEN
SIMP_TAC[VAL_WORD_EQ; BIGDIGIT_BOUND; DIMINDEX_64] THEN
ASM_SIMP_TAC[highdigits; ARITH_RULE
`~(k = 0) ==> 64 * k = SUC(64 * (k - 1) + 63)`] THEN
SIMP_TAC[DIV_MULT2; EXP; ARITH_EQ] THEN
REWRITE_TAC[EXP_ADD; GSYM DIV_DIV] THEN
AP_THM_TAC THEN AP_TERM_TAC THEN
REWRITE_TAC[bigdigit] THEN CONV_TAC SYM_CONV THEN
MATCH_MP_TAC MOD_LT THEN
ASM_SIMP_TAC[RDIV_LT_EQ; EXP_EQ_0; ARITH_EQ; GSYM EXP_ADD] THEN
ASM_SIMP_TAC[ARITH_RULE `~(k = 0) ==> 64 * (k - 1) + 64 = 64 * k`];
ALL_TAC] THEN
ASM_CASES_TAC `bit 63 (word(bigdigit p62 (k - 1)):int64)` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THENL
[ASM_SIMP_TAC[ARITH_RULE `n:num < e ==> ~(e + a < n)`] THEN
UNDISCH_TAC
`&lo:real =
&2 pow (64 * k) * &(bitval(~hi)) +
&(lowdigits (2 * p62) k) - &n` THEN
UNDISCH_TAC `lo < 2 EXP (64 * k)` THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
BOOL_CASES_TAC `hi:bool` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
REAL_ARITH_TAC;
STRIP_TAC THEN AP_TERM_TAC THEN
REWRITE_TAC[NOT_LT; TAUT `(p <=> ~q) <=> (~p <=> q)`] THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN
EXISTS_TAC `64 * k` THEN REWRITE_TAC[GSYM REAL_BITVAL_NOT] THEN
UNDISCH_THEN
`&lo:real =
&2 pow (64 * k) * &(bitval(~hi)) + &(lowdigits (2 * p62) k) - &n`
(SUBST1_TAC o SYM) THEN
ASM_REWRITE_TAC[REAL_OF_NUM_CLAUSES; LE_0]];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hi:int64` `read X9` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MATCH_MP th)) THEN
ASSUME_TAC th) THEN
ASM_REWRITE_TAC[LOWDIGITS_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[WORD_ADD; WORD_NEG_NEG; VAL_WORD_BITVAL; WORD_BITVAL_EQ_0;
LOWDIGITS_CLAUSES; WORD_NEG_EQ_0; BITVAL_BOUND; NOT_LT] THEN
REWRITE_TAC[WORD_AND_MASK] THEN COND_CASES_TAC THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN ASM_REWRITE_TAC[NOT_LT] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND; VAL_WORD_0;
BITVAL_CLAUSES; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
REWRITE_TAC[REAL_POW_ADD] THEN CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF; HIGHDIGITS_ZERO; SUB_REFL] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL]] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MP th)) THEN
ASSUME_TAC(CONJUNCT2 th) THEN MP_TAC(CONJUNCT1 th)) THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MP th)) THEN
ASSUME_TAC th) THEN
SUBGOAL_THEN `2 EXP (64 * k + 63) MOD n =
(2 * 2 EXP (64 * k + 62) MOD n) MOD n`
SUBST1_TAC THENL
[REWRITE_TAC[ARITH_RULE `n + 63 = SUC(n + 62)`; EXP] THEN
CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
SUBGOAL_THEN `p62:num < n`
(fun th -> FIRST_X_ASSUM(MP_TAC o C MP th) THEN ASSUME_TAC th)
THENL
[ASM_REWRITE_TAC[MOD_LT_EQ] THEN
UNDISCH_TAC `2 EXP (64 * k - 1) <= n` THEN
SIMP_TAC[GSYM NOT_LT; CONTRAPOS_THM; EXP_LT_0] THEN ARITH_TAC;
UNDISCH_THEN `p62 = 2 EXP (64 * k + 62) MOD n` (SUBST1_TAC o SYM)] THEN
STRIP_TAC THEN
ASM_SIMP_TAC[MOD_ADD_CASES; MULT_2; ARITH_RULE
`p62 < n ==> p62 + p62 < 2 * n`] THEN
REWRITE_TAC[GSYM MULT_2] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN
MAP_EVERY EXISTS_TAC [`64 * k`; `&0:real`] THEN CONJ_TAC THENL
[REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; REAL_OF_NUM_CLAUSES] THEN
REWRITE_TAC[LE_0; BIGNUM_FROM_MEMORY_BOUND];
ALL_TAC] THEN
CONJ_TAC THENL
[MAP_EVERY UNDISCH_TAC [`p62:num < n`; `n < 2 EXP (64 * k)`] THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN ARITH_TAC;
REWRITE_TAC[INTEGER_CLOSED]] THEN
ASM_REWRITE_TAC[] THEN REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
COND_CASES_TAC THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
ASM_SIMP_TAC[GSYM REAL_OF_NUM_SUB; GSYM NOT_LT] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
REWRITE_TAC[ONCE_REWRITE_RULE[REAL_MUL_SYM] real_div] THEN
REWRITE_TAC[REAL_ADD_LDISTRIB; REAL_SUB_LDISTRIB; REAL_MUL_ASSOC] THEN
REWRITE_TAC[REAL_FIELD `inv(&2 pow n) * &2 pow n = (&1:real)`] THEN
CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN
REWRITE_TAC[REAL_ARITH
`--(&2) * e * a + e * b + c:real = e * (b - &2 * a) + c`] THEN
MATCH_MP_TAC INTEGER_ADD THEN
(CONJ_TAC THENL [ALL_TAC; REAL_INTEGER_TAC]) THEN
REWRITE_TAC[REAL_ARITH `inv x * (a - b):real = (a - b) / x`] THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
W(MP_TAC o PART_MATCH (rand o rand) REAL_CONGRUENCE o snd) THEN
REWRITE_TAC[EXP_EQ_0; ARITH_EQ] THEN DISCH_THEN(SUBST1_TAC o SYM) THEN
REWRITE_TAC[CONG; lowdigits] THEN CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
* * The second modular doubling , " dubloop2 " and " corrloop2 " * *
ENSURES_SEQUENCE_TAC `pc + 0x1e8`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
(ODD m /\ ~(m = 1)
==> bignum_from_memory(z,k) s = 2 EXP (64 * k + 64) MOD n /\
bignum_from_memory(t,k) s = 2 EXP (64 * k + 64) MOD n)` THEN
CONJ_TAC THENL
[GHOST_INTRO_TAC `p63:num` `bignum_from_memory (z,k)` THEN
GLOBALIZE_PRECONDITION_TAC THEN
BIGNUM_TERMRANGE_TAC `k:num` `p63:num` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x194` `pc + 0x1b0`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
read X5 s = word i /\
(read X9 s =
if i = 0 then word 0 else word(bigdigit p63 (i - 1))) /\
bignum_from_memory (word_add z (word(8 * i)),k - i) s =
highdigits p63 i /\
bignum_from_memory (word_add t (word(8 * i)),k - i) s =
highdigits n i /\
&(bignum_from_memory(z,i) s):real =
&2 pow (64 * i) * &(bitval(~read CF s)) +
&(lowdigits (2 * p63) i) - &(lowdigits n i)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; BITVAL_CLAUSES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN REAL_ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--7) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[GSYM WORD_ADD; ADD_EQ_0; ARITH_EQ; ADD_SUB] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES] THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[ARITH_RULE `64 * (n + 1) = 64 * n + 64`; REAL_POW_ADD] THEN
MATCH_MP_TAC(REAL_RING
`ee * y:real = w - z
==> --e * c + s = y ==> z + ee * s = (ee * e) * c + w`) THEN
REWRITE_TAC[REAL_SUB_LDISTRIB; REAL_ARITH
`x - y:real = z <=> x = y + z`] THEN
CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN
REWRITE_TAC[REAL_ARITH `(x:real) * &2 pow k = &2 pow k * x`] THEN
AP_TERM_TAC THEN AP_TERM_TAC THEN
CONV_TAC(ONCE_DEPTH_CONV NUM_MOD_CONV) THEN
SIMP_TAC[VAL_WORD_SUBWORD_JOIN; DIMINDEX_64; LE_REFL] THEN
ONCE_REWRITE_TAC[COND_RAND] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND; VAL_WORD_0] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[ADD_CLAUSES] THENL
[REWRITE_TAC[ARITH_RULE `(2 EXP 64 * x) DIV 2 EXP 63 = 2 * x`] THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
TRANS_TAC EQ_TRANS
`(highdigits p63 (i - 1) DIV 2 EXP 63) MOD 2 EXP 64` THEN
CONJ_TAC THENL
[GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [HIGHDIGITS_STEP] THEN
ASM_SIMP_TAC[ARITH_RULE `~(i = 0) ==> i - 1 + 1 = i`; DIV_MOD] THEN
AP_THM_TAC THEN AP_TERM_TAC THEN REWRITE_TAC[GSYM CONG] THEN
MATCH_MP_TAC(NUMBER_RULE
`(a:num == a') (mod n)
==> (e * a + b == e * a' + b) (mod (n * e))`) THEN
REWRITE_TAC[bigdigit; highdigits; CONG; MOD_MOD_EXP_MIN] THEN
CONV_TAC NUM_REDUCE_CONV THEN REFL_TAC;
REWRITE_TAC[highdigits; DIV_DIV; GSYM EXP_ADD] THEN
ASM_SIMP_TAC[bigdigit; EXP; DIV_MULT2; ARITH_EQ; ARITH_RULE
`~(i = 0) ==> 64 * i = SUC(64 * (i - 1) + 63)`]];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF; HIGHDIGITS_ZERO; SUB_REFL] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL]] THEN
GHOST_INTRO_TAC `hi:bool` `read CF` THEN
GHOST_INTRO_TAC `lo:num` `bignum_from_memory(z,k)` THEN
GLOBALIZE_PRECONDITION_TAC THEN
BIGNUM_TERMRANGE_TAC `k:num` `lo:num` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x1c4` `pc + 0x1e0`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
read X5 s = word i /\
bignum_from_memory (word_add z (word(8 * i)),k - i) s =
highdigits lo i /\
bignum_from_memory (word_add t (word(8 * i)),k - i) s =
highdigits n i /\
(p63 < n
==> read X9 s = word_neg(word(bitval(2 * p63 < n))) /\
&(bignum_from_memory(z,i) s):real =
(&(lowdigits lo i) +
&(bitval(2 * p63 < n)) * &(lowdigits n i)) -
&2 pow (64 * i) * &(bitval(read CF s)) /\
&(bignum_from_memory(t,i) s):real =
(&(lowdigits lo i) +
&(bitval(2 * p63 < n)) * &(lowdigits n i)) -
&2 pow (64 * i) * &(bitval(read CF s)))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
RULE_ASSUM_TAC(REWRITE_RULE[VAL_WORD_SUB_EQ_0]) THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (3--5) THEN
ENSURES_FINAL_STATE_TAC THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; BITVAL_CLAUSES] THEN
REWRITE_TAC[REAL_MUL_RZERO; REAL_SUB_REFL; REAL_ADD_LID] THEN
DISCH_TAC THEN REWRITE_TAC[WORD_RULE
`word_sub a b = word_neg c <=> word_add c a = b`] THEN
MP_TAC(GEN `x:int64` (ISPEC `x:int64` WORD_USHR_MSB)) THEN
REWRITE_TAC[DIMINDEX_64] THEN CONV_TAC NUM_REDUCE_CONV THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
REWRITE_TAC[GSYM VAL_EQ; VAL_WORD_BITVAL; VAL_WORD_ADD_CASES] THEN
SIMP_TAC[DIMINDEX_64; BITVAL_BOUND; ARITH_RULE
`b <= 1 /\ c <= 1 ==> b + c < 2 EXP 64`] THEN
SUBGOAL_THEN `2 * p63 < 2 * n /\ 2 * p63 < 2 * 2 EXP (64 * k)`
MP_TAC THENL
[ASM_REWRITE_TAC[LT_MULT_LCANCEL; ARITH_EQ]; ALL_TAC] THEN
SUBGOAL_THEN
`2 * p63 = 2 EXP (64 * k) *
bitval(bit 63 (word(bigdigit p63 (k - 1)):int64)) +
lowdigits (2 * p63) k`
SUBST1_TAC THENL
[MP_TAC(SPECL [`2 * p63`; `k:num`] (CONJUNCT1 HIGH_LOW_DIGITS)) THEN
DISCH_THEN(fun th -> GEN_REWRITE_TAC LAND_CONV [SYM th]) THEN
AP_THM_TAC THEN AP_TERM_TAC THEN AP_TERM_TAC THEN
MP_TAC(ISPEC `word(bigdigit p63 (k - 1)):int64` WORD_USHR_MSB) THEN
REWRITE_TAC[DIMINDEX_64] THEN CONV_TAC NUM_REDUCE_CONV THEN
DISCH_THEN(MP_TAC o SYM o AP_TERM `val:int64->num`) THEN
REWRITE_TAC[VAL_WORD_BITVAL; VAL_WORD_USHR] THEN
DISCH_THEN SUBST1_TAC THEN
SIMP_TAC[VAL_WORD_EQ; BIGDIGIT_BOUND; DIMINDEX_64] THEN
ASM_SIMP_TAC[highdigits; ARITH_RULE
`~(k = 0) ==> 64 * k = SUC(64 * (k - 1) + 63)`] THEN
SIMP_TAC[DIV_MULT2; EXP; ARITH_EQ] THEN
REWRITE_TAC[EXP_ADD; GSYM DIV_DIV] THEN
AP_THM_TAC THEN AP_TERM_TAC THEN
REWRITE_TAC[bigdigit] THEN CONV_TAC SYM_CONV THEN
MATCH_MP_TAC MOD_LT THEN
ASM_SIMP_TAC[RDIV_LT_EQ; EXP_EQ_0; ARITH_EQ; GSYM EXP_ADD] THEN
ASM_SIMP_TAC[ARITH_RULE `~(k = 0) ==> 64 * (k - 1) + 64 = 64 * k`];
ALL_TAC] THEN
ASM_CASES_TAC `bit 63 (word(bigdigit p63 (k - 1)):int64)` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THENL
[ASM_SIMP_TAC[ARITH_RULE `n:num < e ==> ~(e + a < n)`] THEN
UNDISCH_TAC
`&lo:real =
&2 pow (64 * k) * &(bitval(~hi)) +
&(lowdigits (2 * p63) k) - &n` THEN
UNDISCH_TAC `lo < 2 EXP (64 * k)` THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
BOOL_CASES_TAC `hi:bool` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
REAL_ARITH_TAC;
STRIP_TAC THEN AP_TERM_TAC THEN
REWRITE_TAC[NOT_LT; TAUT `(p <=> ~q) <=> (~p <=> q)`] THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN
EXISTS_TAC `64 * k` THEN REWRITE_TAC[GSYM REAL_BITVAL_NOT] THEN
UNDISCH_THEN
`&lo:real =
&2 pow (64 * k) * &(bitval(~hi)) + &(lowdigits (2 * p63) k) - &n`
(SUBST1_TAC o SYM) THEN
ASM_REWRITE_TAC[REAL_OF_NUM_CLAUSES; LE_0]];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hi:int64` `read X9` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--7) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MATCH_MP th)) THEN
ASSUME_TAC th) THEN
ASM_REWRITE_TAC[LOWDIGITS_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[WORD_ADD; WORD_NEG_NEG; VAL_WORD_BITVAL; WORD_BITVAL_EQ_0;
LOWDIGITS_CLAUSES; WORD_NEG_EQ_0; BITVAL_BOUND; NOT_LT] THEN
REWRITE_TAC[WORD_AND_MASK] THEN COND_CASES_TAC THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN ASM_REWRITE_TAC[NOT_LT] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND; VAL_WORD_0;
BITVAL_CLAUSES; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
REWRITE_TAC[REAL_POW_ADD] THEN CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF; HIGHDIGITS_ZERO; SUB_REFL] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL]] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MP th)) THEN
ASSUME_TAC(CONJUNCT2 th) THEN MP_TAC(CONJUNCT1 th)) THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MP th)) THEN
ASSUME_TAC th) THEN
SUBGOAL_THEN `2 EXP (64 * k + 64) MOD n =
(2 * 2 EXP (64 * k + 63) MOD n) MOD n`
SUBST1_TAC THENL
[REWRITE_TAC[ARITH_RULE `n + 64 = SUC(n + 63)`; EXP] THEN
CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
SUBGOAL_THEN `p63:num < n`
(fun th -> FIRST_X_ASSUM(MP_TAC o C MP th) THEN ASSUME_TAC th)
THENL
[ASM_REWRITE_TAC[MOD_LT_EQ] THEN
UNDISCH_TAC `2 EXP (64 * k - 1) <= n` THEN
SIMP_TAC[GSYM NOT_LT; CONTRAPOS_THM; EXP_LT_0] THEN ARITH_TAC;
UNDISCH_THEN `p63 = 2 EXP (64 * k + 63) MOD n` (SUBST1_TAC o SYM)] THEN
STRIP_TAC THEN
ASM_SIMP_TAC[MOD_ADD_CASES; MULT_2; ARITH_RULE
`p63 < n ==> p63 + p63 < 2 * n`] THEN
REWRITE_TAC[GSYM MULT_2] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
MATCH_MP_TAC(MESON[] `x = y /\ x = a ==> x = a /\ y = a`) THEN
CONJ_TAC THENL [ASM_REWRITE_TAC[]; ALL_TAC] THEN
MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN
MAP_EVERY EXISTS_TAC [`64 * k`; `&0:real`] THEN CONJ_TAC THENL
[REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; REAL_OF_NUM_CLAUSES] THEN
REWRITE_TAC[LE_0; BIGNUM_FROM_MEMORY_BOUND];
ALL_TAC] THEN
CONJ_TAC THENL
[MAP_EVERY UNDISCH_TAC [`p63:num < n`; `n < 2 EXP (64 * k)`] THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN ARITH_TAC;
REWRITE_TAC[INTEGER_CLOSED]] THEN
ASM_REWRITE_TAC[] THEN REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
COND_CASES_TAC THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
ASM_SIMP_TAC[GSYM REAL_OF_NUM_SUB; GSYM NOT_LT] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
REWRITE_TAC[ONCE_REWRITE_RULE[REAL_MUL_SYM] real_div] THEN
REWRITE_TAC[REAL_ADD_LDISTRIB; REAL_SUB_LDISTRIB; REAL_MUL_ASSOC] THEN
REWRITE_TAC[REAL_FIELD `inv(&2 pow n) * &2 pow n = (&1:real)`] THEN
CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN
REWRITE_TAC[REAL_ARITH
`--(&2) * e * a + e * b + c:real = e * (b - &2 * a) + c`] THEN
MATCH_MP_TAC INTEGER_ADD THEN
(CONJ_TAC THENL [ALL_TAC; REAL_INTEGER_TAC]) THEN
REWRITE_TAC[REAL_ARITH `inv x * (a - b):real = (a - b) / x`] THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
W(MP_TAC o PART_MATCH (rand o rand) REAL_CONGRUENCE o snd) THEN
REWRITE_TAC[EXP_EQ_0; ARITH_EQ] THEN DISCH_THEN(SUBST1_TAC o SYM) THEN
REWRITE_TAC[CONG; lowdigits] THEN CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
(*** A bit of cleanup ***)
REPEAT(FIRST_X_ASSUM(K ALL_TAC o check (free_in `h:num` o concl))) THEN
REPEAT(FIRST_X_ASSUM(K ALL_TAC o check (free_in `l:num` o concl))) THEN
REWRITE_TAC[TAUT `p ==> q /\ r <=> (p ==> q) /\ (p ==> r)`] THEN
GHOST_INTRO_TAC `r:num` `bignum_from_memory (z,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `r:num` THEN GLOBALIZE_PRECONDITION_TAC THEN
(*** Now the main loop "modloop" ***)
ENSURES_WHILE_PUP_TAC `k:num` `pc + 0x1f0` `pc + 0x25c`
`\i s. (read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X4 s = word(k - i) /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (z,k) s = r /\
(ODD m ==> (2 EXP (64 * k) * val(read X6 s) +
bignum_from_memory(t,k) s ==
2 EXP (64 * (k + i + 1))) (mod m))) /\
(read ZF s <=> i = k)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; ADD_CLAUSES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[VAL_WORD_0; ADD_CLAUSES; MULT_CLAUSES] THEN
ASM_CASES_TAC `m = 1` THEN ASM_SIMP_TAC[CONG_MOD_1; MULT_CLAUSES] THEN
DISCH_TAC THEN MATCH_MP_TAC(NUMBER_RULE
`!m:num. (a == b) (mod n) /\ m divides n ==> (a == b) (mod m)`) THEN
ASM_REWRITE_TAC[LEFT_ADD_DISTRIB; MULT_CLAUSES; CONG_LMOD; CONG_REFL];
(*** The main loop invariant of "modloop" ***)
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `h:num` `\s. val(read X6 s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GHOST_INTRO_TAC `t1:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `t1:num` THEN GLOBALIZE_PRECONDITION_TAC THEN
(*** The inner multiply-add loop "cmaloop" ***)
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x1fc` `pc + 0x220`
`\j s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X4 s = word (k - i) /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (z,k) s = r /\
read X6 s = word h /\
read X5 s = word j /\
bignum_from_memory (word_add z (word(8 * j)),k - j) s =
highdigits r j /\
bignum_from_memory (word_add t (word(8 * j)),k - j) s =
highdigits t1 j /\
read X10 s = word(bigdigit (2 EXP 64 * t1) j) /\
2 EXP (64 * j) * (bitval(read CF s) + val(read X9 s)) +
bignum_from_memory(t,j) s =
lowdigits (2 EXP 64 * t1) j + h * lowdigits r j` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--3) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; LOWDIGITS_0] THEN
REWRITE_TAC[MULT_CLAUSES; SUB_0; BITVAL_CLAUSES; VAL_WORD_0] THEN
REWRITE_TAC[WORD_ADD_0; BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; HIGHDIGITS_0] THEN
REWRITE_TAC[ADD_CLAUSES; MULT_CLAUSES] THEN AP_TERM_TAC THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES; MOD_MULT];
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read X9` THEN
GHOST_INTRO_TAC `prd:int64` `read X10` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - j - 1 = k - (j + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [2;3;5;6] (1--9) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REPEAT CONJ_TAC THENL
[CONV_TAC WORD_RULE;
AP_TERM_TAC THEN REWRITE_TAC[bigdigit] THEN
REWRITE_TAC[ARITH_RULE `64 * (j + 1) = 64 + 64 * j`] THEN
SIMP_TAC[EXP_ADD; DIV_MULT2; EXP_EQ_0; ARITH_EQ];
REWRITE_TAC[LOWDIGITS_CLAUSES]] THEN
GEN_REWRITE_TAC RAND_CONV
[ARITH_RULE `(e * d1 + d0) + c * (e * a1 + a0):num =
e * (c * a1 + d1) + d0 + c * a0`] THEN
FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [SYM th]) THEN
REWRITE_TAC[EXP_ADD; ARITH_RULE `64 * (j + 1) = 64 * j + 64`] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
GEN_REWRITE_TAC LAND_CONV
[TAUT `p /\ q /\ r /\ s <=> p /\ r /\ q /\ s`] THEN
DISCH_THEN(MP_TAC o end_itlist CONJ o DECARRY_RULE o CONJUNCTS) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN CONV_TAC REAL_RING;
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF]] THEN
(*** Additional absorption of the top digit before correction ***)
ENSURES_SEQUENCE_TAC `pc + 0x22c`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X4 s = word (k - i) /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (z,k) s = r /\
2 EXP (64 * k) * (2 EXP 64 * bitval(read CF s) + val(read X6 s)) +
bignum_from_memory(t,k) s =
2 EXP 64 * t1 + h * r` THEN
CONJ_TAC THENL
[GHOST_INTRO_TAC `hup:int64` `read X9` THEN
GHOST_INTRO_TAC `cup:bool` `read CF` THEN
GHOST_INTRO_TAC `tup:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `tup:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
RULE_ASSUM_TAC(REWRITE_RULE[VAL_WORD_SUB_EQ_0]) THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [3] [3] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN DISCH_THEN SUBST1_TAC THEN
ASM_REWRITE_TAC[ARITH_RULE
`e * (a + b + c) + d:num = e * a + e * (c + b) + d`] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[ADD_ASSOC; EQ_ADD_RCANCEL] THEN
REWRITE_TAC[GSYM(CONJUNCT2 LOWDIGITS_CLAUSES)] THEN
MATCH_MP_TAC LOWDIGITS_SELF THEN
REWRITE_TAC[EXP_ADD; ARITH_RULE `64 * (j + 1) = 64 + 64 * j`] THEN
ASM_REWRITE_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ];
GHOST_INTRO_TAC `hup:int64` `read X6` THEN
GHOST_INTRO_TAC `cup:bool` `read CF` THEN
GHOST_INTRO_TAC `tup:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `tup:num` THEN
GLOBALIZE_PRECONDITION_TAC] THEN
(**** The optional addition loop "oaloop" fixing things up ***)
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x234` `pc + 0x24c`
`\j s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X4 s = word (k - i) /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (z,k) s = r /\
read X6 s = hup /\
read X8 s = word_neg(word(bitval cup)) /\
read X5 s = word j /\
bignum_from_memory (word_add z (word(8 * j)),k - j) s =
highdigits r j /\
bignum_from_memory (word_add t (word(8 * j)),k - j) s =
highdigits tup j /\
2 EXP (64 * j) * bitval(read CF s) + bignum_from_memory(t,j) s =
lowdigits tup j + bitval(cup) * lowdigits r j` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; LOWDIGITS_0] THEN
REWRITE_TAC[MULT_CLAUSES; SUB_0; BITVAL_CLAUSES; VAL_WORD_0] THEN
REWRITE_TAC[WORD_ADD_0; BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; HIGHDIGITS_0] THEN
REWRITE_TAC[COND_SWAP] THEN COND_CASES_TAC THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC WORD_REDUCE_CONV;
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - j - 1 = k - (j + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
REWRITE_TAC[REAL_ARITH
`&2 pow k * c + z:real = w <=> z = w - &2 pow k * c`] THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; LOWDIGITS_CLAUSES] THEN
REWRITE_TAC[ARITH_RULE `64 * (j + 1) = 64 * j + 64`; REAL_POW_ADD] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
REWRITE_TAC[WORD_AND_MASK] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[VAL_WORD_0; BITVAL_CLAUSES] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
CONV_TAC REAL_RING;
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF]] THEN
(*** The final case analysis and conclusion ***)
GHOST_INTRO_TAC `topc:bool` `read CF` THEN
GHOST_INTRO_TAC `tout:num` `bignum_from_memory(t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `tout:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
RULE_ASSUM_TAC(REWRITE_RULE[VAL_WORD_SUB_EQ_0]) THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [3] (3--4) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> r) /\ q ==> p /\ q /\ r `) THEN
REPEAT CONJ_TAC THENL
[REWRITE_TAC[ARITH_RULE `a - (i + 1) = a - i - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < k ==> 1 <= k - i`];
DISCH_THEN SUBST1_TAC THEN
W(MP_TAC o PART_MATCH (lhand o rand) VAL_WORD_EQ o
lhand o lhand o snd) THEN
REWRITE_TAC[DIMINDEX_64] THEN ANTS_TAC THENL
[ALL_TAC; DISCH_THEN SUBST1_TAC] THEN
MAP_EVERY UNDISCH_TAC [`k < 2 EXP 64`; `i:num < k`] THEN ARITH_TAC;
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MATCH_MP th)) THEN
ASSUME_TAC th)] THEN
REWRITE_TAC[ARITH_RULE
`64 * (k + (i + 1) + 1) = 64 + 64 * (k + i + 1)`] THEN
ONCE_REWRITE_TAC[EXP_ADD] THEN FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP
(NUMBER_RULE `(x:num == a) (mod m)
==> (e * x == y) (mod m) ==> (y == e * a) (mod m)`)) THEN
UNDISCH_TAC `ODD m /\ ~(m = 1) ==> r = 2 EXP (64 * k + 64) MOD n` THEN
ASM_CASES_TAC `m = 1` THEN ASM_REWRITE_TAC[CONG_MOD_1] THEN
DISCH_THEN(ASSUME_TAC o MATCH_MP(MESON[CONG_RMOD; CONG_REFL]
`x = y MOD n ==> (y == x) (mod n)`)) THEN
REWRITE_TAC[ARITH_RULE `e * (ee * h + t):num = e * t + (ee * e) * h`] THEN
REWRITE_TAC[GSYM EXP_ADD] THEN
FIRST_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE
`(e1:num == r) (mod n)
==> m divides n /\ (t + r * h == z) (mod m)
==> (t + e1 * h == z) (mod m)`)) THEN
ASM_REWRITE_TAC[] THEN
SUBGOAL_THEN `val(sum_s3:int64) = val(hup:int64) + bitval topc`
SUBST1_TAC THENL
[ALL_TAC;
MAP_EVERY UNDISCH_TAC
[`2 EXP (64 * k) * (2 EXP 64 * bitval cup + val(hup:int64)) + tup =
2 EXP 64 * t1 + h * r`;
`2 EXP (64 * k) * bitval topc + tout = tup + bitval cup * r`;
`(2 EXP (64 * k + 64) == r) (mod n)`; `(m:num) divides n`] THEN
REWRITE_TAC[EXP_ADD] THEN SPEC_TAC(`2 EXP (64 * k)`,`ee:num`) THEN
SPEC_TAC(`2 EXP 64`,`e:num`) THEN
BOOL_CASES_TAC `cup:bool` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
CONV_TAC NUMBER_RULE] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN MATCH_MP_TAC(ARITH_RULE
`(e * c < e * 1 ==> e * c = 0) /\ z < e
==> e * c + s:num = z ==> s = z`) THEN
REWRITE_TAC[LT_MULT_LCANCEL; MULT_EQ_0; EXP_EQ_0; ARITH_EQ] THEN
REWRITE_TAC[ARITH_RULE `b < 1 ==> b = 0`] THEN
SUBGOAL_THEN `2 EXP (64 * k) * (val(hup:int64) + bitval topc) <
2 EXP (64 * k) * 2 EXP 64`
MP_TAC THENL
[ALL_TAC; REWRITE_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ]] THEN
MAP_EVERY UNDISCH_TAC
[`2 EXP (64 * k) * (2 EXP 64 * bitval cup + val(hup:int64)) + tup =
2 EXP 64 * t1 + h * r`;
`2 EXP (64 * k) * bitval topc + tout = tup + bitval cup * r`] THEN
ASM_CASES_TAC `cup:bool` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THENL
[SUBGOAL_THEN `2 EXP 64 * t1 < 2 EXP 64 * 2 EXP (64 * k) /\
(h + 1) * r <= 2 EXP 64 * 2 EXP (64 * k)`
MP_TAC THENL [ALL_TAC; ARITH_TAC] THEN
ASM_REWRITE_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ] THEN
MATCH_MP_TAC LE_MULT2 THEN
ASM_SIMP_TAC[LT_IMP_LE; ARITH_RULE `x + 1 <= y <=> x < y`];
ALL_TAC] THEN
ASM_CASES_TAC `topc:bool` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THENL
[MAP_EVERY UNDISCH_TAC
[`tout < 2 EXP (64 * k)`; `tup < 2 EXP (64 * k)`] THEN
ARITH_TAC;
SIMP_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ; VAL_BOUND_64]];
(*** Trivial loop-back ***)
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[] THEN ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC [1];
ALL_TAC] THEN
* * Initial word modular inverse of tail * *
ENSURES_SEQUENCE_TAC `pc + 0x294`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X7 s = word(bigdigit m 0) /\
bignum_from_memory (mm,k) s = m /\
(ODD m
==> (2 EXP (64 * k) * val (read X6 s) +
bignum_from_memory (t,k) s ==
2 EXP (64 * (2 * k + 1))) (mod m)) /\
(ODD m ==> (m * val(read X11 s) + 1 == 0) (mod (2 EXP 64)))` THEN
CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC [1] THEN
SUBGOAL_THEN `bignum_from_memory(mm,k) s1 = highdigits m 0` MP_TAC THENL
[ASM_REWRITE_TAC[HIGHDIGITS_0; BIGNUM_FROM_MEMORY_BYTES];
GEN_REWRITE_TAC LAND_CONV[BIGNUM_FROM_MEMORY_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; ADD_CLAUSES] THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
REWRITE_TAC[GSYM DIMINDEX_64; WORD_MOD_SIZE] THEN
REWRITE_TAC[DIMINDEX_64] THEN STRIP_TAC] THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (2--5) THEN
SUBGOAL_THEN `ODD m ==> (m * val (read X11 s5) + 1 == 0) (mod 16)`
MP_TAC THENL [ASM_SIMP_TAC[WORD_NEGMODINV_SEED_LEMMA_16]; ALL_TAC] THEN
REABBREV_TAC `x0 = read X11 s5` THEN DISCH_TAC THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (6--14) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_REWRITE_TAC[ARITH_RULE `2 * k + 1 = k + k + 1`] THEN
REWRITE_TAC[VAL_WORD_MUL; VAL_WORD_ADD; VAL_WORD; DIMINDEX_64; CONG] THEN
CONV_TAC MOD_DOWN_CONV THEN REWRITE_TAC[GSYM CONG] THEN
SUBST1_TAC(ARITH_RULE `2 EXP 64 = 16 EXP (2 EXP 4)`) THEN
DISCH_TAC THEN UNDISCH_TAC
`ODD m ==> (m * val(x0:int64) + 1 == 0) (mod 16)` THEN
ASM_REWRITE_TAC[] THEN
SPEC_TAC(`16`,`e:num`) THEN CONV_TAC NUM_REDUCE_CONV THEN
CONV_TAC NUMBER_RULE;
GHOST_INTRO_TAC `w:num` `\s. val(read X11 s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64]] THEN
* * More cleanup and setup of Montgomery multiplier * *
REPEAT(FIRST_X_ASSUM(K ALL_TAC o check (free_in `n:num` o concl))) THEN
GHOST_INTRO_TAC `h:num` `\s. val(read X6 s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GHOST_INTRO_TAC `z1:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `z1:num` THEN
GLOBALIZE_PRECONDITION_TAC THEN
ABBREV_TAC `q0 = (w * z1) MOD 2 EXP 64` THEN
SUBGOAL_THEN `q0 < 2 EXP 64 /\ val(word q0:int64) = q0`
STRIP_ASSUME_TAC THENL
[EXPAND_TAC "q0" THEN CONJ_TAC THENL [ARITH_TAC; ALL_TAC] THEN
REWRITE_TAC[VAL_WORD; DIMINDEX_64; MOD_MOD_REFL];
ALL_TAC] THEN
* * The prelude of the reduction * *
ENSURES_SEQUENCE_TAC `pc + 0x2b0`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = z1 /\
read X6 s = word h /\
read X11 s = word q0 /\
read X5 s = word 1 /\
read X7 s = word(k - 1) /\
?r0. r0 < 2 EXP 64 /\
2 EXP 64 * (bitval(read CF s) + val(read X9 s)) + r0 =
q0 * bigdigit m 0 + bigdigit z1 0` THEN
CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
SUBGOAL_THEN
`bignum_from_memory(mm,k) s0 = highdigits m 0 /\
bignum_from_memory(t,k) s0 = highdigits z1 0`
MP_TAC THENL
[ASM_REWRITE_TAC[HIGHDIGITS_0; BIGNUM_FROM_MEMORY_BYTES];
GEN_REWRITE_TAC (LAND_CONV o BINOP_CONV)
[BIGNUM_FROM_MEMORY_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; ADD_CLAUSES] THEN
STRIP_TAC] THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [3; 7] (1--7) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[UNDISCH_THEN `(w * z1) MOD 2 EXP 64 = q0` (SUBST1_TAC o SYM) THEN
ONCE_REWRITE_TAC[GSYM WORD_MOD_SIZE] THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
REWRITE_TAC[ADD_CLAUSES; DIMINDEX_64; VAL_WORD] THEN
CONV_TAC MOD_DOWN_CONV THEN REWRITE_TAC[MULT_SYM];
DISCH_THEN SUBST_ALL_TAC] THEN
ASM_REWRITE_TAC[WORD_SUB; ARITH_RULE `1 <= k <=> ~(k = 0)`] THEN
EXISTS_TAC `val(sum_s7:int64)` THEN REWRITE_TAC[VAL_BOUND_64] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REAL_ARITH_TAC;
ALL_TAC] THEN
(*** Break at "montend" to share the end reasoning ***)
GHOST_INTRO_TAC `carin:bool` `read CF` THEN
GHOST_INTRO_TAC `mulin:int64` `read X9` THEN
GLOBALIZE_PRECONDITION_TAC THEN
FIRST_X_ASSUM(X_CHOOSE_THEN `r0:num` STRIP_ASSUME_TAC) THEN
ENSURES_SEQUENCE_TAC `pc + 0x2e4`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
read X6 s = word h /\
read X11 s = word q0 /\
2 EXP (64 * k) * (bitval(read CF s) + val(read X9 s)) +
2 EXP 64 * bignum_from_memory (t,k - 1) s + r0 =
lowdigits z1 k + q0 * lowdigits m k` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `k = 1` THENL
[UNDISCH_THEN `k = 1` SUBST_ALL_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC [1] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[SUB_REFL; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES] THEN
REWRITE_TAC[LOWDIGITS_1] THEN ARITH_TAC;
ALL_TAC] THEN
* * The reduction loop " montloop " * *
VAL_INT64_TAC `k - 1` THEN
ENSURES_WHILE_AUP_TAC `1` `k:num` `pc + 0x2b4` `pc + 0x2dc`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
read X6 s = word h /\
read X11 s = word q0 /\
read X5 s = word i /\
bignum_from_memory(word_add t (word (8 * i)),k - i) s =
highdigits z1 i /\
bignum_from_memory(word_add mm (word (8 * i)),k - i) s =
highdigits m i /\
2 EXP (64 * i) * (bitval(read CF s) + val(read X9 s)) +
2 EXP 64 * bignum_from_memory(t,i-1) s + r0 =
lowdigits z1 i + q0 * lowdigits m i` THEN
REPEAT CONJ_TAC THENL
[ASM_REWRITE_TAC[ARITH_RULE `1 < k <=> ~(k = 0 \/ k = 1)`];
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC [1] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
ASM_REWRITE_TAC[ARITH_RULE `k <= 1 <=> k = 0 \/ k = 1`] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_DIV; BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[GSYM highdigits; BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; LOWDIGITS_1] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN
MAP_EVERY VAL_INT64_TAC [`i:num`; `i - 1`] THEN
SUBGOAL_THEN `word_sub (word i) (word 1):int64 = word(i - 1)`
ASSUME_TAC THENL [ASM_REWRITE_TAC[WORD_SUB]; ALL_TAC] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read X9` THEN
MP_TAC(GENL [`x:int64`; `a:num`]
(ISPECL [`x:int64`; `k - i:num`; `a:num`; `i:num`]
BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS)) THEN
ASM_REWRITE_TAC[ARITH_RULE `k - i = 0 <=> ~(i < k)`] THEN
DISCH_THEN(fun th -> ONCE_REWRITE_TAC[th]) THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
UNDISCH_THEN `val(word q0:int64) = q0` (K ALL_TAC) THEN
ABBREV_TAC `i' = i - 1` THEN
SUBGOAL_THEN `i = i' + 1` SUBST_ALL_TAC THENL
[EXPAND_TAC "i'" THEN UNDISCH_TAC `1 <= i` THEN ARITH_TAC;
ALL_TAC] THEN
RULE_ASSUM_TAC(REWRITE_RULE[ARITH_RULE `(i' + 1) + 1 = i' + 2`]) THEN
REWRITE_TAC[ARITH_RULE `(i' + 1) + 1 = i' + 2`] THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [3;4;6;7] (1--10) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
REWRITE_TAC[ARITH_RULE `(m + 2) - 1 = m + 1`] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
SUBGOAL_THEN `i' + 2 = (i' + 1) + 1` MP_TAC THENL
[ARITH_TAC; DISCH_THEN SUBST_ALL_TAC] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ONCE_REWRITE_TAC[LOWDIGITS_CLAUSES] THEN
GEN_REWRITE_TAC RAND_CONV
[ARITH_RULE `(e * d1 + d0) + c * (e * a1 + a0):num =
e * (c * a1 + d1) + d0 + c * a0`] THEN
FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [SYM th]) THEN
REWRITE_TAC[EXP_ADD; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
GEN_REWRITE_TAC LAND_CONV
[TAUT `p /\ q /\ r /\ s <=> p /\ r /\ q /\ s`] THEN
DISCH_THEN(MP_TAC o end_itlist CONJ o DECARRY_RULE o CONJUNCTS) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN
MAP_EVERY VAL_INT64_TAC [`i:num`; `i - 1`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0]];
ASM_SIMP_TAC[LOWDIGITS_SELF]] THEN
(*** The final digit write ****)
ENSURES_SEQUENCE_TAC `pc + 0x2f4`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
?c. read X8 s = word_neg(word(bitval c)) /\
2 EXP 64 * (2 EXP (64 * k) * bitval c +
bignum_from_memory(t,k) s) + r0 =
(2 EXP (64 * k) * h + z1) + q0 * m` THEN
CONJ_TAC THENL
[GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read X9` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
VAL_INT64_TAC `k - 1` THEN
SUBGOAL_THEN `word_sub (word k) (word 1):int64 = word(k - 1)`
ASSUME_TAC THENL
[ASM_REWRITE_TAC[WORD_SUB; ARITH_RULE `1 <= k <=> ~(k = 0)`];
ALL_TAC] THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [1] (1--4) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
EXISTS_TAC `carry_s1:bool` THEN CONJ_TAC THENL
[REWRITE_TAC[COND_SWAP] THEN COND_CASES_TAC THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC WORD_REDUCE_CONV;
ALL_TAC] THEN
SUBGOAL_THEN `8 * k = 8 * ((k - 1) + 1)` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC;
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES]] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[GSYM ADD_ASSOC] THEN FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [SYM th]) THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
SUBGOAL_THEN `64 * k = 64 * (k - 1) + 64` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC; REWRITE_TAC[REAL_POW_ADD]] THEN
CONV_TAC REAL_RING;
ALL_TAC] THEN
(*** The final correction to keep inside k digits, "osloop" ***)
GHOST_INTRO_TAC `z2:num` `bignum_from_memory(t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `z2:num` THEN
GHOST_INTRO_TAC `g8:int64` `read X8` THEN
GLOBALIZE_PRECONDITION_TAC THEN
FIRST_X_ASSUM(X_CHOOSE_THEN `cf:bool`
(CONJUNCTS_THEN2 SUBST_ALL_TAC ASSUME_TAC)) THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x2f8` `pc + 0x310`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X8 s = word_neg (word (bitval cf)) /\
read X5 s = word i /\
bignum_from_memory (word_add t (word(8 * i)),k - i) s =
highdigits z2 i /\
bignum_from_memory (word_add mm (word(8 * i)),k - i) s =
highdigits m i /\
&(bignum_from_memory(z,i) s):real =
&2 pow (64 * i) * &(bitval(~read CF s)) +
&(lowdigits z2 i) - &(bitval cf) * &(lowdigits m i)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC [1] THEN
REWRITE_TAC[WORD_SUB_LZERO; SUB_0; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[WORD_ADD_0; MULT_CLAUSES; BITVAL_CLAUSES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL; LOWDIGITS_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; HIGHDIGITS_0] THEN
REAL_ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[WORD_ADD; WORD_NEG_NEG; VAL_WORD_BITVAL; WORD_BITVAL_EQ_0;
LOWDIGITS_CLAUSES; WORD_NEG_EQ_0; BITVAL_BOUND; NOT_LT] THEN
REWRITE_TAC[WORD_AND_MASK] THEN COND_CASES_TAC THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN ASM_REWRITE_TAC[NOT_LT] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND; VAL_WORD_0;
BITVAL_CLAUSES; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
REWRITE_TAC[REAL_POW_ADD] THEN CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MATCH_MP th)) THEN
ASSUME_TAC th)] THEN
(*** Finally deduce that the lowest digit is 0 by congruence reasoning ***)
UNDISCH_THEN
`2 EXP 64 * (bitval carin + val(mulin:int64)) + r0 =
q0 * bigdigit m 0 + bigdigit z1 0`
(MP_TAC o AP_TERM `\x. x MOD 2 EXP 64`) THEN
REWRITE_TAC[MOD_MULT_ADD] THEN
UNDISCH_THEN `(w * z1) MOD 2 EXP 64 = q0` (SUBST1_TAC o SYM) THEN
ASM_SIMP_TAC[MOD_LT; GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
CONV_TAC(LAND_CONV MOD_DOWN_CONV) THEN
REWRITE_TAC[ARITH_RULE `(w * z1) * m + z1 = z1 * (m * w + 1)`] THEN
ONCE_REWRITE_TAC[GSYM MOD_MULT_MOD2] THEN
UNDISCH_TAC `(m * w + 1 == 0) (mod (2 EXP 64))` THEN
GEN_REWRITE_TAC LAND_CONV [CONG] THEN DISCH_THEN SUBST1_TAC THEN
CONV_TAC(LAND_CONV MOD_DOWN_CONV) THEN
REWRITE_TAC[MULT_CLAUSES; MOD_0] THEN DISCH_THEN SUBST_ALL_TAC THEN
RULE_ASSUM_TAC(REWRITE_RULE[ADD_CLAUSES]) THEN
(*** The final congruence/range reasoning ***)
MATCH_MP_TAC CONG_MULT_LCANCEL THEN EXISTS_TAC `2 EXP 64` THEN
ASM_REWRITE_TAC[COPRIME_LEXP; COPRIME_2] THEN
REWRITE_TAC[GSYM EXP_ADD; ARITH_RULE `64 + 128 * k = 64 * (2 * k + 1)`] THEN
FIRST_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE
`(x:num == y) (mod n) ==> (z == x) (mod n) ==> (z == y) (mod n)`)) THEN
FIRST_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE
`x:num = y + q * m ==> (z == x) (mod m) ==> (z == y) (mod m)`)) THEN
MATCH_MP_TAC CONG_LMUL THEN
SUBGOAL_THEN `~(read CF s2) <=> z2 < bitval cf * m` SUBST_ALL_TAC THENL
[MATCH_MP_TAC FLAG_FROM_CARRY_LT THEN EXISTS_TAC `64 * k` THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
UNDISCH_THEN
`&(read (memory :> bytes (z,8 * k)) s2) =
&2 pow (64 * k) * &(bitval (~read CF s2)) + &z2 - &(bitval cf) * &m`
(SUBST1_TAC o SYM) THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BOUND; LE_0];
ALL_TAC] THEN
REPEAT(FIRST_X_ASSUM(MP_TAC o check (free_in `cf:bool` o concl))) THEN
REWRITE_TAC[GSYM int_of_num_th; GSYM int_pow_th; GSYM int_mul_th;
GSYM int_add_th; GSYM int_sub_th; GSYM int_eq] THEN
SIMP_TAC[num_congruent; GSYM INT_OF_NUM_CLAUSES] THEN
REWRITE_TAC[INT_OF_NUM_CLAUSES] THEN
BOOL_CASES_TAC `cf:bool` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; MULT_CLAUSES; ADD_CLAUSES; CONJUNCT1 LT] THEN
REWRITE_TAC[INT_CONG_REFL; INT_ADD_LID; INT_SUB_RZERO] THEN
ASM_CASES_TAC `z2:num < m` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; MULT_CLAUSES; ADD_CLAUSES] THENL
[REPEAT(DISCH_THEN(K ALL_TAC)) THEN
REWRITE_TAC[GSYM INT_OF_NUM_CLAUSES] THEN CONV_TAC INTEGER_RULE;
MATCH_MP_TAC(TAUT `~p ==> p ==> q`)] THEN
MATCH_MP_TAC(ARITH_RULE `b:num < a ==> ~(a = b)`) THEN
MATCH_MP_TAC(ARITH_RULE
`x + q * m < 2 EXP 64 * ee + 2 EXP 64 * m /\ ~(z2 < m)
==> x + q * m < 2 EXP 64 * (ee + z2)`) THEN
ASM_REWRITE_TAC[] THEN MATCH_MP_TAC LET_ADD2 THEN
FIRST_ASSUM(ASSUME_TAC o MATCH_MP (MESON[ODD] `ODD m ==> ~(m = 0)`)) THEN
ASM_REWRITE_TAC[LT_MULT_RCANCEL] THEN
FIRST_ASSUM(MATCH_MP_TAC o MATCH_MP (ARITH_RULE
`z1:num < ee ==> (h + 1) * ee <= b ==> ee * h + z1 <= b`)) THEN
ASM_REWRITE_TAC[LE_MULT_RCANCEL; EXP_EQ_0; ARITH_EQ] THEN
ASM_REWRITE_TAC[ARITH_RULE `a + 1 <= b <=> a < b`]);;
let BIGNUM_AMONTIFIER_SUBROUTINE_CORRECT = time prove
(`!k z m t n pc returnaddress.
nonoverlapping (z,8 * val k) (t,8 * val k) /\
ALLPAIRS nonoverlapping [(z,8 * val k); (t,8 * val k)]
[(word pc,0x31c); (m,8 * val k)]
==> ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_amontifier_mc /\
read PC s = word pc /\
read X30 s = returnaddress /\
C_ARGUMENTS [k; z; m; t] s /\
bignum_from_memory (m,val k) s = n)
(\s. read PC s = returnaddress /\
(ODD n
==> (bignum_from_memory (z,val k) s ==
2 EXP (128 * val k)) (mod n)))
(MAYCHANGE [PC; X4; X5; X6; X7; X8; X9; X10; X11] ,,
MAYCHANGE [memory :> bytes(z,8 * val k);
memory :> bytes(t,8 * val k)] ,,
MAYCHANGE SOME_FLAGS)`,
ARM_ADD_RETURN_NOSTACK_TAC
BIGNUM_AMONTIFIER_EXEC BIGNUM_AMONTIFIER_CORRECT);;
| null | https://raw.githubusercontent.com/awslabs/s2n-bignum/824c15f908d7a343af1b2f378cfedd36e880bdde/arm/proofs/bignum_amontifier.ml | ocaml | =========================================================================
Almost-Montgomerifier computation.
=========================================================================
*** print_literal_from_elf "arm/generic/bignum_amontifier.o";;
***
arm_CSEL X9 X9 X7 Condition_EQ
arm_CLZ X9 X9
arm_CSETM X7 Condition_CS
arm_CBNZ X7 (word 2097112)
arm_CSETM X8 Condition_CS
arm_LDR X7 X2 (Immediate_Offset (word 0))
arm_MUL X11 X10 X11
arm_CSETM X8 Condition_CS
-------------------------------------------------------------------------
Proof.
-------------------------------------------------------------------------
** Copied from bignum_shl_small proof, similar logic to bitloop **
** This is for the rather specific remainder computation below **
** Degenerate k = 0 case **
** Get a basic bound on k from the nonoverlapping assumptions **
** Initial copying into temporary buffer, "copyinloop" **
** The digitwise normalization "normloop" **
** Do the main loop invariant below **
** Nested loop "shufloop" **
** Inner loop invariant below **
** Bitwise stage of normalization **
** The "bitloop" loop **
** Introduce the multiple n, and abbreviations for high and low parts **
*** The somewhat stupid quotient loop **
** The "mulloop" doing q * n **
** The "remloop" producing remainder by sign-correction **
** A bit of cleanup **
** Now the main loop "modloop" **
** The main loop invariant of "modloop" **
** The inner multiply-add loop "cmaloop" **
** Additional absorption of the top digit before correction **
*** The optional addition loop "oaloop" fixing things up **
** The final case analysis and conclusion **
** Trivial loop-back **
** Break at "montend" to share the end reasoning **
** The final digit write ***
** The final correction to keep inside k digits, "osloop" **
** Finally deduce that the lowest digit is 0 by congruence reasoning **
** The final congruence/range reasoning ** |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
let bignum_amontifier_mc =
define_assert_from_elf "bignum_amontifier_mc" "arm/generic/bignum_amontifier.o"
[
arm_CBZ X0 ( word 792 )
arm_MOV X4 XZR
arm_LDR X9 X2 ( Shiftreg_Offset X4 3 )
arm_STR ( Shiftreg_Offset X4 3 )
arm_ADD X4 X4 ( rvalue ( word 1 ) )
arm_CMP
arm_BCC ( word 2097136 )
arm_SUBS ( rvalue ( word 1 ) )
arm_BEQ ( word 52 )
arm_MOV X5 XZR
arm_CMP X9 XZR
arm_MOV X7 XZR
arm_MOV X9 X7
arm_LDR X7 X3 ( Shiftreg_Offset X5 3 )
arm_STR ( Shiftreg_Offset X5 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X11 X5 X0
arm_CBNZ X11 ( word 2097128 )
arm_SUBS X4 X4 ( rvalue ( word 1 ) )
arm_BNE ( word 2097108 )
arm_MOV X10 XZR
arm_MOV X4 XZR
arm_TST X9 ( rvalue ( word 63 ) )
arm_CSETM X8 Condition_NE
arm_NEG X11 X9
arm_LDR X5 X3 ( Shiftreg_Offset X4 3 )
arm_LSL X7 X5 X9
arm_ORR X7 X7 X10
arm_LSR X10 X5 X11
arm_AND X10 X10 X8
arm_STR X7 X3 ( Shiftreg_Offset X4 3 )
arm_ADD X4 X4 ( rvalue ( word 1 ) )
arm_CMP
arm_BCC ( word 2097120 )
arm_SUB X6 X0 ( rvalue ( word 1 ) )
arm_LDR X6 X3 ( Shiftreg_Offset X6 3 )
arm_MOV X11 ( rvalue ( word 1 ) )
arm_NEG X10 X6
arm_MOV X4 ( rvalue ( word 62 ) )
arm_ADD X11 X11 X11
arm_MOV X7 X6
arm_SUB X7 X7 X10
arm_CMP X10 X7
arm_SUB X11 X11 X7
arm_ADD X10 X10 X10
arm_AND X7 X7 X6
arm_SUB X10 X10 X7
arm_SUBS X4 X4 ( rvalue ( word 1 ) )
arm_BNE ( word 2097112 )
arm_CMP X10 X6
arm_CSINC X11 X11 X11 Condition_NE
arm_MOV X9 XZR
arm_ADDS X4 XZR XZR
arm_LDR X7 X3 ( Shiftreg_Offset X4 3 )
arm_MUL X8 X11 X7
arm_ADCS X8 X8 X9
arm_UMULH X9 X11 X7
arm_STR X8 X1 ( Shiftreg_Offset X4 3 )
arm_ADD X4 X4 ( rvalue ( word 1 ) )
arm_SUB X7 X4 X0
arm_CBNZ X7 ( word 2097124 )
arm_ADC XZR
arm_MOVZ X7 ( word 16384 ) 48
arm_SUBS X9 X9 X7
arm_CSETM X11
arm_NEGS X4 XZR
arm_LDR X7 X3 ( Shiftreg_Offset X4 3 )
arm_LDR X10 X1 ( Shiftreg_Offset X4 3 )
arm_AND X7 X7 X11
arm_SBCS X7 X7 X10
arm_STR X7 X1 ( Shiftreg_Offset X4 3 )
arm_ADD X4 X4 ( rvalue ( word 1 ) )
arm_SUB X7 X4 X0
arm_CBNZ X7 ( word 2097124 )
arm_MOV X9 XZR
arm_NEGS X5 XZR
arm_LDR X7 X1 ( Shiftreg_Offset X5 3 )
arm_EXTR X9 X7 X9 ( rvalue ( word 63 ) )
arm_LDR X10 X3 ( Shiftreg_Offset X5 3 )
arm_SBCS X9 X9 X10
arm_STR X9 X1 ( Shiftreg_Offset X5 3 )
arm_MOV X9 X7
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097120 )
arm_LSR ( rvalue ( word 63 ) )
arm_SBC XZR
arm_ADDS X5 XZR XZR
arm_LDR X7 X1 ( Shiftreg_Offset X5 3 )
arm_LDR X10 X3 ( Shiftreg_Offset X5 3 )
arm_AND X10 X10 X9
arm_ADCS X7 X7 X10
arm_STR X7 X1 ( Shiftreg_Offset X5 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097124 )
arm_MOV X9 XZR
arm_NEGS X5 XZR
arm_LDR X7 X1 ( Shiftreg_Offset X5 3 )
arm_EXTR X9 X7 X9 ( rvalue ( word 63 ) )
arm_LDR X10 X3 ( Shiftreg_Offset X5 3 )
arm_SBCS X9 X9 X10
arm_STR X9 X1 ( Shiftreg_Offset X5 3 )
arm_MOV X9 X7
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097120 )
arm_LSR ( rvalue ( word 63 ) )
arm_SBC XZR
arm_ADDS X5 XZR XZR
arm_LDR X7 X1 ( Shiftreg_Offset X5 3 )
arm_LDR X10 X3 ( Shiftreg_Offset X5 3 )
arm_AND X10 X10 X9
arm_ADCS X7 X7 X10
arm_STR X7 X1 ( Shiftreg_Offset X5 3 )
arm_STR X7 X3 ( Shiftreg_Offset X5 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097120 )
arm_MOV X6 XZR
arm_MOV
arm_MOV X5 XZR
arm_MOV X10 XZR
arm_ADDS X9 XZR XZR
arm_LDR X7 X1 ( Shiftreg_Offset X5 3 )
arm_MUL X8 X6 X7
arm_ADCS X10 X10 X9
arm_UMULH X9 X6 X7
arm_ADC XZR
arm_ADDS X8 X10 X8
arm_LDR X10 X3 ( Shiftreg_Offset X5 3 )
arm_STR X8 X3 ( Shiftreg_Offset X5 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_ADCS X6 X10 X9
arm_ADDS X5 XZR XZR
arm_LDR X7 X3 ( Shiftreg_Offset X5 3 )
arm_LDR X10 X1 ( Shiftreg_Offset X5 3 )
arm_AND X10 X10 X8
arm_ADCS X7 X7 X10
arm_STR X7 X3 ( Shiftreg_Offset X5 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097124 )
arm_ADC X6 X6 XZR
arm_SUBS X4 X4 ( rvalue ( word 1 ) )
arm_BNE ( word 2097044 )
arm_LSL X11 X7 ( rvalue ( word 2 ) )
arm_SUB X11 X7 X11
arm_EOR X11 X11 ( rvalue ( word 2 ) )
arm_MOV X8 ( rvalue ( word 1 ) )
arm_MADD X9 X7 X11 X8
arm_MUL X10
arm_MADD X11 X9 X11 X11
arm_MUL X9 X10 X10
arm_MADD X11 X10 X11 X11
arm_MUL X10
arm_MADD X11 X9 X11 X11
arm_MADD X11 X10 X11 X11
arm_LDR X10 X3 ( Immediate_Offset ( word 0 ) )
arm_MUL X8 X11 X7
arm_UMULH X9 X11 X7
arm_MOV X5 ( rvalue ( word 1 ) )
arm_SUB X7 X0 ( rvalue ( word 1 ) )
arm_CMN X10 X8
arm_CBZ X7 ( word 52 )
arm_LDR X7 X2 ( Shiftreg_Offset X5 3 )
arm_LDR X10 X3 ( Shiftreg_Offset X5 3 )
arm_MUL X8 X11 X7
arm_ADCS X10 X10 X9
arm_UMULH X9 X11 X7
arm_ADC XZR
arm_ADDS X10 X10 X8
arm_SUB X7 X5 ( rvalue ( word 1 ) )
arm_STR X10 X3 ( Shiftreg_Offset X7 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097108 )
arm_ADCS X6 X6 X9
arm_SUB X7 X0 ( rvalue ( word 1 ) )
arm_STR X6 X3 ( Shiftreg_Offset X7 3 )
arm_NEGS X5 XZR
arm_LDR X7 X3 ( Shiftreg_Offset X5 3 )
arm_LDR X10 X2 ( Shiftreg_Offset X5 3 )
arm_AND X10 X10 X8
arm_SBCS X7 X7 X10
arm_STR X7 X1 ( Shiftreg_Offset X5 3 )
arm_ADD X5 X5 ( rvalue ( word 1 ) )
arm_SUB X7 X5 X0
arm_CBNZ X7 ( word 2097124 )
arm_RET X30
];;
let BIGNUM_AMONTIFIER_EXEC = ARM_MK_EXEC_RULE bignum_amontifier_mc;;
* * This actually works mod 32 but if anything this is more convenient * *
let WORD_NEGMODINV_SEED_LEMMA_16 = prove
(`!a x:int64.
ODD a /\
word_xor (word_sub (word a) (word_shl (word a) 2)) (word 2) = x
==> (a * val x + 1 == 0) (mod 16)`,
REPEAT STRIP_TAC THEN REWRITE_TAC[CONG; MOD_0] THEN
TRANS_TAC EQ_TRANS
`(val(word a:int64) MOD 16 * val(x:int64) MOD 16 + 1) MOD 16` THEN
REWRITE_TAC[ARITH_RULE `16 = 2 EXP 4`] THEN CONJ_TAC THENL
[REWRITE_TAC[VAL_WORD; DIMINDEX_64; MOD_MOD_EXP_MIN] THEN
CONV_TAC NUM_REDUCE_CONV THEN CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
REWRITE_TAC[VAL_MOD; NUMSEG_LT; ARITH_EQ; ARITH]] THEN
SUBGOAL_THEN `bit 0 (word a:int64)` MP_TAC THENL
[ASM_REWRITE_TAC[BIT_LSB_WORD];
EXPAND_TAC "x" THEN POP_ASSUM_LIST(K ALL_TAC) THEN DISCH_TAC] THEN
CONV_TAC(ONCE_DEPTH_CONV EXPAND_NSUM_CONV) THEN
CONV_TAC(TOP_DEPTH_CONV BIT_WORD_CONV) THEN
MAP_EVERY ASM_CASES_TAC
[`bit 1 (word a:int64)`;`bit 2 (word a:int64)`;`bit 3 (word a:int64)`] THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC NUM_REDUCE_CONV);;
let lemma1 = prove
(`!n c. word_and (word_jushr (word n) (word_neg (word c)))
(word_neg (word (bitval (~(c MOD 64 = 0))))):int64 =
word_ushr (word n) (64 - c MOD 64)`,
REPEAT GEN_TAC THEN REWRITE_TAC[WORD_AND_MASK; COND_SWAP] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[] THENL
[CONV_TAC SYM_CONV THEN REWRITE_TAC[GSYM VAL_EQ_0; VAL_WORD_USHR] THEN
REWRITE_TAC[SUB_0] THEN MATCH_MP_TAC DIV_LT THEN REWRITE_TAC[VAL_BOUND_64];
W(MP_TAC o PART_MATCH (lhand o rand) WORD_JUSHR_NEG o lhand o snd) THEN
ASM_REWRITE_TAC[DIMINDEX_64; MOD_64_CLAUSES] THEN
DISCH_THEN MATCH_MP_TAC THEN CONV_TAC NUM_REDUCE_CONV THEN
CONV_TAC DIVIDES_CONV]);;
let remalemma = prove
(`!x n q b.
(x <= q * n <=> b) /\ ~(n divides x) /\ abs(&x - &q * &n:real) <= &n
==> &(x MOD n):real = &(bitval b) * &n + &x - &q * &n`,
REPEAT GEN_TAC THEN
REWRITE_TAC[GSYM int_of_num_th; GSYM int_sub_th; GSYM int_add_th;
GSYM int_mul_th; GSYM int_add_th; GSYM int_abs_th] THEN
REWRITE_TAC[GSYM int_le; GSYM int_eq] THEN
REWRITE_TAC[GSYM INT_OF_NUM_REM; num_divides] THEN
REWRITE_TAC[GSYM INT_OF_NUM_LE; GSYM INT_OF_NUM_MUL] THEN
ASM_CASES_TAC `b:bool` THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN
STRIP_TAC THEN MATCH_MP_TAC INT_REM_UNIQ THENL
[EXISTS_TAC `&q - &1:int`; EXISTS_TAC `&q:int`] THEN
REPLICATE_TAC 2 (CONJ_TAC THENL [ASM_INT_ARITH_TAC; ALL_TAC]) THEN
REWRITE_TAC[INT_ABS_NUM; INT_MUL_LZERO; INT_MUL_LID; INT_ADD_LID] THEN
REWRITE_TAC[INT_ARITH `n + x - qn:int < n <=> x < qn`] THEN
REWRITE_TAC[INT_ARITH `x - q * n:int < n <=> x < (q + &1) * n`] THEN
REWRITE_TAC[INT_LT_LE] THEN
(CONJ_TAC THENL [ASM_INT_ARITH_TAC; DISCH_TAC]) THEN
UNDISCH_TAC `~((&n:int) divides (&x))` THEN
ASM_REWRITE_TAC[] THEN CONV_TAC INTEGER_RULE);;
let BIGNUM_AMONTIFIER_CORRECT = time prove
(`!k z m t n pc.
nonoverlapping (z,8 * val k) (t,8 * val k) /\
ALLPAIRS nonoverlapping [(z,8 * val k); (t,8 * val k)]
[(word pc,0x31c); (m,8 * val k)]
==> ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_amontifier_mc /\
read PC s = word pc /\
C_ARGUMENTS [k; z; m; t] s /\
bignum_from_memory (m,val k) s = n)
(\s. read PC s = word(pc + 0x318) /\
(ODD n
==> (bignum_from_memory (z,val k) s ==
2 EXP (128 * val k)) (mod n)))
(MAYCHANGE [PC; X4; X5; X6; X7; X8; X9; X10; X11] ,,
MAYCHANGE [memory :> bytes(z,8 * val k);
memory :> bytes(t,8 * val k)] ,,
MAYCHANGE SOME_FLAGS)`,
W64_GEN_TAC `k:num` THEN
MAP_EVERY X_GEN_TAC
[`z:int64`; `mm:int64`; `t:int64`; `m:num`; `pc:num`] THEN
REWRITE_TAC[ALL; ALLPAIRS; NONOVERLAPPING_CLAUSES] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
BIGNUM_TERMRANGE_TAC `k:num` `m:num` THEN
ASM_CASES_TAC `k = 0` THENL
[UNDISCH_THEN `k = 0` SUBST_ALL_TAC THEN
REPEAT(FIRST_X_ASSUM(SUBST_ALL_TAC o MATCH_MP (ARITH_RULE
`a < 2 EXP (64 * 0) ==> a = 0`))) THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC [1] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[ODD];
ALL_TAC] THEN
FIRST_ASSUM(MP_TAC o MATCH_MP (ONCE_REWRITE_RULE[IMP_CONJ]
NONOVERLAPPING_IMP_SMALL_1)) THEN
ANTS_TAC THENL [CONV_TAC NUM_REDUCE_CONV; DISCH_TAC] THEN
ENSURES_WHILE_PUP_TAC `k:num` `pc + 0x8` `pc + 0x14`
`\i s. (read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory(mm,k) s = m /\
read X4 s = word i /\
bignum_from_memory(word_add mm (word(8 * i)),k - i) s =
highdigits m i /\
bignum_from_memory(t,i) s = lowdigits m i) /\
(read X9 s = word(bigdigit m (i - 1)))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; LOWDIGITS_0] THEN
REWRITE_TAC[MULT_CLAUSES; WORD_ADD_0; SUB_0; HIGHDIGITS_0] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--3) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES; ADD_SUB] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2);
ASM_SIMP_TAC[LOWDIGITS_SELF]] THEN
ENSURES_SEQUENCE_TAC `pc + 0x54`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory(mm,k) s = m /\
m divides bignum_from_memory(t,k) s /\
read X9 s = word(bigdigit (bignum_from_memory(t,k) s) (k - 1)) /\
(ODD m ==> 2 EXP (64 * (k - 1)) <= bignum_from_memory(t,k) s)` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `k = 1` THENL
[UNDISCH_THEN `k = 1` SUBST_ALL_TAC THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--4) THEN
ASM_SIMP_TAC[LOWDIGITS_SELF; DIVIDES_REFL; SUB_REFL] THEN
REWRITE_TAC[ARITH_RULE `2 EXP (64 * 0) <= m <=> ~(m = 0)`] THEN
MESON_TAC[ODD];
ALL_TAC] THEN
MP_TAC(ARITH_RULE `k - 1 = 0 <=> k = 0 \/ k = 1`) THEN
ASM_REWRITE_TAC[] THEN DISCH_TAC THEN
ENSURES_WHILE_PUP_TAC `k - 1` `pc + 0x24` `pc + 0x50`
`\i s. (read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory(mm,k) s = m /\
read X4 s = word(k - 1 - i) /\
read X9 s = word(bigdigit (bignum_from_memory(t,k) s) (k - 1)) /\
m divides bignum_from_memory(t,k) s /\
(ODD m ==> 2 EXP (64 * i) <= bignum_from_memory(t,k) s)) /\
(read ZF s <=> i = k - 1)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[MP_TAC(ISPECL [`word k:int64`; `word 1:int64`] VAL_WORD_SUB_CASES) THEN
ASM_SIMP_TAC[VAL_WORD_1; LE_1] THEN DISCH_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--4) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[SUB_0] THEN
ASM_SIMP_TAC[DIVIDES_REFL; WORD_SUB; LE_1] THEN
REWRITE_TAC[ARITH_RULE `2 EXP (64 * 0) <= m <=> ~(m = 0)`] THEN
MESON_TAC[ODD];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC [1];
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC [1]] THEN
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `n:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `n:num` THEN
GLOBALIZE_PRECONDITION_TAC THEN
ABBREV_TAC `topz <=> bigdigit n (k - 1) = 0` THEN
ENSURES_WHILE_PUP_TAC `k:num` `pc + 0x30` `pc + 0x44`
`\j s. (read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
read X4 s = word (k - 1 - i) /\
read X5 s = word j /\
read X7 s = (if j = 0 then word 0 else word(bigdigit n (j - 1))) /\
(read ZF s <=> topz) /\
bignum_from_memory(word_add t (word(8 * j)),k - j) s =
highdigits n j /\
bignum_from_memory(t,j) s =
lowdigits (if topz then 2 EXP 64 * n else n) j) /\
(read X9 s =
word(bigdigit (bignum_from_memory(t,j) s) (j - 1)))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--3) THEN
REWRITE_TAC[VAL_WORD_SUB_EQ_0; VAL_WORD_0; HIGHDIGITS_0; SUB_0] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; BIGDIGIT_BOUND; DIMINDEX_64] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL; LOWDIGITS_0] THEN
ASM_REWRITE_TAC[WORD_ADD_0; MULT_CLAUSES; BIGNUM_FROM_MEMORY_BYTES];
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
VAL_INT64_TAC `k - 1` THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
RULE_ASSUM_TAC(REWRITE_RULE[VAL_WORD_SUB_EQ_0]) THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC [3] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> s) /\ q /\ r ==> p /\ q /\ r /\ s`) THEN
CONJ_TAC THENL
[REWRITE_TAC[ARITH_RULE `a - (i + 1) = a - i - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < k - 1 ==> 1 <= k - 1 - i`];
ALL_TAC] THEN
CONJ_TAC THENL
[DISCH_THEN SUBST1_TAC THEN
W(MP_TAC o PART_MATCH (lhand o rand) VAL_WORD_EQ o
lhand o lhand o snd) THEN
REWRITE_TAC[DIMINDEX_64] THEN ANTS_TAC THENL
[ALL_TAC; DISCH_THEN SUBST1_TAC] THEN
MAP_EVERY UNDISCH_TAC [`k < 2 EXP 64`; `i < k - 1`] THEN ARITH_TAC;
ALL_TAC] THEN
W(MP_TAC o PART_MATCH (lhand o rand) LOWDIGITS_SELF o
rand o lhand o snd) THEN
ANTS_TAC THENL
[EXPAND_TAC "topz" THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN
SUBGOAL_THEN `n = lowdigits n ((k - 1) + 1)` SUBST1_TAC THENL
[ASM_SIMP_TAC[SUB_ADD; LE_1; LOWDIGITS_SELF];
ASM_REWRITE_TAC[LOWDIGITS_CLAUSES; ADD_CLAUSES; MULT_CLAUSES]] THEN
SUBGOAL_THEN `64 * k = 64 + 64 * (k - 1)` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC; REWRITE_TAC[EXP_ADD]] THEN
SIMP_TAC[LT_MULT_LCANCEL; LOWDIGITS_BOUND; EXP_EQ_0; ARITH_EQ];
DISCH_THEN SUBST1_TAC] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[] THENL
[ASM_SIMP_TAC[DIVIDES_LMUL; EXP_ADD; LE_MULT_LCANCEL; EXP_EQ_0;
ARITH_EQ; ARITH_RULE `64 * (i + 1) = 64 + 64 * i`];
DISCH_TAC THEN TRANS_TAC LE_TRANS `2 EXP (64 * (k - 1))`] THEN
ASM_SIMP_TAC[LE_EXP; ARITH_EQ; ARITH_RULE
`i < k - 1 ==> 64 * (i + 1) <= 64 * (k - 1)`] THEN
SUBGOAL_THEN `n = lowdigits n ((k - 1) + 1)` SUBST1_TAC THENL
[ASM_SIMP_TAC[SUB_ADD; LE_1; LOWDIGITS_SELF];
ASM_REWRITE_TAC[LOWDIGITS_CLAUSES; ADD_CLAUSES; MULT_CLAUSES]] THEN
MATCH_MP_TAC(ARITH_RULE `e * 1 <= e * d ==> e <= e * d + c`) THEN
ASM_SIMP_TAC[LE_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ; LE_1]] THEN
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[ARITH_RULE `k - j = 0 <=> ~(j < k)`] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP; BIGDIGIT_BIGNUM_FROM_MEMORY] THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--5) THEN
ASM_REWRITE_TAC[ADD_SUB; GSYM WORD_ADD; ADD_EQ_0; ARITH_EQ] THEN
REWRITE_TAC[ARITH_RULE `j < j + 1`] THEN
UNDISCH_THEN `bigdigit n (k - 1) = 0 <=> topz` (SUBST_ALL_TAC o SYM) THEN
ASM_CASES_TAC `bigdigit n (k - 1) = 0` THEN ASM_REWRITE_TAC[] THEN
SIMP_TAC[LOWDIGITS_CLAUSES; VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THENL
[ALL_TAC; ARITH_TAC] THEN
ASM_CASES_TAC `j = 0` THEN ASM_REWRITE_TAC[MULT_CLAUSES; EXP] THEN
REWRITE_TAC[LOWDIGITS_0; VAL_WORD_0; ADD_CLAUSES] THEN
REWRITE_TAC[REWRITE_RULE[lowdigits] (GSYM LOWDIGITS_1)] THEN
REWRITE_TAC[MULT_CLAUSES; MOD_MULT] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
MATCH_MP_TAC(NUM_RING `x:num = y ==> a + e * x = e * y + a`) THEN
SUBGOAL_THEN `j = SUC(j - 1)`
(fun th -> GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [th])
THENL [UNDISCH_TAC `~(j = 0)` THEN ARITH_TAC; ALL_TAC] THEN
REWRITE_TAC[bigdigit; EXP_ADD; ARITH_RULE `64 * SUC j = 64 + 64 * j`] THEN
SIMP_TAC[DIV_MULT2; EXP_EQ_0; ARITH_EQ];
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC `pc + 0x90`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory(mm,k) s = m /\
m divides bignum_from_memory(t,k) s /\
(ODD m ==> 2 EXP (64 * k - 1) <= bignum_from_memory(t,k) s)` THEN
CONJ_TAC THENL
[GHOST_INTRO_TAC `n:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `n:num` THEN GLOBALIZE_PRECONDITION_TAC THEN
ABBREV_TAC `c = 64 - bitsize(bigdigit n (k - 1))` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x6c` `pc + 0x88`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
read X4 s = word i /\
read X8 s = word_neg(word(bitval(~(c MOD 64 = 0)))) /\
read X9 s = word c /\
read X11 s = word_neg(word c) /\
bignum_from_memory(word_add t (word (8 * i)),k - i) s =
highdigits n i /\
2 EXP (64 * i) * val(read X10 s) + bignum_from_memory(t,i) s =
2 EXP (c MOD 64) * lowdigits n i` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--6) THEN
SIMP_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; BIGNUM_FROM_MEMORY_TRIVIAL] THEN
REWRITE_TAC[LOWDIGITS_0; DIV_0; VAL_WORD_0; MULT_CLAUSES; ADD_CLAUSES;
WORD_ADD_0; HIGHDIGITS_0; SUB_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[WORD_SUB_LZERO] THEN
SUBST1_TAC(SYM(WORD_REDUCE_CONV `word_not(word 0):int64`)) THEN
ONCE_REWRITE_TAC[GSYM COND_SWAP] THEN REWRITE_TAC[GSYM WORD_MASK] THEN
SUBST1_TAC(ARITH_RULE `63 = 2 EXP 6 - 1`) THEN
REWRITE_TAC[VAL_WORD_AND_MASK_WORD] THEN
CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[MOD_64_CLAUSES] THEN
SUBGOAL_THEN `word_clz(word(bigdigit n (k - 1)):int64) = c`
(fun th -> ASM_REWRITE_TAC[th]) THEN
REWRITE_TAC[WORD_CLZ_BITSIZE; DIMINDEX_64] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `b:int64` `read X10` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[ARITH_RULE `n - i = 0 <=> ~(i < n)`] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--7) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
SIMP_TAC[VAL_WORD_EQ; BIGDIGIT_BOUND; DIMINDEX_64] THEN
REWRITE_TAC[MOD_64_CLAUSES; LOWDIGITS_CLAUSES] THEN
REWRITE_TAC[EXP_ADD; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
FIRST_ASSUM(MATCH_MP_TAC o MATCH_MP (NUM_RING
`ee * b + m:num = c * l
==> e * d + y = c * z + b
==> (ee * e) * d + m + ee * y = c * (ee * z + l)`)) THEN
REWRITE_TAC[ADD_ASSOC; EQ_ADD_RCANCEL; lemma1] THEN
REWRITE_TAC[word_jshl; MOD_64_CLAUSES; DIMINDEX_64; VAL_WORD_USHR] THEN
W(MP_TAC o PART_MATCH (lhand o rand) VAL_WORD_OR_DISJOINT o
rand o lhand o snd) THEN
ANTS_TAC THENL
[REWRITE_TAC[WORD_EQ_BITS_ALT; BIT_WORD_0; BIT_WORD_AND] THEN
SIMP_TAC[BIT_WORD_SHL; DIMINDEX_64] THEN MATCH_MP_TAC(MESON[]
`(!i. q i ==> ~s i) ==> !i. p i ==> ~((q i /\ r i) /\ (s i))`) THEN
REWRITE_TAC[UPPER_BITS_ZERO] THEN
UNDISCH_THEN
`2 EXP (64 * i) * val(b:int64) + read (memory :> bytes (t,8 * i)) s7 =
2 EXP (c MOD 64) * lowdigits n i`
(MP_TAC o AP_TERM `\x. x DIV 2 EXP (64 * i)`) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
SIMP_TAC[DIV_MULT_ADD; EXP_EQ_0; ARITH_EQ] THEN
SIMP_TAC[DIV_LT; BIGNUM_FROM_MEMORY_BOUND; ADD_CLAUSES] THEN
DISCH_THEN SUBST1_TAC THEN
SIMP_TAC[RDIV_LT_EQ; EXP_EQ_0; ARITH_EQ] THEN
GEN_REWRITE_TAC RAND_CONV [MULT_SYM] THEN
REWRITE_TAC[LT_MULT_LCANCEL; LOWDIGITS_BOUND; EXP_EQ_0; ARITH_EQ];
DISCH_THEN SUBST1_TAC] THEN
SIMP_TAC[VAL_WORD_SHL; VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[ADD_ASSOC; EQ_ADD_RCANCEL] THEN
SUBGOAL_THEN `2 EXP 64 = 2 EXP (c MOD 64) * 2 EXP (64 - c MOD 64)`
SUBST1_TAC THENL
[REWRITE_TAC[GSYM EXP_ADD] THEN AP_TERM_TAC THEN ARITH_TAC;
REWRITE_TAC[MOD_MULT2; GSYM MULT_ASSOC; GSYM LEFT_ADD_DISTRIB]] THEN
REWRITE_TAC[DIVISION_SIMP];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2);
GHOST_INTRO_TAC `b:int64` `read X10` THEN
ASM_SIMP_TAC[LOWDIGITS_SELF] THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2)] THEN
FIRST_X_ASSUM(MP_TAC o MATCH_MP (ARITH_RULE
`e * b + z = cn
==> (e * b < e * 1 ==> e * b = 0)
==> cn < e ==> z = cn`)) THEN
ANTS_TAC THENL
[SIMP_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ; MULT_EQ_0] THEN ARITH_TAC;
ALL_TAC] THEN
ASM_CASES_TAC `n = 0` THENL
[ASM_REWRITE_TAC[MULT_CLAUSES; EXP_LT_0; ARITH_EQ] THEN
DISCH_THEN SUBST1_TAC THEN ASM_REWRITE_TAC[DIVIDES_0] THEN
DISCH_THEN(fun th -> FIRST_X_ASSUM(MP_TAC o C MATCH_MP th)) THEN
ASM_REWRITE_TAC[CONJUNCT1 LE; EXP_EQ_0; ARITH_EQ];
ALL_TAC] THEN
ANTS_TAC THENL
[SUBGOAL_THEN `64 * k = c MOD 64 + (64 * k - c MOD 64)` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC;
REWRITE_TAC[EXP_ADD; LT_MULT_LCANCEL; ARITH_EQ; EXP_EQ_0]] THEN
REWRITE_TAC[GSYM BITSIZE_LE] THEN
SUBGOAL_THEN
`n = 2 EXP (64 * (k - 1)) * highdigits n (k - 1) + lowdigits n (k - 1)`
SUBST1_TAC THENL [REWRITE_TAC[HIGH_LOW_DIGITS]; ALL_TAC] THEN
ASM_SIMP_TAC[HIGHDIGITS_TOP] THEN
UNDISCH_THEN `64 - bitsize (bigdigit n (k - 1)) = c`
(SUBST1_TAC o SYM) THEN
ASM_CASES_TAC `bigdigit n (k - 1) = 0` THENL
[ASM_REWRITE_TAC[BITSIZE_0; MULT_CLAUSES; ADD_CLAUSES] THEN
CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[BITSIZE_LE; SUB_0] THEN
TRANS_TAC LTE_TRANS `2 EXP (64 * (k - 1))` THEN
ASM_REWRITE_TAC[LOWDIGITS_BOUND; LE_EXP; ARITH_EQ] THEN ARITH_TAC;
ASM_SIMP_TAC[BITSIZE_MULT_ADD; LOWDIGITS_BOUND]] THEN
MATCH_MP_TAC(ARITH_RULE `a + c <= b ==> a <= b - c MOD 64`) THEN
MATCH_MP_TAC(ARITH_RULE
`~(k = 0) /\ b <= 64 ==> (64 * (k - 1) + b) + (64 - b) <= 64 * k`) THEN
ASM_REWRITE_TAC[BITSIZE_LE; BIGDIGIT_BOUND];
DISCH_THEN SUBST1_TAC] THEN
ASM_SIMP_TAC[DIVIDES_LMUL] THEN
DISCH_THEN(fun th -> FIRST_X_ASSUM(MP_TAC o C MATCH_MP th)) THEN
SUBGOAL_THEN `64 * k - 1 = c MOD 64 + (64 * k - 1 - c MOD 64)`
SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC;
REWRITE_TAC[EXP_ADD; LE_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ]] THEN
REWRITE_TAC[GSYM NOT_LT; GSYM BITSIZE_LE] THEN DISCH_TAC THEN
MATCH_MP_TAC(ARITH_RULE `~(b = 0) /\ a <= b + c ==> a - 1 - c < b`) THEN
ASM_REWRITE_TAC[BITSIZE_EQ_0] THEN
UNDISCH_THEN `64 - bitsize (bigdigit n (k - 1)) = c`
(SUBST1_TAC o SYM) THEN
ASM_SIMP_TAC[GSYM HIGHDIGITS_TOP; highdigits; BITSIZE_DIV] THEN
ASM_SIMP_TAC[MOD_LT; ARITH_RULE `b < a ==> 64 - (a - b) < 64`] THEN
UNDISCH_TAC `64 * (k - 1) < bitsize n` THEN ARITH_TAC;
ALL_TAC] THEN
GHOST_INTRO_TAC `n:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `n:num` THEN
GLOBALIZE_PRECONDITION_TAC THEN
ABBREV_TAC `h = bigdigit n (k - 1)` THEN
ABBREV_TAC `l = lowdigits n (k - 1)` THEN
SUBGOAL_THEN
`h < 2 EXP 64 /\ l < 2 EXP (64 * (k - 1)) /\
2 EXP (64 * (k - 1)) * h + l = n /\
(ODD m ==> 2 EXP 63 <= h)`
STRIP_ASSUME_TAC THENL
[UNDISCH_THEN `bigdigit n (k - 1) = h` (SUBST1_TAC o SYM) THEN
UNDISCH_THEN `lowdigits n (k - 1) = l` (SUBST1_TAC o SYM) THEN
REWRITE_TAC[LOWDIGITS_BOUND; BIGDIGIT_BOUND] THEN
ASM_SIMP_TAC[GSYM HIGHDIGITS_TOP; HIGH_LOW_DIGITS] THEN
SIMP_TAC[highdigits; LE_RDIV_EQ; EXP_EQ_0; ARITH_EQ; GSYM EXP_ADD] THEN
ASM_SIMP_TAC[ARITH_RULE `~(k = 0) ==> 64 * (k - 1) + 63 = 64 * k - 1`];
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC `pc + 0xd8`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
(ODD m ==> read X11 s = word(2 EXP 126 DIV h))` THEN
CONJ_TAC THENL
[ENSURES_WHILE_PUP_TAC `62` `pc + 0xa4` `pc + 0xcc`
`\i s. (read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
read X6 s = word h /\
read X4 s = word(62 - i) /\
val(read X11 s) < 2 EXP (i + 1) /\
(ODD m
==> val(read X11 s) * h + val(read X10 s) = 2 EXP (64 + i) /\
val(read X10 s) <= h)) /\
(read ZF s <=> i = 62)` THEN
REPEAT CONJ_TAC THENL
[ARITH_TAC;
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
MP_TAC(ISPECL [`k:num`; `t:int64`; `s0:armstate`; `k - 1`]
BIGDIGIT_BIGNUM_FROM_MEMORY) THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[ARITH_RULE `k - 1 < k <=> ~(k = 0)`] THEN
DISCH_THEN(MP_TAC o SYM) THEN
GEN_REWRITE_TAC LAND_CONV [VAL_WORD_GALOIS] THEN
REWRITE_TAC[DIMINDEX_64] THEN STRIP_TAC THEN
SUBGOAL_THEN `word_sub (word k) (word 1):int64 = word(k - 1)`
ASSUME_TAC THENL [ASM_SIMP_TAC[WORD_SUB; LE_1; VAL_WORD_1]; ALL_TAC] THEN
VAL_INT64_TAC `k - 1` THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
SIMP_TAC[VAL_WORD_1; EXP_1; ADD_CLAUSES; SUB_0; ARITH_RULE `1 < 2`] THEN
DISCH_THEN(fun th -> REPEAT(FIRST_X_ASSUM(ASSUME_TAC o C MP th))) THEN
REWRITE_TAC[WORD_SUB_LZERO; VAL_WORD_1; MULT_CLAUSES] THEN
REWRITE_TAC[VAL_WORD_NEG_CASES; DIMINDEX_64] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64] THEN
MAP_EVERY UNDISCH_TAC [`2 EXP 63 <= h`; `h < 2 EXP 64`] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN
GHOST_INTRO_TAC `q:num` `\s. val(read X11 s)` THEN
GHOST_INTRO_TAC `r:num` `\s. val(read X10 s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GLOBALIZE_PRECONDITION_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--10) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
SUBST1_TAC(SYM(WORD_REDUCE_CONV `word_not(word 0):int64`)) THEN
ONCE_REWRITE_TAC[GSYM COND_SWAP] THEN REWRITE_TAC[GSYM WORD_MASK] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[REWRITE_TAC[ARITH_RULE `a - (i + 1) = a - i - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < k ==> 1 <= k - i`];
DISCH_THEN SUBST1_TAC] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64;
ARITH_RULE `i < 62 ==> (62 - (i + 1) = 0 <=> i + 1 = 62)`;
ARITH_RULE `62 - i < 2 EXP 64`] THEN
REWRITE_TAC[WORD_RULE `word_sub x (word_neg y) = word_add x y`] THEN
REWRITE_TAC[NOT_LT; GSYM WORD_ADD] THEN CONJ_TAC THENL
[MATCH_MP_TAC VAL_WORD_LT THEN ONCE_REWRITE_TAC[EXP_ADD] THEN
MATCH_MP_TAC(ARITH_RULE
`q < i /\ b <= 1 ==> (q + q) + b < i * 2 EXP 1`) THEN
ASM_REWRITE_TAC[BITVAL_BOUND];
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MP th)))] THEN
SUBST1_TAC(ISPECL
[`word h:int64`; `word r:int64`] VAL_WORD_SUB_CASES) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64] THEN
ASM_SIMP_TAC[ARITH_RULE `r <= h ==> (h - r <= r <=> h <= 2 * r)`] THEN
REWRITE_TAC[WORD_AND_MASK; GSYM MULT_2] THEN
ASM_CASES_TAC `h <= 2 * r` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
REWRITE_TAC[WORD_SUB_0; GSYM MULT_2] THENL
[SUBGOAL_THEN
`word_sub (word (2 * r)) (word h):int64 = word(2 * r - h)`
SUBST1_TAC THENL [ASM_REWRITE_TAC[WORD_SUB]; ALL_TAC] THEN
SUBGOAL_THEN `2 * r - h < 2 EXP 64` ASSUME_TAC THENL
[MAP_EVERY UNDISCH_TAC [`r:num <= h`; `h < 2 EXP 64`] THEN ARITH_TAC;
ALL_TAC] THEN
SUBGOAL_THEN `2 * q + 1 < 2 EXP 64` ASSUME_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (ARITH_RULE
`q < 2 EXP (i + 1)
==> 2 EXP 1 * 2 EXP (i + 1) <= 2 EXP 64
==> 2 * q + 1 < 2 EXP 64`)) THEN
REWRITE_TAC[GSYM EXP_ADD; LE_EXP; ARITH_EQ] THEN
UNDISCH_TAC `i < 62` THEN ARITH_TAC;
ALL_TAC] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64] THEN
REWRITE_TAC[ADD_ASSOC] THEN ONCE_REWRITE_TAC[EXP_ADD] THEN
SIMPLE_ARITH_TAC;
RULE_ASSUM_TAC(REWRITE_RULE[NOT_LE]) THEN
ASM_SIMP_TAC[VAL_WORD_LE; LT_IMP_LE] THEN
SUBGOAL_THEN `2 * r < 2 EXP 64` ASSUME_TAC THENL
[MAP_EVERY UNDISCH_TAC [`2 * r < h`; `h < 2 EXP 64`] THEN ARITH_TAC;
ALL_TAC] THEN
SUBGOAL_THEN `2 * q < 2 EXP 64` ASSUME_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (ARITH_RULE
`q < 2 EXP (i + 1)
==> 2 EXP 1 * 2 EXP (i + 1) <= 2 EXP 64
==> 2 * q < 2 EXP 64`)) THEN
REWRITE_TAC[GSYM EXP_ADD; LE_EXP; ARITH_EQ] THEN
UNDISCH_TAC `i < 62` THEN ARITH_TAC;
ALL_TAC] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64] THEN
ASM_REWRITE_TAC[GSYM MULT_ASSOC; GSYM LEFT_ADD_DISTRIB] THEN
REWRITE_TAC[EXP_ADD] THEN ARITH_TAC];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC [1];
GHOST_INTRO_TAC `q:num` `\s. val(read X11 s)` THEN
GHOST_INTRO_TAC `r:num` `\s. val(read X10 s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GLOBALIZE_PRECONDITION_TAC THEN
ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--3) THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MP th))) THEN
ASM_SIMP_TAC[VAL_WORD_SUB_EQ_0; VAL_WORD_EQ; DIMINDEX_64] THEN
REWRITE_TAC[COND_SWAP; GSYM WORD_ADD] THEN
GEN_REWRITE_TAC LAND_CONV [GSYM COND_RAND] THEN
AP_TERM_TAC THEN CONV_TAC SYM_CONV THEN
MATCH_MP_TAC DIV_UNIQ THEN EXISTS_TAC `if r = h then 0 else r` THEN
UNDISCH_TAC `q * h + r = 2 EXP (64 + 62)` THEN
UNDISCH_TAC `r:num <= h` THEN REWRITE_TAC[LE_LT] THEN
UNDISCH_TAC `2 EXP 63 <= h` THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[LT_REFL] THEN ARITH_TAC];
ALL_TAC] THEN
* * Ghost the quotient estimate q = floor(2 ^ 126 / h ) * *
GHOST_INTRO_TAC `q:int64` `read X11` THEN GLOBALIZE_PRECONDITION_TAC THEN
ENSURES_SEQUENCE_TAC `pc + 0x104`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
2 EXP (64 * k) * val(read X9 s) + bignum_from_memory(z,k) s =
val(q:int64) * n` THEN
CONJ_TAC THENL
[ENSURES_WHILE_UP_TAC `k:num` `pc + 0xe0` `pc + 0xf8`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
read X11 s = q /\
read X4 s = word i /\
bignum_from_memory(word_add t (word (8 * i)),k - i) s =
highdigits n i /\
2 EXP (64 * i) * (bitval(read CF s) + val(read X9 s)) +
bignum_from_memory(z,i) s =
val(q:int64) * lowdigits n i` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; SUB_0; VAL_WORD_0] THEN
REWRITE_TAC[BITVAL_CLAUSES; MULT_CLAUSES; WORD_ADD_0] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL; LOWDIGITS_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; HIGHDIGITS_0] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read X9` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [2;3] (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES; GSYM WORD_ADD] THEN
REWRITE_TAC[LEFT_ADD_DISTRIB; ADD_ASSOC] THEN FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [SYM th]) THEN
REWRITE_TAC[EXP_ADD; MULT_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read X9` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
RULE_ASSUM_TAC(REWRITE_RULE[VAL_WORD_SUB_EQ_0]) THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [3] [3] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
GEN_REWRITE_TAC (LAND_CONV o RAND_CONV) [ADD_SYM] THEN
DISCH_THEN(SUBST_ALL_TAC o SYM) THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (ARITH_RULE
`ee * (e * c + s) + z = qn
==> (ee * e * c < ee * e * 1 ==> ee * e * c = 0) /\ qn < e * ee
==> ee * s + z = qn`)) THEN
SIMP_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ; MULT_EQ_0] THEN
CONJ_TAC THENL [ARITH_TAC; MATCH_MP_TAC LT_MULT2] THEN
ASM_REWRITE_TAC[VAL_BOUND_64]];
ALL_TAC] THEN
* * We introduce an exclusion of m = 1 temporarily here . * *
ENSURES_SEQUENCE_TAC `pc + 0x134`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
(ODD m /\ ~(m = 1)
==> bignum_from_memory(z,k) s = 2 EXP (64 * k + 62) MOD n)` THEN
CONJ_TAC THENL
[GHOST_INTRO_TAC `rhi:num` `\s. val(read X9 s)` THEN
GHOST_INTRO_TAC `rlo:num` `bignum_from_memory (z,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `rlo:num` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GLOBALIZE_PRECONDITION_TAC THEN
ABBREV_TAC `b <=> 2 EXP (64 * k + 62) <= val(q:int64) * n` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x114` `pc + 0x12c`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X4 s = word i /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
read X11 s = word_neg(word(bitval b)) /\
bignum_from_memory(word_add t (word (8 * i)),k - i) s =
highdigits n i /\
bignum_from_memory(word_add z (word (8 * i)),k - i) s =
highdigits rlo i /\
&(bignum_from_memory(z,i) s):real =
&2 pow (64 * i) * &(bitval(~(read CF s))) +
(&(bitval b) * &(lowdigits n i) - &(lowdigits rlo i))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--4) THEN
REWRITE_TAC[SUB_0; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL; LOWDIGITS_0; HIGHDIGITS_0] THEN
REWRITE_TAC[ADD_CLAUSES; MULT_CLAUSES; WORD_ADD_0; BITVAL_CLAUSES] THEN
ASM_REWRITE_TAC[REAL_MUL_RZERO; BIGNUM_FROM_MEMORY_BYTES] THEN
CONV_TAC REAL_RAT_REDUCE_CONV THEN REWRITE_TAC[WORD_MASK] THEN
EXPAND_TAC "b" THEN REWRITE_TAC[GSYM NOT_LT; COND_SWAP] THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64] THEN
CONV_TAC WORD_REDUCE_CONV THEN AP_THM_TAC THEN
AP_THM_TAC THEN AP_TERM_TAC THEN FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (RAND_CONV o LAND_CONV) [SYM th]) THEN
REWRITE_TAC[EXP_ADD] THEN
GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [ARITH_RULE `x = x + 0`] THEN
ASM_SIMP_TAC[LEXICOGRAPHIC_LT; EXP_LT_0; ARITH_EQ] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES; GSYM WORD_ADD] THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
REWRITE_TAC[REAL_POW_ADD; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
REWRITE_TAC[WORD_AND_MASK] THEN COND_CASES_TAC THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; VAL_WORD_0; MULT_CLAUSES] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `r:num` `bignum_from_memory (z,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `r:num` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GLOBALIZE_PRECONDITION_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
DISCH_THEN(CONJUNCTS_THEN2 MP_TAC ASSUME_TAC) THEN
DISCH_THEN(fun th -> ASSUME_TAC th THEN MP_TAC th) THEN
DISCH_THEN(fun th -> REPEAT(FIRST_X_ASSUM(ASSUME_TAC o C MP th)))] THEN
UNDISCH_TAC `2 EXP (64 * k - 1) <= n` THEN ASM_CASES_TAC `n = 0` THEN
ASM_REWRITE_TAC[CONJUNCT1 LE; EXP_EQ_0; ARITH_EQ] THEN DISCH_TAC THEN
SUBGOAL_THEN `val(q:int64) = 2 EXP 126 DIV h` SUBST_ALL_TAC THENL
[ASM_REWRITE_TAC[] THEN MATCH_MP_TAC VAL_WORD_EQ THEN
REWRITE_TAC[DIMINDEX_64] THEN MATCH_MP_TAC(ARITH_RULE
`x <= 2 EXP 126 DIV 2 EXP 63 ==> x < 2 EXP 64`) THEN
MATCH_MP_TAC DIV_MONO2 THEN ASM_REWRITE_TAC[] THEN ARITH_TAC;
UNDISCH_THEN `q:int64 = word(2 EXP 126 DIV h)` (K ALL_TAC)] THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC EQUAL_FROM_CONGRUENT_MOD_MOD THEN
MAP_EVERY EXISTS_TAC
[`64 * k`;
`&(bitval b) * &n +
(&2 pow (64 * k + 62) - &(2 EXP 126 DIV h) * &n):real`] THEN
ASM_REWRITE_TAC[] THEN CONJ_TAC THENL
[REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
UNDISCH_THEN `2 EXP (64 * k) * rhi + rlo = 2 EXP 126 DIV h * n`
(SUBST1_TAC o SYM) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; REAL_POW_ADD] THEN
REWRITE_TAC[ONCE_REWRITE_RULE[REAL_MUL_SYM] real_div] THEN
REWRITE_TAC[REAL_ADD_LDISTRIB; REAL_SUB_LDISTRIB; REAL_MUL_ASSOC] THEN
SIMP_TAC[REAL_MUL_LINV; REAL_POW_EQ_0; REAL_OF_NUM_EQ; ARITH_EQ] THEN
REAL_INTEGER_TAC;
ALL_TAC] THEN
ONCE_REWRITE_TAC[REAL_OF_NUM_POW] THEN MATCH_MP_TAC remalemma THEN
ASM_REWRITE_TAC[] THEN CONJ_TAC THENL
[DISCH_THEN(MP_TAC o SPEC `m:num` o MATCH_MP (NUMBER_RULE
`n divides x ==> !m:num. m divides n ==> m divides x`)) THEN
ASM_REWRITE_TAC[] THEN SIMP_TAC[DIVIDES_PRIMEPOW; PRIME_2] THEN
DISCH_THEN(X_CHOOSE_THEN `i:num` (SUBST_ALL_TAC o CONJUNCT2)) THEN
MAP_EVERY UNDISCH_TAC [`~(2 EXP i = 1)`; `ODD(2 EXP i)`] THEN
SIMP_TAC[ODD_EXP; ARITH; EXP];
ALL_TAC] THEN
MP_TAC(ASSUME `2 EXP (64 * (k - 1)) * h + l = n`) THEN DISCH_THEN(fun th ->
GEN_REWRITE_TAC (LAND_CONV o funpow 4 RAND_CONV) [SYM th]) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
SUBGOAL_THEN `64 * k + 62 = 64 * (k - 1) + 126` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC; REWRITE_TAC[REAL_POW_ADD]] THEN
REWRITE_TAC[REAL_ARITH
`ee * e - d * (ee * h + l):real = ee * (e - d * h) - d * l`] THEN
REWRITE_TAC[REAL_OF_NUM_POW; GSYM REAL_OF_NUM_MOD] THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
MATCH_MP_TAC(REAL_ARITH
`!x y:real. &0 <= x /\ &0 <= y /\ x <= e /\ y <= e
==> abs(x - y) <= e`) THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES; LE_0] THEN CONJ_TAC THENL
[MP_TAC(ASSUME `2 EXP (64 * (k - 1)) * h + l = n`) THEN
DISCH_THEN(fun th -> GEN_REWRITE_TAC RAND_CONV [SYM th]) THEN
MATCH_MP_TAC(ARITH_RULE `a:num < b ==> a <= b + c`) THEN
REWRITE_TAC[LT_MULT_LCANCEL; MOD_LT_EQ; EXP_EQ_0; ARITH_EQ] THEN
UNDISCH_TAC `2 EXP 63 <= h` THEN ARITH_TAC;
TRANS_TAC LE_TRANS `2 EXP 63 * 2 EXP (64 * (k - 1))` THEN CONJ_TAC THENL
[MATCH_MP_TAC LE_MULT2 THEN ASM_SIMP_TAC[LT_IMP_LE] THEN
SUBST1_TAC(ARITH_RULE `2 EXP 63 = 2 EXP 126 DIV 2 EXP 63`) THEN
MATCH_MP_TAC DIV_MONO2 THEN ASM_REWRITE_TAC[] THEN ARITH_TAC;
MP_TAC(ASSUME `2 EXP (64 * (k - 1)) * h + l = n`) THEN
DISCH_THEN(fun th -> GEN_REWRITE_TAC RAND_CONV [SYM th]) THEN
MATCH_MP_TAC(ARITH_RULE
`ee * e:num <= ee * h ==> e * ee <= ee * h + l`) THEN
ASM_REWRITE_TAC[LE_MULT_LCANCEL]]];
ALL_TAC] THEN
* * The first modular doubling , " dubloop1 " and " corrloop1 " * *
ENSURES_SEQUENCE_TAC `pc + 0x18c`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
(ODD m /\ ~(m = 1)
==> bignum_from_memory(z,k) s = 2 EXP (64 * k + 63) MOD n)` THEN
CONJ_TAC THENL
[GHOST_INTRO_TAC `p62:num` `bignum_from_memory (z,k)` THEN
GLOBALIZE_PRECONDITION_TAC THEN
BIGNUM_TERMRANGE_TAC `k:num` `p62:num` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x13c` `pc + 0x158`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
read X5 s = word i /\
(read X9 s =
if i = 0 then word 0 else word(bigdigit p62 (i - 1))) /\
bignum_from_memory (word_add z (word(8 * i)),k - i) s =
highdigits p62 i /\
bignum_from_memory (word_add t (word(8 * i)),k - i) s =
highdigits n i /\
&(bignum_from_memory(z,i) s):real =
&2 pow (64 * i) * &(bitval(~read CF s)) +
&(lowdigits (2 * p62) i) - &(lowdigits n i)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; BITVAL_CLAUSES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN REAL_ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--7) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[GSYM WORD_ADD; ADD_EQ_0; ARITH_EQ; ADD_SUB] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES] THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[ARITH_RULE `64 * (n + 1) = 64 * n + 64`; REAL_POW_ADD] THEN
MATCH_MP_TAC(REAL_RING
`ee * y:real = w - z
==> --e * c + s = y ==> z + ee * s = (ee * e) * c + w`) THEN
REWRITE_TAC[REAL_SUB_LDISTRIB; REAL_ARITH
`x - y:real = z <=> x = y + z`] THEN
CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN
REWRITE_TAC[REAL_ARITH `(x:real) * &2 pow k = &2 pow k * x`] THEN
AP_TERM_TAC THEN AP_TERM_TAC THEN
CONV_TAC(ONCE_DEPTH_CONV NUM_MOD_CONV) THEN
SIMP_TAC[VAL_WORD_SUBWORD_JOIN; DIMINDEX_64; LE_REFL] THEN
ONCE_REWRITE_TAC[COND_RAND] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND; VAL_WORD_0] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[ADD_CLAUSES] THENL
[REWRITE_TAC[ARITH_RULE `(2 EXP 64 * x) DIV 2 EXP 63 = 2 * x`] THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
TRANS_TAC EQ_TRANS
`(highdigits p62 (i - 1) DIV 2 EXP 63) MOD 2 EXP 64` THEN
CONJ_TAC THENL
[GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [HIGHDIGITS_STEP] THEN
ASM_SIMP_TAC[ARITH_RULE `~(i = 0) ==> i - 1 + 1 = i`; DIV_MOD] THEN
AP_THM_TAC THEN AP_TERM_TAC THEN REWRITE_TAC[GSYM CONG] THEN
MATCH_MP_TAC(NUMBER_RULE
`(a:num == a') (mod n)
==> (e * a + b == e * a' + b) (mod (n * e))`) THEN
REWRITE_TAC[bigdigit; highdigits; CONG; MOD_MOD_EXP_MIN] THEN
CONV_TAC NUM_REDUCE_CONV THEN REFL_TAC;
REWRITE_TAC[highdigits; DIV_DIV; GSYM EXP_ADD] THEN
ASM_SIMP_TAC[bigdigit; EXP; DIV_MULT2; ARITH_EQ; ARITH_RULE
`~(i = 0) ==> 64 * i = SUC(64 * (i - 1) + 63)`]];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF; HIGHDIGITS_ZERO; SUB_REFL] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL]] THEN
GHOST_INTRO_TAC `hi:bool` `read CF` THEN
GHOST_INTRO_TAC `lo:num` `bignum_from_memory(z,k)` THEN
GLOBALIZE_PRECONDITION_TAC THEN
BIGNUM_TERMRANGE_TAC `k:num` `lo:num` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x16c` `pc + 0x184`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
read X5 s = word i /\
bignum_from_memory (word_add z (word(8 * i)),k - i) s =
highdigits lo i /\
bignum_from_memory (word_add t (word(8 * i)),k - i) s =
highdigits n i /\
(p62 < n
==> read X9 s = word_neg(word(bitval(2 * p62 < n))) /\
&(bignum_from_memory(z,i) s):real =
(&(lowdigits lo i) +
&(bitval(2 * p62 < n)) * &(lowdigits n i)) -
&2 pow (64 * i) * &(bitval(read CF s)))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
RULE_ASSUM_TAC(REWRITE_RULE[VAL_WORD_SUB_EQ_0]) THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (3--5) THEN
ENSURES_FINAL_STATE_TAC THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; BITVAL_CLAUSES] THEN
REWRITE_TAC[REAL_MUL_RZERO; REAL_SUB_REFL; REAL_ADD_LID] THEN
DISCH_TAC THEN REWRITE_TAC[WORD_RULE
`word_sub a b = word_neg c <=> word_add c a = b`] THEN
MP_TAC(GEN `x:int64` (ISPEC `x:int64` WORD_USHR_MSB)) THEN
REWRITE_TAC[DIMINDEX_64] THEN CONV_TAC NUM_REDUCE_CONV THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
REWRITE_TAC[GSYM VAL_EQ; VAL_WORD_BITVAL; VAL_WORD_ADD_CASES] THEN
SIMP_TAC[DIMINDEX_64; BITVAL_BOUND; ARITH_RULE
`b <= 1 /\ c <= 1 ==> b + c < 2 EXP 64`] THEN
SUBGOAL_THEN `2 * p62 < 2 * n /\ 2 * p62 < 2 * 2 EXP (64 * k)`
MP_TAC THENL
[ASM_REWRITE_TAC[LT_MULT_LCANCEL; ARITH_EQ]; ALL_TAC] THEN
SUBGOAL_THEN
`2 * p62 = 2 EXP (64 * k) *
bitval(bit 63 (word(bigdigit p62 (k - 1)):int64)) +
lowdigits (2 * p62) k`
SUBST1_TAC THENL
[MP_TAC(SPECL [`2 * p62`; `k:num`] (CONJUNCT1 HIGH_LOW_DIGITS)) THEN
DISCH_THEN(fun th -> GEN_REWRITE_TAC LAND_CONV [SYM th]) THEN
AP_THM_TAC THEN AP_TERM_TAC THEN AP_TERM_TAC THEN
MP_TAC(ISPEC `word(bigdigit p62 (k - 1)):int64` WORD_USHR_MSB) THEN
REWRITE_TAC[DIMINDEX_64] THEN CONV_TAC NUM_REDUCE_CONV THEN
DISCH_THEN(MP_TAC o SYM o AP_TERM `val:int64->num`) THEN
REWRITE_TAC[VAL_WORD_BITVAL; VAL_WORD_USHR] THEN
DISCH_THEN SUBST1_TAC THEN
SIMP_TAC[VAL_WORD_EQ; BIGDIGIT_BOUND; DIMINDEX_64] THEN
ASM_SIMP_TAC[highdigits; ARITH_RULE
`~(k = 0) ==> 64 * k = SUC(64 * (k - 1) + 63)`] THEN
SIMP_TAC[DIV_MULT2; EXP; ARITH_EQ] THEN
REWRITE_TAC[EXP_ADD; GSYM DIV_DIV] THEN
AP_THM_TAC THEN AP_TERM_TAC THEN
REWRITE_TAC[bigdigit] THEN CONV_TAC SYM_CONV THEN
MATCH_MP_TAC MOD_LT THEN
ASM_SIMP_TAC[RDIV_LT_EQ; EXP_EQ_0; ARITH_EQ; GSYM EXP_ADD] THEN
ASM_SIMP_TAC[ARITH_RULE `~(k = 0) ==> 64 * (k - 1) + 64 = 64 * k`];
ALL_TAC] THEN
ASM_CASES_TAC `bit 63 (word(bigdigit p62 (k - 1)):int64)` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THENL
[ASM_SIMP_TAC[ARITH_RULE `n:num < e ==> ~(e + a < n)`] THEN
UNDISCH_TAC
`&lo:real =
&2 pow (64 * k) * &(bitval(~hi)) +
&(lowdigits (2 * p62) k) - &n` THEN
UNDISCH_TAC `lo < 2 EXP (64 * k)` THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
BOOL_CASES_TAC `hi:bool` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
REAL_ARITH_TAC;
STRIP_TAC THEN AP_TERM_TAC THEN
REWRITE_TAC[NOT_LT; TAUT `(p <=> ~q) <=> (~p <=> q)`] THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN
EXISTS_TAC `64 * k` THEN REWRITE_TAC[GSYM REAL_BITVAL_NOT] THEN
UNDISCH_THEN
`&lo:real =
&2 pow (64 * k) * &(bitval(~hi)) + &(lowdigits (2 * p62) k) - &n`
(SUBST1_TAC o SYM) THEN
ASM_REWRITE_TAC[REAL_OF_NUM_CLAUSES; LE_0]];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hi:int64` `read X9` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MATCH_MP th)) THEN
ASSUME_TAC th) THEN
ASM_REWRITE_TAC[LOWDIGITS_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[WORD_ADD; WORD_NEG_NEG; VAL_WORD_BITVAL; WORD_BITVAL_EQ_0;
LOWDIGITS_CLAUSES; WORD_NEG_EQ_0; BITVAL_BOUND; NOT_LT] THEN
REWRITE_TAC[WORD_AND_MASK] THEN COND_CASES_TAC THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN ASM_REWRITE_TAC[NOT_LT] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND; VAL_WORD_0;
BITVAL_CLAUSES; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
REWRITE_TAC[REAL_POW_ADD] THEN CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF; HIGHDIGITS_ZERO; SUB_REFL] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL]] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MP th)) THEN
ASSUME_TAC(CONJUNCT2 th) THEN MP_TAC(CONJUNCT1 th)) THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MP th)) THEN
ASSUME_TAC th) THEN
SUBGOAL_THEN `2 EXP (64 * k + 63) MOD n =
(2 * 2 EXP (64 * k + 62) MOD n) MOD n`
SUBST1_TAC THENL
[REWRITE_TAC[ARITH_RULE `n + 63 = SUC(n + 62)`; EXP] THEN
CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
SUBGOAL_THEN `p62:num < n`
(fun th -> FIRST_X_ASSUM(MP_TAC o C MP th) THEN ASSUME_TAC th)
THENL
[ASM_REWRITE_TAC[MOD_LT_EQ] THEN
UNDISCH_TAC `2 EXP (64 * k - 1) <= n` THEN
SIMP_TAC[GSYM NOT_LT; CONTRAPOS_THM; EXP_LT_0] THEN ARITH_TAC;
UNDISCH_THEN `p62 = 2 EXP (64 * k + 62) MOD n` (SUBST1_TAC o SYM)] THEN
STRIP_TAC THEN
ASM_SIMP_TAC[MOD_ADD_CASES; MULT_2; ARITH_RULE
`p62 < n ==> p62 + p62 < 2 * n`] THEN
REWRITE_TAC[GSYM MULT_2] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN
MAP_EVERY EXISTS_TAC [`64 * k`; `&0:real`] THEN CONJ_TAC THENL
[REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; REAL_OF_NUM_CLAUSES] THEN
REWRITE_TAC[LE_0; BIGNUM_FROM_MEMORY_BOUND];
ALL_TAC] THEN
CONJ_TAC THENL
[MAP_EVERY UNDISCH_TAC [`p62:num < n`; `n < 2 EXP (64 * k)`] THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN ARITH_TAC;
REWRITE_TAC[INTEGER_CLOSED]] THEN
ASM_REWRITE_TAC[] THEN REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
COND_CASES_TAC THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
ASM_SIMP_TAC[GSYM REAL_OF_NUM_SUB; GSYM NOT_LT] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
REWRITE_TAC[ONCE_REWRITE_RULE[REAL_MUL_SYM] real_div] THEN
REWRITE_TAC[REAL_ADD_LDISTRIB; REAL_SUB_LDISTRIB; REAL_MUL_ASSOC] THEN
REWRITE_TAC[REAL_FIELD `inv(&2 pow n) * &2 pow n = (&1:real)`] THEN
CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN
REWRITE_TAC[REAL_ARITH
`--(&2) * e * a + e * b + c:real = e * (b - &2 * a) + c`] THEN
MATCH_MP_TAC INTEGER_ADD THEN
(CONJ_TAC THENL [ALL_TAC; REAL_INTEGER_TAC]) THEN
REWRITE_TAC[REAL_ARITH `inv x * (a - b):real = (a - b) / x`] THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
W(MP_TAC o PART_MATCH (rand o rand) REAL_CONGRUENCE o snd) THEN
REWRITE_TAC[EXP_EQ_0; ARITH_EQ] THEN DISCH_THEN(SUBST1_TAC o SYM) THEN
REWRITE_TAC[CONG; lowdigits] THEN CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
* * The second modular doubling , " dubloop2 " and " corrloop2 " * *
ENSURES_SEQUENCE_TAC `pc + 0x1e8`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
(ODD m /\ ~(m = 1)
==> bignum_from_memory(z,k) s = 2 EXP (64 * k + 64) MOD n /\
bignum_from_memory(t,k) s = 2 EXP (64 * k + 64) MOD n)` THEN
CONJ_TAC THENL
[GHOST_INTRO_TAC `p63:num` `bignum_from_memory (z,k)` THEN
GLOBALIZE_PRECONDITION_TAC THEN
BIGNUM_TERMRANGE_TAC `k:num` `p63:num` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x194` `pc + 0x1b0`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = n /\
read X5 s = word i /\
(read X9 s =
if i = 0 then word 0 else word(bigdigit p63 (i - 1))) /\
bignum_from_memory (word_add z (word(8 * i)),k - i) s =
highdigits p63 i /\
bignum_from_memory (word_add t (word(8 * i)),k - i) s =
highdigits n i /\
&(bignum_from_memory(z,i) s):real =
&2 pow (64 * i) * &(bitval(~read CF s)) +
&(lowdigits (2 * p63) i) - &(lowdigits n i)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; BITVAL_CLAUSES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN REAL_ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--7) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[GSYM WORD_ADD; ADD_EQ_0; ARITH_EQ; ADD_SUB] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES] THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[ARITH_RULE `64 * (n + 1) = 64 * n + 64`; REAL_POW_ADD] THEN
MATCH_MP_TAC(REAL_RING
`ee * y:real = w - z
==> --e * c + s = y ==> z + ee * s = (ee * e) * c + w`) THEN
REWRITE_TAC[REAL_SUB_LDISTRIB; REAL_ARITH
`x - y:real = z <=> x = y + z`] THEN
CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN
REWRITE_TAC[REAL_ARITH `(x:real) * &2 pow k = &2 pow k * x`] THEN
AP_TERM_TAC THEN AP_TERM_TAC THEN
CONV_TAC(ONCE_DEPTH_CONV NUM_MOD_CONV) THEN
SIMP_TAC[VAL_WORD_SUBWORD_JOIN; DIMINDEX_64; LE_REFL] THEN
ONCE_REWRITE_TAC[COND_RAND] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND; VAL_WORD_0] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[ADD_CLAUSES] THENL
[REWRITE_TAC[ARITH_RULE `(2 EXP 64 * x) DIV 2 EXP 63 = 2 * x`] THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
TRANS_TAC EQ_TRANS
`(highdigits p63 (i - 1) DIV 2 EXP 63) MOD 2 EXP 64` THEN
CONJ_TAC THENL
[GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [HIGHDIGITS_STEP] THEN
ASM_SIMP_TAC[ARITH_RULE `~(i = 0) ==> i - 1 + 1 = i`; DIV_MOD] THEN
AP_THM_TAC THEN AP_TERM_TAC THEN REWRITE_TAC[GSYM CONG] THEN
MATCH_MP_TAC(NUMBER_RULE
`(a:num == a') (mod n)
==> (e * a + b == e * a' + b) (mod (n * e))`) THEN
REWRITE_TAC[bigdigit; highdigits; CONG; MOD_MOD_EXP_MIN] THEN
CONV_TAC NUM_REDUCE_CONV THEN REFL_TAC;
REWRITE_TAC[highdigits; DIV_DIV; GSYM EXP_ADD] THEN
ASM_SIMP_TAC[bigdigit; EXP; DIV_MULT2; ARITH_EQ; ARITH_RULE
`~(i = 0) ==> 64 * i = SUC(64 * (i - 1) + 63)`]];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF; HIGHDIGITS_ZERO; SUB_REFL] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL]] THEN
GHOST_INTRO_TAC `hi:bool` `read CF` THEN
GHOST_INTRO_TAC `lo:num` `bignum_from_memory(z,k)` THEN
GLOBALIZE_PRECONDITION_TAC THEN
BIGNUM_TERMRANGE_TAC `k:num` `lo:num` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x1c4` `pc + 0x1e0`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
read X5 s = word i /\
bignum_from_memory (word_add z (word(8 * i)),k - i) s =
highdigits lo i /\
bignum_from_memory (word_add t (word(8 * i)),k - i) s =
highdigits n i /\
(p63 < n
==> read X9 s = word_neg(word(bitval(2 * p63 < n))) /\
&(bignum_from_memory(z,i) s):real =
(&(lowdigits lo i) +
&(bitval(2 * p63 < n)) * &(lowdigits n i)) -
&2 pow (64 * i) * &(bitval(read CF s)) /\
&(bignum_from_memory(t,i) s):real =
(&(lowdigits lo i) +
&(bitval(2 * p63 < n)) * &(lowdigits n i)) -
&2 pow (64 * i) * &(bitval(read CF s)))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
RULE_ASSUM_TAC(REWRITE_RULE[VAL_WORD_SUB_EQ_0]) THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (3--5) THEN
ENSURES_FINAL_STATE_TAC THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; BITVAL_CLAUSES] THEN
REWRITE_TAC[REAL_MUL_RZERO; REAL_SUB_REFL; REAL_ADD_LID] THEN
DISCH_TAC THEN REWRITE_TAC[WORD_RULE
`word_sub a b = word_neg c <=> word_add c a = b`] THEN
MP_TAC(GEN `x:int64` (ISPEC `x:int64` WORD_USHR_MSB)) THEN
REWRITE_TAC[DIMINDEX_64] THEN CONV_TAC NUM_REDUCE_CONV THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
REWRITE_TAC[GSYM VAL_EQ; VAL_WORD_BITVAL; VAL_WORD_ADD_CASES] THEN
SIMP_TAC[DIMINDEX_64; BITVAL_BOUND; ARITH_RULE
`b <= 1 /\ c <= 1 ==> b + c < 2 EXP 64`] THEN
SUBGOAL_THEN `2 * p63 < 2 * n /\ 2 * p63 < 2 * 2 EXP (64 * k)`
MP_TAC THENL
[ASM_REWRITE_TAC[LT_MULT_LCANCEL; ARITH_EQ]; ALL_TAC] THEN
SUBGOAL_THEN
`2 * p63 = 2 EXP (64 * k) *
bitval(bit 63 (word(bigdigit p63 (k - 1)):int64)) +
lowdigits (2 * p63) k`
SUBST1_TAC THENL
[MP_TAC(SPECL [`2 * p63`; `k:num`] (CONJUNCT1 HIGH_LOW_DIGITS)) THEN
DISCH_THEN(fun th -> GEN_REWRITE_TAC LAND_CONV [SYM th]) THEN
AP_THM_TAC THEN AP_TERM_TAC THEN AP_TERM_TAC THEN
MP_TAC(ISPEC `word(bigdigit p63 (k - 1)):int64` WORD_USHR_MSB) THEN
REWRITE_TAC[DIMINDEX_64] THEN CONV_TAC NUM_REDUCE_CONV THEN
DISCH_THEN(MP_TAC o SYM o AP_TERM `val:int64->num`) THEN
REWRITE_TAC[VAL_WORD_BITVAL; VAL_WORD_USHR] THEN
DISCH_THEN SUBST1_TAC THEN
SIMP_TAC[VAL_WORD_EQ; BIGDIGIT_BOUND; DIMINDEX_64] THEN
ASM_SIMP_TAC[highdigits; ARITH_RULE
`~(k = 0) ==> 64 * k = SUC(64 * (k - 1) + 63)`] THEN
SIMP_TAC[DIV_MULT2; EXP; ARITH_EQ] THEN
REWRITE_TAC[EXP_ADD; GSYM DIV_DIV] THEN
AP_THM_TAC THEN AP_TERM_TAC THEN
REWRITE_TAC[bigdigit] THEN CONV_TAC SYM_CONV THEN
MATCH_MP_TAC MOD_LT THEN
ASM_SIMP_TAC[RDIV_LT_EQ; EXP_EQ_0; ARITH_EQ; GSYM EXP_ADD] THEN
ASM_SIMP_TAC[ARITH_RULE `~(k = 0) ==> 64 * (k - 1) + 64 = 64 * k`];
ALL_TAC] THEN
ASM_CASES_TAC `bit 63 (word(bigdigit p63 (k - 1)):int64)` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THENL
[ASM_SIMP_TAC[ARITH_RULE `n:num < e ==> ~(e + a < n)`] THEN
UNDISCH_TAC
`&lo:real =
&2 pow (64 * k) * &(bitval(~hi)) +
&(lowdigits (2 * p63) k) - &n` THEN
UNDISCH_TAC `lo < 2 EXP (64 * k)` THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
BOOL_CASES_TAC `hi:bool` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
REAL_ARITH_TAC;
STRIP_TAC THEN AP_TERM_TAC THEN
REWRITE_TAC[NOT_LT; TAUT `(p <=> ~q) <=> (~p <=> q)`] THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN
EXISTS_TAC `64 * k` THEN REWRITE_TAC[GSYM REAL_BITVAL_NOT] THEN
UNDISCH_THEN
`&lo:real =
&2 pow (64 * k) * &(bitval(~hi)) + &(lowdigits (2 * p63) k) - &n`
(SUBST1_TAC o SYM) THEN
ASM_REWRITE_TAC[REAL_OF_NUM_CLAUSES; LE_0]];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hi:int64` `read X9` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--7) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MATCH_MP th)) THEN
ASSUME_TAC th) THEN
ASM_REWRITE_TAC[LOWDIGITS_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[WORD_ADD; WORD_NEG_NEG; VAL_WORD_BITVAL; WORD_BITVAL_EQ_0;
LOWDIGITS_CLAUSES; WORD_NEG_EQ_0; BITVAL_BOUND; NOT_LT] THEN
REWRITE_TAC[WORD_AND_MASK] THEN COND_CASES_TAC THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN ASM_REWRITE_TAC[NOT_LT] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND; VAL_WORD_0;
BITVAL_CLAUSES; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
REWRITE_TAC[REAL_POW_ADD] THEN CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF; HIGHDIGITS_ZERO; SUB_REFL] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL]] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MP th)) THEN
ASSUME_TAC(CONJUNCT2 th) THEN MP_TAC(CONJUNCT1 th)) THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MP th)) THEN
ASSUME_TAC th) THEN
SUBGOAL_THEN `2 EXP (64 * k + 64) MOD n =
(2 * 2 EXP (64 * k + 63) MOD n) MOD n`
SUBST1_TAC THENL
[REWRITE_TAC[ARITH_RULE `n + 64 = SUC(n + 63)`; EXP] THEN
CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
SUBGOAL_THEN `p63:num < n`
(fun th -> FIRST_X_ASSUM(MP_TAC o C MP th) THEN ASSUME_TAC th)
THENL
[ASM_REWRITE_TAC[MOD_LT_EQ] THEN
UNDISCH_TAC `2 EXP (64 * k - 1) <= n` THEN
SIMP_TAC[GSYM NOT_LT; CONTRAPOS_THM; EXP_LT_0] THEN ARITH_TAC;
UNDISCH_THEN `p63 = 2 EXP (64 * k + 63) MOD n` (SUBST1_TAC o SYM)] THEN
STRIP_TAC THEN
ASM_SIMP_TAC[MOD_ADD_CASES; MULT_2; ARITH_RULE
`p63 < n ==> p63 + p63 < 2 * n`] THEN
REWRITE_TAC[GSYM MULT_2] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
MATCH_MP_TAC(MESON[] `x = y /\ x = a ==> x = a /\ y = a`) THEN
CONJ_TAC THENL [ASM_REWRITE_TAC[]; ALL_TAC] THEN
MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN
MAP_EVERY EXISTS_TAC [`64 * k`; `&0:real`] THEN CONJ_TAC THENL
[REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; REAL_OF_NUM_CLAUSES] THEN
REWRITE_TAC[LE_0; BIGNUM_FROM_MEMORY_BOUND];
ALL_TAC] THEN
CONJ_TAC THENL
[MAP_EVERY UNDISCH_TAC [`p63:num < n`; `n < 2 EXP (64 * k)`] THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN ARITH_TAC;
REWRITE_TAC[INTEGER_CLOSED]] THEN
ASM_REWRITE_TAC[] THEN REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
COND_CASES_TAC THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
ASM_SIMP_TAC[GSYM REAL_OF_NUM_SUB; GSYM NOT_LT] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
REWRITE_TAC[ONCE_REWRITE_RULE[REAL_MUL_SYM] real_div] THEN
REWRITE_TAC[REAL_ADD_LDISTRIB; REAL_SUB_LDISTRIB; REAL_MUL_ASSOC] THEN
REWRITE_TAC[REAL_FIELD `inv(&2 pow n) * &2 pow n = (&1:real)`] THEN
CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN
REWRITE_TAC[REAL_ARITH
`--(&2) * e * a + e * b + c:real = e * (b - &2 * a) + c`] THEN
MATCH_MP_TAC INTEGER_ADD THEN
(CONJ_TAC THENL [ALL_TAC; REAL_INTEGER_TAC]) THEN
REWRITE_TAC[REAL_ARITH `inv x * (a - b):real = (a - b) / x`] THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
W(MP_TAC o PART_MATCH (rand o rand) REAL_CONGRUENCE o snd) THEN
REWRITE_TAC[EXP_EQ_0; ARITH_EQ] THEN DISCH_THEN(SUBST1_TAC o SYM) THEN
REWRITE_TAC[CONG; lowdigits] THEN CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
REPEAT(FIRST_X_ASSUM(K ALL_TAC o check (free_in `h:num` o concl))) THEN
REPEAT(FIRST_X_ASSUM(K ALL_TAC o check (free_in `l:num` o concl))) THEN
REWRITE_TAC[TAUT `p ==> q /\ r <=> (p ==> q) /\ (p ==> r)`] THEN
GHOST_INTRO_TAC `r:num` `bignum_from_memory (z,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `r:num` THEN GLOBALIZE_PRECONDITION_TAC THEN
ENSURES_WHILE_PUP_TAC `k:num` `pc + 0x1f0` `pc + 0x25c`
`\i s. (read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X4 s = word(k - i) /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (z,k) s = r /\
(ODD m ==> (2 EXP (64 * k) * val(read X6 s) +
bignum_from_memory(t,k) s ==
2 EXP (64 * (k + i + 1))) (mod m))) /\
(read ZF s <=> i = k)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; ADD_CLAUSES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[VAL_WORD_0; ADD_CLAUSES; MULT_CLAUSES] THEN
ASM_CASES_TAC `m = 1` THEN ASM_SIMP_TAC[CONG_MOD_1; MULT_CLAUSES] THEN
DISCH_TAC THEN MATCH_MP_TAC(NUMBER_RULE
`!m:num. (a == b) (mod n) /\ m divides n ==> (a == b) (mod m)`) THEN
ASM_REWRITE_TAC[LEFT_ADD_DISTRIB; MULT_CLAUSES; CONG_LMOD; CONG_REFL];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `h:num` `\s. val(read X6 s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GHOST_INTRO_TAC `t1:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `t1:num` THEN GLOBALIZE_PRECONDITION_TAC THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x1fc` `pc + 0x220`
`\j s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X4 s = word (k - i) /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (z,k) s = r /\
read X6 s = word h /\
read X5 s = word j /\
bignum_from_memory (word_add z (word(8 * j)),k - j) s =
highdigits r j /\
bignum_from_memory (word_add t (word(8 * j)),k - j) s =
highdigits t1 j /\
read X10 s = word(bigdigit (2 EXP 64 * t1) j) /\
2 EXP (64 * j) * (bitval(read CF s) + val(read X9 s)) +
bignum_from_memory(t,j) s =
lowdigits (2 EXP 64 * t1) j + h * lowdigits r j` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--3) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; LOWDIGITS_0] THEN
REWRITE_TAC[MULT_CLAUSES; SUB_0; BITVAL_CLAUSES; VAL_WORD_0] THEN
REWRITE_TAC[WORD_ADD_0; BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; HIGHDIGITS_0] THEN
REWRITE_TAC[ADD_CLAUSES; MULT_CLAUSES] THEN AP_TERM_TAC THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES; MOD_MULT];
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read X9` THEN
GHOST_INTRO_TAC `prd:int64` `read X10` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - j - 1 = k - (j + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [2;3;5;6] (1--9) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REPEAT CONJ_TAC THENL
[CONV_TAC WORD_RULE;
AP_TERM_TAC THEN REWRITE_TAC[bigdigit] THEN
REWRITE_TAC[ARITH_RULE `64 * (j + 1) = 64 + 64 * j`] THEN
SIMP_TAC[EXP_ADD; DIV_MULT2; EXP_EQ_0; ARITH_EQ];
REWRITE_TAC[LOWDIGITS_CLAUSES]] THEN
GEN_REWRITE_TAC RAND_CONV
[ARITH_RULE `(e * d1 + d0) + c * (e * a1 + a0):num =
e * (c * a1 + d1) + d0 + c * a0`] THEN
FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [SYM th]) THEN
REWRITE_TAC[EXP_ADD; ARITH_RULE `64 * (j + 1) = 64 * j + 64`] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
GEN_REWRITE_TAC LAND_CONV
[TAUT `p /\ q /\ r /\ s <=> p /\ r /\ q /\ s`] THEN
DISCH_THEN(MP_TAC o end_itlist CONJ o DECARRY_RULE o CONJUNCTS) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN CONV_TAC REAL_RING;
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF]] THEN
ENSURES_SEQUENCE_TAC `pc + 0x22c`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X4 s = word (k - i) /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (z,k) s = r /\
2 EXP (64 * k) * (2 EXP 64 * bitval(read CF s) + val(read X6 s)) +
bignum_from_memory(t,k) s =
2 EXP 64 * t1 + h * r` THEN
CONJ_TAC THENL
[GHOST_INTRO_TAC `hup:int64` `read X9` THEN
GHOST_INTRO_TAC `cup:bool` `read CF` THEN
GHOST_INTRO_TAC `tup:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `tup:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
RULE_ASSUM_TAC(REWRITE_RULE[VAL_WORD_SUB_EQ_0]) THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [3] [3] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN DISCH_THEN SUBST1_TAC THEN
ASM_REWRITE_TAC[ARITH_RULE
`e * (a + b + c) + d:num = e * a + e * (c + b) + d`] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[ADD_ASSOC; EQ_ADD_RCANCEL] THEN
REWRITE_TAC[GSYM(CONJUNCT2 LOWDIGITS_CLAUSES)] THEN
MATCH_MP_TAC LOWDIGITS_SELF THEN
REWRITE_TAC[EXP_ADD; ARITH_RULE `64 * (j + 1) = 64 + 64 * j`] THEN
ASM_REWRITE_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ];
GHOST_INTRO_TAC `hup:int64` `read X6` THEN
GHOST_INTRO_TAC `cup:bool` `read CF` THEN
GHOST_INTRO_TAC `tup:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `tup:num` THEN
GLOBALIZE_PRECONDITION_TAC] THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x234` `pc + 0x24c`
`\j s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X4 s = word (k - i) /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (z,k) s = r /\
read X6 s = hup /\
read X8 s = word_neg(word(bitval cup)) /\
read X5 s = word j /\
bignum_from_memory (word_add z (word(8 * j)),k - j) s =
highdigits r j /\
bignum_from_memory (word_add t (word(8 * j)),k - j) s =
highdigits tup j /\
2 EXP (64 * j) * bitval(read CF s) + bignum_from_memory(t,j) s =
lowdigits tup j + bitval(cup) * lowdigits r j` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; LOWDIGITS_0] THEN
REWRITE_TAC[MULT_CLAUSES; SUB_0; BITVAL_CLAUSES; VAL_WORD_0] THEN
REWRITE_TAC[WORD_ADD_0; BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; HIGHDIGITS_0] THEN
REWRITE_TAC[COND_SWAP] THEN COND_CASES_TAC THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC WORD_REDUCE_CONV;
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - j - 1 = k - (j + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
REWRITE_TAC[REAL_ARITH
`&2 pow k * c + z:real = w <=> z = w - &2 pow k * c`] THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; LOWDIGITS_CLAUSES] THEN
REWRITE_TAC[ARITH_RULE `64 * (j + 1) = 64 * j + 64`; REAL_POW_ADD] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
REWRITE_TAC[WORD_AND_MASK] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[VAL_WORD_0; BITVAL_CLAUSES] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
CONV_TAC REAL_RING;
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF]] THEN
GHOST_INTRO_TAC `topc:bool` `read CF` THEN
GHOST_INTRO_TAC `tout:num` `bignum_from_memory(t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `tout:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
RULE_ASSUM_TAC(REWRITE_RULE[VAL_WORD_SUB_EQ_0]) THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [3] (3--4) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> r) /\ q ==> p /\ q /\ r `) THEN
REPEAT CONJ_TAC THENL
[REWRITE_TAC[ARITH_RULE `a - (i + 1) = a - i - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < k ==> 1 <= k - i`];
DISCH_THEN SUBST1_TAC THEN
W(MP_TAC o PART_MATCH (lhand o rand) VAL_WORD_EQ o
lhand o lhand o snd) THEN
REWRITE_TAC[DIMINDEX_64] THEN ANTS_TAC THENL
[ALL_TAC; DISCH_THEN SUBST1_TAC] THEN
MAP_EVERY UNDISCH_TAC [`k < 2 EXP 64`; `i:num < k`] THEN ARITH_TAC;
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MATCH_MP th)) THEN
ASSUME_TAC th)] THEN
REWRITE_TAC[ARITH_RULE
`64 * (k + (i + 1) + 1) = 64 + 64 * (k + i + 1)`] THEN
ONCE_REWRITE_TAC[EXP_ADD] THEN FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP
(NUMBER_RULE `(x:num == a) (mod m)
==> (e * x == y) (mod m) ==> (y == e * a) (mod m)`)) THEN
UNDISCH_TAC `ODD m /\ ~(m = 1) ==> r = 2 EXP (64 * k + 64) MOD n` THEN
ASM_CASES_TAC `m = 1` THEN ASM_REWRITE_TAC[CONG_MOD_1] THEN
DISCH_THEN(ASSUME_TAC o MATCH_MP(MESON[CONG_RMOD; CONG_REFL]
`x = y MOD n ==> (y == x) (mod n)`)) THEN
REWRITE_TAC[ARITH_RULE `e * (ee * h + t):num = e * t + (ee * e) * h`] THEN
REWRITE_TAC[GSYM EXP_ADD] THEN
FIRST_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE
`(e1:num == r) (mod n)
==> m divides n /\ (t + r * h == z) (mod m)
==> (t + e1 * h == z) (mod m)`)) THEN
ASM_REWRITE_TAC[] THEN
SUBGOAL_THEN `val(sum_s3:int64) = val(hup:int64) + bitval topc`
SUBST1_TAC THENL
[ALL_TAC;
MAP_EVERY UNDISCH_TAC
[`2 EXP (64 * k) * (2 EXP 64 * bitval cup + val(hup:int64)) + tup =
2 EXP 64 * t1 + h * r`;
`2 EXP (64 * k) * bitval topc + tout = tup + bitval cup * r`;
`(2 EXP (64 * k + 64) == r) (mod n)`; `(m:num) divides n`] THEN
REWRITE_TAC[EXP_ADD] THEN SPEC_TAC(`2 EXP (64 * k)`,`ee:num`) THEN
SPEC_TAC(`2 EXP 64`,`e:num`) THEN
BOOL_CASES_TAC `cup:bool` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
CONV_TAC NUMBER_RULE] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN MATCH_MP_TAC(ARITH_RULE
`(e * c < e * 1 ==> e * c = 0) /\ z < e
==> e * c + s:num = z ==> s = z`) THEN
REWRITE_TAC[LT_MULT_LCANCEL; MULT_EQ_0; EXP_EQ_0; ARITH_EQ] THEN
REWRITE_TAC[ARITH_RULE `b < 1 ==> b = 0`] THEN
SUBGOAL_THEN `2 EXP (64 * k) * (val(hup:int64) + bitval topc) <
2 EXP (64 * k) * 2 EXP 64`
MP_TAC THENL
[ALL_TAC; REWRITE_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ]] THEN
MAP_EVERY UNDISCH_TAC
[`2 EXP (64 * k) * (2 EXP 64 * bitval cup + val(hup:int64)) + tup =
2 EXP 64 * t1 + h * r`;
`2 EXP (64 * k) * bitval topc + tout = tup + bitval cup * r`] THEN
ASM_CASES_TAC `cup:bool` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THENL
[SUBGOAL_THEN `2 EXP 64 * t1 < 2 EXP 64 * 2 EXP (64 * k) /\
(h + 1) * r <= 2 EXP 64 * 2 EXP (64 * k)`
MP_TAC THENL [ALL_TAC; ARITH_TAC] THEN
ASM_REWRITE_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ] THEN
MATCH_MP_TAC LE_MULT2 THEN
ASM_SIMP_TAC[LT_IMP_LE; ARITH_RULE `x + 1 <= y <=> x < y`];
ALL_TAC] THEN
ASM_CASES_TAC `topc:bool` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THENL
[MAP_EVERY UNDISCH_TAC
[`tout < 2 EXP (64 * k)`; `tup < 2 EXP (64 * k)`] THEN
ARITH_TAC;
SIMP_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ; VAL_BOUND_64]];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[] THEN ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC [1];
ALL_TAC] THEN
* * Initial word modular inverse of tail * *
ENSURES_SEQUENCE_TAC `pc + 0x294`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X7 s = word(bigdigit m 0) /\
bignum_from_memory (mm,k) s = m /\
(ODD m
==> (2 EXP (64 * k) * val (read X6 s) +
bignum_from_memory (t,k) s ==
2 EXP (64 * (2 * k + 1))) (mod m)) /\
(ODD m ==> (m * val(read X11 s) + 1 == 0) (mod (2 EXP 64)))` THEN
CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC [1] THEN
SUBGOAL_THEN `bignum_from_memory(mm,k) s1 = highdigits m 0` MP_TAC THENL
[ASM_REWRITE_TAC[HIGHDIGITS_0; BIGNUM_FROM_MEMORY_BYTES];
GEN_REWRITE_TAC LAND_CONV[BIGNUM_FROM_MEMORY_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; ADD_CLAUSES] THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
REWRITE_TAC[GSYM DIMINDEX_64; WORD_MOD_SIZE] THEN
REWRITE_TAC[DIMINDEX_64] THEN STRIP_TAC] THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (2--5) THEN
SUBGOAL_THEN `ODD m ==> (m * val (read X11 s5) + 1 == 0) (mod 16)`
MP_TAC THENL [ASM_SIMP_TAC[WORD_NEGMODINV_SEED_LEMMA_16]; ALL_TAC] THEN
REABBREV_TAC `x0 = read X11 s5` THEN DISCH_TAC THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (6--14) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_REWRITE_TAC[ARITH_RULE `2 * k + 1 = k + k + 1`] THEN
REWRITE_TAC[VAL_WORD_MUL; VAL_WORD_ADD; VAL_WORD; DIMINDEX_64; CONG] THEN
CONV_TAC MOD_DOWN_CONV THEN REWRITE_TAC[GSYM CONG] THEN
SUBST1_TAC(ARITH_RULE `2 EXP 64 = 16 EXP (2 EXP 4)`) THEN
DISCH_TAC THEN UNDISCH_TAC
`ODD m ==> (m * val(x0:int64) + 1 == 0) (mod 16)` THEN
ASM_REWRITE_TAC[] THEN
SPEC_TAC(`16`,`e:num`) THEN CONV_TAC NUM_REDUCE_CONV THEN
CONV_TAC NUMBER_RULE;
GHOST_INTRO_TAC `w:num` `\s. val(read X11 s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64]] THEN
* * More cleanup and setup of Montgomery multiplier * *
REPEAT(FIRST_X_ASSUM(K ALL_TAC o check (free_in `n:num` o concl))) THEN
GHOST_INTRO_TAC `h:num` `\s. val(read X6 s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GHOST_INTRO_TAC `z1:num` `bignum_from_memory (t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `z1:num` THEN
GLOBALIZE_PRECONDITION_TAC THEN
ABBREV_TAC `q0 = (w * z1) MOD 2 EXP 64` THEN
SUBGOAL_THEN `q0 < 2 EXP 64 /\ val(word q0:int64) = q0`
STRIP_ASSUME_TAC THENL
[EXPAND_TAC "q0" THEN CONJ_TAC THENL [ARITH_TAC; ALL_TAC] THEN
REWRITE_TAC[VAL_WORD; DIMINDEX_64; MOD_MOD_REFL];
ALL_TAC] THEN
* * The prelude of the reduction * *
ENSURES_SEQUENCE_TAC `pc + 0x2b0`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
bignum_from_memory (t,k) s = z1 /\
read X6 s = word h /\
read X11 s = word q0 /\
read X5 s = word 1 /\
read X7 s = word(k - 1) /\
?r0. r0 < 2 EXP 64 /\
2 EXP 64 * (bitval(read CF s) + val(read X9 s)) + r0 =
q0 * bigdigit m 0 + bigdigit z1 0` THEN
CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
SUBGOAL_THEN
`bignum_from_memory(mm,k) s0 = highdigits m 0 /\
bignum_from_memory(t,k) s0 = highdigits z1 0`
MP_TAC THENL
[ASM_REWRITE_TAC[HIGHDIGITS_0; BIGNUM_FROM_MEMORY_BYTES];
GEN_REWRITE_TAC (LAND_CONV o BINOP_CONV)
[BIGNUM_FROM_MEMORY_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; ADD_CLAUSES] THEN
STRIP_TAC] THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [3; 7] (1--7) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[UNDISCH_THEN `(w * z1) MOD 2 EXP 64 = q0` (SUBST1_TAC o SYM) THEN
ONCE_REWRITE_TAC[GSYM WORD_MOD_SIZE] THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
REWRITE_TAC[ADD_CLAUSES; DIMINDEX_64; VAL_WORD] THEN
CONV_TAC MOD_DOWN_CONV THEN REWRITE_TAC[MULT_SYM];
DISCH_THEN SUBST_ALL_TAC] THEN
ASM_REWRITE_TAC[WORD_SUB; ARITH_RULE `1 <= k <=> ~(k = 0)`] THEN
EXISTS_TAC `val(sum_s7:int64)` THEN REWRITE_TAC[VAL_BOUND_64] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REAL_ARITH_TAC;
ALL_TAC] THEN
GHOST_INTRO_TAC `carin:bool` `read CF` THEN
GHOST_INTRO_TAC `mulin:int64` `read X9` THEN
GLOBALIZE_PRECONDITION_TAC THEN
FIRST_X_ASSUM(X_CHOOSE_THEN `r0:num` STRIP_ASSUME_TAC) THEN
ENSURES_SEQUENCE_TAC `pc + 0x2e4`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
read X6 s = word h /\
read X11 s = word q0 /\
2 EXP (64 * k) * (bitval(read CF s) + val(read X9 s)) +
2 EXP 64 * bignum_from_memory (t,k - 1) s + r0 =
lowdigits z1 k + q0 * lowdigits m k` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `k = 1` THENL
[UNDISCH_THEN `k = 1` SUBST_ALL_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC [1] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[SUB_REFL; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES] THEN
REWRITE_TAC[LOWDIGITS_1] THEN ARITH_TAC;
ALL_TAC] THEN
* * The reduction loop " montloop " * *
VAL_INT64_TAC `k - 1` THEN
ENSURES_WHILE_AUP_TAC `1` `k:num` `pc + 0x2b4` `pc + 0x2dc`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
read X6 s = word h /\
read X11 s = word q0 /\
read X5 s = word i /\
bignum_from_memory(word_add t (word (8 * i)),k - i) s =
highdigits z1 i /\
bignum_from_memory(word_add mm (word (8 * i)),k - i) s =
highdigits m i /\
2 EXP (64 * i) * (bitval(read CF s) + val(read X9 s)) +
2 EXP 64 * bignum_from_memory(t,i-1) s + r0 =
lowdigits z1 i + q0 * lowdigits m i` THEN
REPEAT CONJ_TAC THENL
[ASM_REWRITE_TAC[ARITH_RULE `1 < k <=> ~(k = 0 \/ k = 1)`];
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC [1] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
ASM_REWRITE_TAC[ARITH_RULE `k <= 1 <=> k = 0 \/ k = 1`] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_DIV; BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[GSYM highdigits; BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; LOWDIGITS_1] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN
MAP_EVERY VAL_INT64_TAC [`i:num`; `i - 1`] THEN
SUBGOAL_THEN `word_sub (word i) (word 1):int64 = word(i - 1)`
ASSUME_TAC THENL [ASM_REWRITE_TAC[WORD_SUB]; ALL_TAC] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read X9` THEN
MP_TAC(GENL [`x:int64`; `a:num`]
(ISPECL [`x:int64`; `k - i:num`; `a:num`; `i:num`]
BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS)) THEN
ASM_REWRITE_TAC[ARITH_RULE `k - i = 0 <=> ~(i < k)`] THEN
DISCH_THEN(fun th -> ONCE_REWRITE_TAC[th]) THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
UNDISCH_THEN `val(word q0:int64) = q0` (K ALL_TAC) THEN
ABBREV_TAC `i' = i - 1` THEN
SUBGOAL_THEN `i = i' + 1` SUBST_ALL_TAC THENL
[EXPAND_TAC "i'" THEN UNDISCH_TAC `1 <= i` THEN ARITH_TAC;
ALL_TAC] THEN
RULE_ASSUM_TAC(REWRITE_RULE[ARITH_RULE `(i' + 1) + 1 = i' + 2`]) THEN
REWRITE_TAC[ARITH_RULE `(i' + 1) + 1 = i' + 2`] THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [3;4;6;7] (1--10) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
REWRITE_TAC[ARITH_RULE `(m + 2) - 1 = m + 1`] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
SUBGOAL_THEN `i' + 2 = (i' + 1) + 1` MP_TAC THENL
[ARITH_TAC; DISCH_THEN SUBST_ALL_TAC] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ONCE_REWRITE_TAC[LOWDIGITS_CLAUSES] THEN
GEN_REWRITE_TAC RAND_CONV
[ARITH_RULE `(e * d1 + d0) + c * (e * a1 + a0):num =
e * (c * a1 + d1) + d0 + c * a0`] THEN
FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [SYM th]) THEN
REWRITE_TAC[EXP_ADD; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
GEN_REWRITE_TAC LAND_CONV
[TAUT `p /\ q /\ r /\ s <=> p /\ r /\ q /\ s`] THEN
DISCH_THEN(MP_TAC o end_itlist CONJ o DECARRY_RULE o CONJUNCTS) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN
MAP_EVERY VAL_INT64_TAC [`i:num`; `i - 1`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0]];
ASM_SIMP_TAC[LOWDIGITS_SELF]] THEN
ENSURES_SEQUENCE_TAC `pc + 0x2f4`
`\s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
bignum_from_memory (mm,k) s = m /\
?c. read X8 s = word_neg(word(bitval c)) /\
2 EXP 64 * (2 EXP (64 * k) * bitval c +
bignum_from_memory(t,k) s) + r0 =
(2 EXP (64 * k) * h + z1) + q0 * m` THEN
CONJ_TAC THENL
[GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read X9` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
VAL_INT64_TAC `k - 1` THEN
SUBGOAL_THEN `word_sub (word k) (word 1):int64 = word(k - 1)`
ASSUME_TAC THENL
[ASM_REWRITE_TAC[WORD_SUB; ARITH_RULE `1 <= k <=> ~(k = 0)`];
ALL_TAC] THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [1] (1--4) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
EXISTS_TAC `carry_s1:bool` THEN CONJ_TAC THENL
[REWRITE_TAC[COND_SWAP] THEN COND_CASES_TAC THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC WORD_REDUCE_CONV;
ALL_TAC] THEN
SUBGOAL_THEN `8 * k = 8 * ((k - 1) + 1)` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC;
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES]] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[GSYM ADD_ASSOC] THEN FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [SYM th]) THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
SUBGOAL_THEN `64 * k = 64 * (k - 1) + 64` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC; REWRITE_TAC[REAL_POW_ADD]] THEN
CONV_TAC REAL_RING;
ALL_TAC] THEN
GHOST_INTRO_TAC `z2:num` `bignum_from_memory(t,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `z2:num` THEN
GHOST_INTRO_TAC `g8:int64` `read X8` THEN
GLOBALIZE_PRECONDITION_TAC THEN
FIRST_X_ASSUM(X_CHOOSE_THEN `cf:bool`
(CONJUNCTS_THEN2 SUBST_ALL_TAC ASSUME_TAC)) THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x2f8` `pc + 0x310`
`\i s. read X0 s = word k /\
read X1 s = z /\
read X2 s = mm /\
read X3 s = t /\
read X8 s = word_neg (word (bitval cf)) /\
read X5 s = word i /\
bignum_from_memory (word_add t (word(8 * i)),k - i) s =
highdigits z2 i /\
bignum_from_memory (word_add mm (word(8 * i)),k - i) s =
highdigits m i /\
&(bignum_from_memory(z,i) s):real =
&2 pow (64 * i) * &(bitval(~read CF s)) +
&(lowdigits z2 i) - &(bitval cf) * &(lowdigits m i)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ARM_SIM_TAC BIGNUM_AMONTIFIER_EXEC [1] THEN
REWRITE_TAC[WORD_SUB_LZERO; SUB_0; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[WORD_ADD_0; MULT_CLAUSES; BITVAL_CLAUSES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL; LOWDIGITS_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; HIGHDIGITS_0] THEN
REAL_ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
ARM_ACCSTEPS_TAC BIGNUM_AMONTIFIER_EXEC [4] (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[WORD_ADD; WORD_NEG_NEG; VAL_WORD_BITVAL; WORD_BITVAL_EQ_0;
LOWDIGITS_CLAUSES; WORD_NEG_EQ_0; BITVAL_BOUND; NOT_LT] THEN
REWRITE_TAC[WORD_AND_MASK] THEN COND_CASES_TAC THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN ASM_REWRITE_TAC[NOT_LT] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND; VAL_WORD_0;
BITVAL_CLAUSES; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
REWRITE_TAC[REAL_POW_ADD] THEN CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0];
ASM_SIMP_TAC[LOWDIGITS_SELF] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
ARM_STEPS_TAC BIGNUM_AMONTIFIER_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MATCH_MP th)) THEN
ASSUME_TAC th)] THEN
UNDISCH_THEN
`2 EXP 64 * (bitval carin + val(mulin:int64)) + r0 =
q0 * bigdigit m 0 + bigdigit z1 0`
(MP_TAC o AP_TERM `\x. x MOD 2 EXP 64`) THEN
REWRITE_TAC[MOD_MULT_ADD] THEN
UNDISCH_THEN `(w * z1) MOD 2 EXP 64 = q0` (SUBST1_TAC o SYM) THEN
ASM_SIMP_TAC[MOD_LT; GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
CONV_TAC(LAND_CONV MOD_DOWN_CONV) THEN
REWRITE_TAC[ARITH_RULE `(w * z1) * m + z1 = z1 * (m * w + 1)`] THEN
ONCE_REWRITE_TAC[GSYM MOD_MULT_MOD2] THEN
UNDISCH_TAC `(m * w + 1 == 0) (mod (2 EXP 64))` THEN
GEN_REWRITE_TAC LAND_CONV [CONG] THEN DISCH_THEN SUBST1_TAC THEN
CONV_TAC(LAND_CONV MOD_DOWN_CONV) THEN
REWRITE_TAC[MULT_CLAUSES; MOD_0] THEN DISCH_THEN SUBST_ALL_TAC THEN
RULE_ASSUM_TAC(REWRITE_RULE[ADD_CLAUSES]) THEN
MATCH_MP_TAC CONG_MULT_LCANCEL THEN EXISTS_TAC `2 EXP 64` THEN
ASM_REWRITE_TAC[COPRIME_LEXP; COPRIME_2] THEN
REWRITE_TAC[GSYM EXP_ADD; ARITH_RULE `64 + 128 * k = 64 * (2 * k + 1)`] THEN
FIRST_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE
`(x:num == y) (mod n) ==> (z == x) (mod n) ==> (z == y) (mod n)`)) THEN
FIRST_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE
`x:num = y + q * m ==> (z == x) (mod m) ==> (z == y) (mod m)`)) THEN
MATCH_MP_TAC CONG_LMUL THEN
SUBGOAL_THEN `~(read CF s2) <=> z2 < bitval cf * m` SUBST_ALL_TAC THENL
[MATCH_MP_TAC FLAG_FROM_CARRY_LT THEN EXISTS_TAC `64 * k` THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
UNDISCH_THEN
`&(read (memory :> bytes (z,8 * k)) s2) =
&2 pow (64 * k) * &(bitval (~read CF s2)) + &z2 - &(bitval cf) * &m`
(SUBST1_TAC o SYM) THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BOUND; LE_0];
ALL_TAC] THEN
REPEAT(FIRST_X_ASSUM(MP_TAC o check (free_in `cf:bool` o concl))) THEN
REWRITE_TAC[GSYM int_of_num_th; GSYM int_pow_th; GSYM int_mul_th;
GSYM int_add_th; GSYM int_sub_th; GSYM int_eq] THEN
SIMP_TAC[num_congruent; GSYM INT_OF_NUM_CLAUSES] THEN
REWRITE_TAC[INT_OF_NUM_CLAUSES] THEN
BOOL_CASES_TAC `cf:bool` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; MULT_CLAUSES; ADD_CLAUSES; CONJUNCT1 LT] THEN
REWRITE_TAC[INT_CONG_REFL; INT_ADD_LID; INT_SUB_RZERO] THEN
ASM_CASES_TAC `z2:num < m` THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES; MULT_CLAUSES; ADD_CLAUSES] THENL
[REPEAT(DISCH_THEN(K ALL_TAC)) THEN
REWRITE_TAC[GSYM INT_OF_NUM_CLAUSES] THEN CONV_TAC INTEGER_RULE;
MATCH_MP_TAC(TAUT `~p ==> p ==> q`)] THEN
MATCH_MP_TAC(ARITH_RULE `b:num < a ==> ~(a = b)`) THEN
MATCH_MP_TAC(ARITH_RULE
`x + q * m < 2 EXP 64 * ee + 2 EXP 64 * m /\ ~(z2 < m)
==> x + q * m < 2 EXP 64 * (ee + z2)`) THEN
ASM_REWRITE_TAC[] THEN MATCH_MP_TAC LET_ADD2 THEN
FIRST_ASSUM(ASSUME_TAC o MATCH_MP (MESON[ODD] `ODD m ==> ~(m = 0)`)) THEN
ASM_REWRITE_TAC[LT_MULT_RCANCEL] THEN
FIRST_ASSUM(MATCH_MP_TAC o MATCH_MP (ARITH_RULE
`z1:num < ee ==> (h + 1) * ee <= b ==> ee * h + z1 <= b`)) THEN
ASM_REWRITE_TAC[LE_MULT_RCANCEL; EXP_EQ_0; ARITH_EQ] THEN
ASM_REWRITE_TAC[ARITH_RULE `a + 1 <= b <=> a < b`]);;
let BIGNUM_AMONTIFIER_SUBROUTINE_CORRECT = time prove
(`!k z m t n pc returnaddress.
nonoverlapping (z,8 * val k) (t,8 * val k) /\
ALLPAIRS nonoverlapping [(z,8 * val k); (t,8 * val k)]
[(word pc,0x31c); (m,8 * val k)]
==> ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_amontifier_mc /\
read PC s = word pc /\
read X30 s = returnaddress /\
C_ARGUMENTS [k; z; m; t] s /\
bignum_from_memory (m,val k) s = n)
(\s. read PC s = returnaddress /\
(ODD n
==> (bignum_from_memory (z,val k) s ==
2 EXP (128 * val k)) (mod n)))
(MAYCHANGE [PC; X4; X5; X6; X7; X8; X9; X10; X11] ,,
MAYCHANGE [memory :> bytes(z,8 * val k);
memory :> bytes(t,8 * val k)] ,,
MAYCHANGE SOME_FLAGS)`,
ARM_ADD_RETURN_NOSTACK_TAC
BIGNUM_AMONTIFIER_EXEC BIGNUM_AMONTIFIER_CORRECT);;
|
579b024827e5d8750e91c9d2baaa18fcdaf4f87ad6e29421da72ac22ee02de6a | p-swift/projure | zebra_benchmark.clj | (ns clojure-prolog.zebra_benchmark
(:require [criterium.core :refer :all]
[clojure-prolog.core :refer :all]))
(<-- (nextto ?x ?y ?list) (iright ?x ?y ?list))
(<- (nextto ?x ?y ?list) (iright ?y ?x ?list))
(<-- (iright ?left ?right (?left ?right . ?rest)))
(<- (iright ?left ?right (?x . ?rest)) (iright ?left ?right ?rest))
(<- (= ?x ?x))
(<-- (zebra ?h ?w ?z)
;; Each house is of the form:
;; (house nationality pet cigarette drink house-color)
1,10
?
9
2
3
4
5
6
(house ? ? ? ? green) ?h)
7
8
11
(house ? fox ? ? ?) ?h)
12
(house ? horse ? ? ?) ?h)
13
14
15
(house ? ? ? ? blue) ?h)
(member (house ?w ? ? water ?) ?h) ;Q1
Q2
(bench (query ?z (zebra ?h ?w ?z))) | null | https://raw.githubusercontent.com/p-swift/projure/88e0e82714014b372dfcb8cc305298bf8fe4818a/src/test/clojure_prolog/zebra_benchmark.clj | clojure | Each house is of the form:
(house nationality pet cigarette drink house-color)
Q1 | (ns clojure-prolog.zebra_benchmark
(:require [criterium.core :refer :all]
[clojure-prolog.core :refer :all]))
(<-- (nextto ?x ?y ?list) (iright ?x ?y ?list))
(<- (nextto ?x ?y ?list) (iright ?y ?x ?list))
(<-- (iright ?left ?right (?left ?right . ?rest)))
(<- (iright ?left ?right (?x . ?rest)) (iright ?left ?right ?rest))
(<- (= ?x ?x))
(<-- (zebra ?h ?w ?z)
1,10
?
9
2
3
4
5
6
(house ? ? ? ? green) ?h)
7
8
11
(house ? fox ? ? ?) ?h)
12
(house ? horse ? ? ?) ?h)
13
14
15
(house ? ? ? ? blue) ?h)
Q2
(bench (query ?z (zebra ?h ?w ?z))) |
c51e31d22a5c139b9ea4ffb2286c5920b09efb5ed1d5868c837f17d40a072938 | FranklinChen/learn-you-some-erlang | regis.erl | %%% Application wrapper module for regis,
%%% a process registration application.
%%%
%%% This was added because the standard process registry has a precise
%%% meaning of representing VM-global, non-dynamic processes.
%%% However, for this, we needed dynamic names and so we had to write
one ourselves . Of course we could have used ' global ' ( but we
did n't see distributed Erlang yet ) or ' gproc ' ( I do n't want to
depend on external libs for this guide ) , so checkthem out
%%% if you're writing your own app.
-module(regis).
-behaviour(application).
-export([start/2, stop/1]).
-export([register/2, unregister/1, whereis/1, get_names/0]).
start(normal, []) ->
regis_sup:start_link().
stop(_) ->
ok.
register(Name, Pid) -> regis_server:register(Name, Pid).
unregister(Name) -> regis_server:unregister(Name).
whereis(Name) -> regis_server:whereis(Name).
get_names() -> regis_server:get_names().
| null | https://raw.githubusercontent.com/FranklinChen/learn-you-some-erlang/878c8bc2011a12862fe72dd7fdc6c921348c79d6/processquest/apps/regis-1.0.0/src/regis.erl | erlang | Application wrapper module for regis,
a process registration application.
This was added because the standard process registry has a precise
meaning of representing VM-global, non-dynamic processes.
However, for this, we needed dynamic names and so we had to write
if you're writing your own app. | one ourselves . Of course we could have used ' global ' ( but we
did n't see distributed Erlang yet ) or ' gproc ' ( I do n't want to
depend on external libs for this guide ) , so checkthem out
-module(regis).
-behaviour(application).
-export([start/2, stop/1]).
-export([register/2, unregister/1, whereis/1, get_names/0]).
start(normal, []) ->
regis_sup:start_link().
stop(_) ->
ok.
register(Name, Pid) -> regis_server:register(Name, Pid).
unregister(Name) -> regis_server:unregister(Name).
whereis(Name) -> regis_server:whereis(Name).
get_names() -> regis_server:get_names().
|
e1172ae4662b331ff65dd85c9ec35941891d1bb1766193c1345ff710e69e1720 | emina/rosette | ex-2.rkt | #lang rosette
(define-symbolic xs integer? #:length 4)
(define (sum xs)
(cond
[(null? xs) 0]
[(null? (cdr xs)) (car xs)]
[(andmap (curry = (car xs)) (cdr xs))
(* (length xs) (cdr xs))] ; bug: cdr should be car
[else (apply + xs)]))
(verify
(begin
(assume (positive? (sum xs)))
(assert (ormap positive? xs))))
| null | https://raw.githubusercontent.com/emina/rosette/a64e2bccfe5876c5daaf4a17c5a28a49e2fbd501/test/trace/code/ex-2.rkt | racket | bug: cdr should be car | #lang rosette
(define-symbolic xs integer? #:length 4)
(define (sum xs)
(cond
[(null? xs) 0]
[(null? (cdr xs)) (car xs)]
[(andmap (curry = (car xs)) (cdr xs))
[else (apply + xs)]))
(verify
(begin
(assume (positive? (sum xs)))
(assert (ormap positive? xs))))
|
f381a8adf9c95ccd5b8feb07f3c152af4c174c320305f237f7d06e63271b1097 | vmchale/kempe | TyAssign.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TupleSections #
| Constraint - based typing from the presentation in 's book .
module Kempe.TyAssign ( TypeM
, runTypeM
, checkModule
, assignModule
) where
import Control.Composition (thread, (.$))
import Control.Monad (foldM, replicateM, unless, when, zipWithM_)
import Control.Monad.Except (throwError)
import Control.Monad.State.Strict (State, StateT, evalState, get, gets, modify, put, runStateT)
import Data.Bifunctor (bimap, second)
import Data.Foldable (traverse_)
import Data.Functor (void, ($>))
import qualified Data.IntMap as IM
import Data.List.NonEmpty (NonEmpty (..))
import Data.Semigroup ((<>))
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Tuple.Ext (fst3)
import Kempe.AST
import Kempe.Error
import Kempe.Name
import Kempe.Unique
import Lens.Micro (Lens', over)
import Lens.Micro.Mtl (modifying, (.=))
import Prettyprinter (Doc, Pretty (pretty), vsep, (<+>))
import Prettyprinter.Debug
import Prettyprinter.Ext
type TyEnv a = IM.IntMap (StackType a)
data TyState a = TyState { maxU :: Int -- ^ For renamer
, tyEnv :: TyEnv a
, kindEnv :: IM.IntMap Kind
, renames :: IM.IntMap Int
, constructorTypes :: IM.IntMap (StackType a)
, constraints :: S.Set (KempeTy a, KempeTy a) -- Just need equality between simple types? (do have tyapp but yeah)
}
instance Pretty (TyState a) where
pretty (TyState _ te _ r _ cs) =
"type environment:" <#> vsep (prettyBound <$> IM.toList te)
<#> "renames:" <#*> prettyDumpBinds r
<#> "constraints:" <#> prettyConstraints cs
prettyConstraints :: S.Set (KempeTy a, KempeTy a) -> Doc ann
prettyConstraints cs = vsep (prettyEq <$> S.toList cs)
prettyEq :: (KempeTy a, KempeTy a) -> Doc ann
prettyEq (ty, ty') = pretty ty <+> "≡" <+> pretty ty'
prettyDumpBinds :: Pretty b => IM.IntMap b -> Doc a
prettyDumpBinds b = vsep (prettyBind <$> IM.toList b)
emptyStackType :: StackType a
emptyStackType = StackType [] []
maxULens :: Lens' (TyState a) Int
maxULens f s = fmap (\x -> s { maxU = x }) (f (maxU s))
constructorTypesLens :: Lens' (TyState a) (IM.IntMap (StackType a))
constructorTypesLens f s = fmap (\x -> s { constructorTypes = x }) (f (constructorTypes s))
tyEnvLens :: Lens' (TyState a) (TyEnv a)
tyEnvLens f s = fmap (\x -> s { tyEnv = x }) (f (tyEnv s))
kindEnvLens :: Lens' (TyState a) (IM.IntMap Kind)
kindEnvLens f s = fmap (\x -> s { kindEnv = x }) (f (kindEnv s))
renamesLens :: Lens' (TyState a) (IM.IntMap Int)
renamesLens f s = fmap (\x -> s { renames = x }) (f (renames s))
constraintsLens :: Lens' (TyState a) (S.Set (KempeTy a, KempeTy a))
constraintsLens f s = fmap (\x -> s { constraints = x }) (f (constraints s))
dummyName :: T.Text -> TypeM () (Name ())
dummyName n = do
pSt <- gets maxU
Name n (Unique $ pSt + 1) ()
<$ modifying maxULens (+1)
data Kind = Star
| TyCons Kind Kind
deriving (Eq)
type TypeM a = StateT (TyState a) (Either (Error a))
type UnifyMap = IM.IntMap (KempeTy ())
inContext :: UnifyMap -> KempeTy () -> KempeTy ()
inContext um ty'@(TyVar _ (Name _ (Unique i) _)) =
case IM.lookup i um of
Just ty@TyVar{} -> inContext (IM.delete i um) ty -- prevent cyclic lookups
TODO : does this need a case for TyApp - > inContext ?
Just ty -> ty
Nothing -> ty'
inContext _ ty'@TyBuiltin{} = ty'
inContext _ ty'@TyNamed{} = ty'
inContext um (TyApp l ty ty') = TyApp l (inContext um ty) (inContext um ty')
-- | Perform substitutions before handing off to 'unifyMatch'
unifyPrep :: UnifyMap
-> [(KempeTy (), KempeTy ())]
-> Either (Error ()) (IM.IntMap (KempeTy ()))
unifyPrep _ [] = Right mempty
unifyPrep um ((ty, ty'):tys) =
let ty'' = inContext um ty
ty''' = inContext um ty'
in unifyMatch um $ (ty'', ty'''):tys
unifyMatch :: UnifyMap -> [(KempeTy (), KempeTy ())] -> Either (Error ()) (IM.IntMap (KempeTy ()))
unifyMatch _ [] = Right mempty
unifyMatch um ((ty@(TyBuiltin _ b0), ty'@(TyBuiltin _ b1)):tys) | b0 == b1 = unifyPrep um tys
| otherwise = Left (UnificationFailed () ty ty')
unifyMatch um ((ty@(TyNamed _ n0), ty'@(TyNamed _ n1)):tys) | n0 == n1 = unifyPrep um tys
| otherwise = Left (UnificationFailed () (void ty) (void ty'))
unifyMatch um ((ty@(TyNamed _ _), TyVar _ (Name _ (Unique k) _)):tys) = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unifyMatch um ((TyVar _ (Name _ (Unique k) _), ty@(TyNamed _ _)):tys) = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unifyMatch um ((ty@TyBuiltin{}, TyVar _ (Name _ (Unique k) _)):tys) = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unifyMatch um ((TyVar _ (Name _ (Unique k) _), ty@(TyBuiltin _ _)):tys) = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unifyMatch _ ((ty@TyBuiltin{}, ty'@TyNamed{}):_) = Left (UnificationFailed () ty ty')
unifyMatch _ ((ty@TyNamed{}, ty'@TyBuiltin{}):_) = Left (UnificationFailed () ty ty')
unifyMatch _ ((ty@TyBuiltin{}, ty'@TyApp{}):_) = Left (UnificationFailed () ty ty')
unifyMatch _ ((ty@TyNamed{}, ty'@TyApp{}):_) = Left (UnificationFailed () ty ty')
unifyMatch _ ((ty@TyApp{}, ty'@TyBuiltin{}):_) = Left (UnificationFailed () ty ty')
unifyMatch um ((TyVar _ (Name _ (Unique k) _), ty@TyApp{}):tys) = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unifyMatch um ((ty@TyApp{}, TyVar _ (Name _ (Unique k) _)):tys) = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unifyMatch um ((TyApp _ ty ty', TyApp _ ty'' ty'''):tys) = unifyPrep um ((ty, ty'') : (ty', ty''') : tys)
unifyMatch _ ((ty@TyApp{}, ty'@TyNamed{}):_) = Left (UnificationFailed () (void ty) (void ty'))
unifyMatch um ((TyVar _ n@(Name _ (Unique k) _), ty@(TyVar _ n')):tys)
| n == n' = unifyPrep um tys -- a type variable is always equal to itself, don't bother inserting this!
| otherwise = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unify :: [(KempeTy (), KempeTy ())] -> Either (Error ()) (IM.IntMap (KempeTy ()))
unify = unifyPrep IM.empty
unifyM :: S.Set (KempeTy (), KempeTy ()) -> TypeM () (IM.IntMap (KempeTy ()))
unifyM s =
case {-# SCC "unify" #-} unify (S.toList s) of
Right x -> pure x
Left err -> throwError err
-- TODO: take constructor types as an argument?..
runTypeM :: Int -- ^ For renamer
-> TypeM a x -> Either (Error a) (x, Int)
runTypeM maxInt = fmap (second maxU) .
flip runStateT (TyState maxInt mempty mempty mempty mempty S.empty)
typeOfBuiltin :: BuiltinFn -> TypeM () (StackType ())
typeOfBuiltin Drop = do
aN <- dummyName "a"
pure $ StackType [TyVar () aN] []
typeOfBuiltin Swap = do
aN <- dummyName "a"
bN <- dummyName "b"
pure $ StackType [TyVar () aN, TyVar () bN] [TyVar () bN, TyVar () aN]
typeOfBuiltin Dup = do
aN <- dummyName "a"
pure $ StackType [TyVar () aN] [TyVar () aN, TyVar () aN]
typeOfBuiltin IntEq = pure intRel
typeOfBuiltin IntLeq = pure intRel
typeOfBuiltin IntLt = pure intRel
typeOfBuiltin IntMod = pure intBinOp
typeOfBuiltin IntDiv = pure intBinOp
typeOfBuiltin IntPlus = pure intBinOp
typeOfBuiltin IntTimes = pure intBinOp
typeOfBuiltin IntMinus = pure intBinOp
typeOfBuiltin IntShiftR = pure intShift
typeOfBuiltin IntShiftL = pure intBinOp
typeOfBuiltin IntXor = pure intBinOp
typeOfBuiltin WordXor = pure wordBinOp
typeOfBuiltin WordPlus = pure wordBinOp
typeOfBuiltin WordTimes = pure wordBinOp
typeOfBuiltin WordShiftR = pure wordShift
typeOfBuiltin WordShiftL = pure wordShift
typeOfBuiltin IntGeq = pure intRel
typeOfBuiltin IntNeq = pure intRel
typeOfBuiltin IntGt = pure intRel
typeOfBuiltin WordMinus = pure wordBinOp
typeOfBuiltin WordDiv = pure wordBinOp
typeOfBuiltin WordMod = pure wordBinOp
typeOfBuiltin And = pure boolOp
typeOfBuiltin Or = pure boolOp
typeOfBuiltin Xor = pure boolOp
typeOfBuiltin IntNeg = pure $ StackType [TyBuiltin () TyInt] [TyBuiltin () TyInt]
typeOfBuiltin Popcount = pure $ StackType [TyBuiltin () TyWord] [TyBuiltin () TyInt]
boolOp :: StackType ()
boolOp = StackType [TyBuiltin () TyBool, TyBuiltin () TyBool] [TyBuiltin () TyBool]
intRel :: StackType ()
intRel = StackType [TyBuiltin () TyInt, TyBuiltin () TyInt] [TyBuiltin () TyBool]
intBinOp :: StackType ()
intBinOp = StackType [TyBuiltin () TyInt, TyBuiltin () TyInt] [TyBuiltin () TyInt]
intShift :: StackType ()
intShift = StackType [TyBuiltin () TyInt, TyBuiltin () TyInt] [TyBuiltin () TyInt]
wordBinOp :: StackType ()
wordBinOp = StackType [TyBuiltin () TyWord, TyBuiltin () TyWord] [TyBuiltin () TyWord]
wordShift :: StackType ()
wordShift = StackType [TyBuiltin () TyWord, TyBuiltin () TyWord] [TyBuiltin () TyWord]
tyLookup :: Name a -> TypeM a (StackType a)
tyLookup n@(Name _ (Unique i) l) = do
st <- gets tyEnv
case IM.lookup i st of
Just ty -> pure ty
Nothing -> throwError $ PoorScope l n
consLookup :: TyName a -> TypeM a (StackType a)
consLookup tn@(Name _ (Unique i) l) = do
st <- gets constructorTypes
case IM.lookup i st of
Just ty -> pure ty
Nothing -> throwError $ PoorScope l tn
expandType 1
dipify :: StackType () -> TypeM () (StackType ())
dipify (StackType is os) = do
n <- dummyName "a"
pure $ StackType (is ++ [TyVar () n]) (os ++ [TyVar () n])
tyLeaf :: (Pattern b a, [Atom b a]) -> TypeM () (StackType ())
tyLeaf (p, as) = do
tyP <- tyPattern p
tyA <- tyAtoms as
catTypes tyP tyA
assignCase :: (Pattern b a, [Atom b a]) -> TypeM () (StackType (), Pattern (StackType ()) (StackType ()), [Atom (StackType ()) (StackType ())])
assignCase (p, as) = do
(tyP, p') <- assignPattern p
(as', tyA) <- assignAtoms as
(,,) <$> catTypes tyP tyA <*> pure p' <*> pure as'
tyAtom :: Atom b a -> TypeM () (StackType ())
tyAtom (AtBuiltin _ b) = typeOfBuiltin b
tyAtom BoolLit{} = pure $ StackType [] [TyBuiltin () TyBool]
tyAtom IntLit{} = pure $ StackType [] [TyBuiltin () TyInt]
tyAtom Int8Lit{} = pure $ StackType [] [TyBuiltin () TyInt8 ]
tyAtom WordLit{} = pure $ StackType [] [TyBuiltin () TyWord]
tyAtom (AtName _ n) = renameStack =<< tyLookup (void n)
tyAtom (Dip _ as) = dipify =<< tyAtoms as
tyAtom (AtCons _ tn) = renameStack =<< consLookup (void tn)
tyAtom (If _ as as') = do
tys <- tyAtoms as
tys' <- tyAtoms as'
(StackType ins out) <- mergeStackTypes tys tys'
pure $ StackType (ins ++ [TyBuiltin () TyBool]) out
tyAtom (Case _ ls) = do
tyLs <- traverse tyLeaf ls
TODO : one - pass fold ?
mergeMany tyLs
assignAtom :: Atom b a -> TypeM () (StackType (), Atom (StackType ()) (StackType ()))
assignAtom (AtBuiltin _ b) = do { ty <- typeOfBuiltin b ; pure (ty, AtBuiltin ty b) }
assignAtom (BoolLit _ b) =
let sTy = StackType [] [TyBuiltin () TyBool]
in pure (sTy, BoolLit sTy b)
assignAtom (IntLit _ i) =
let sTy = StackType [] [TyBuiltin () TyInt]
in pure (sTy, IntLit sTy i)
assignAtom (Int8Lit _ i) =
let sTy = StackType [] [TyBuiltin () TyInt8]
in pure (sTy, Int8Lit sTy i)
assignAtom (WordLit _ u) =
let sTy = StackType [] [TyBuiltin () TyWord]
in pure (sTy, WordLit sTy u)
assignAtom (AtName _ n) = do
sTy <- renameStack =<< tyLookup (void n)
pure (sTy, AtName sTy (n $> sTy))
assignAtom (AtCons _ tn) = do
sTy <- renameStack =<< consLookup (void tn)
pure (sTy, AtCons sTy (tn $> sTy))
assignAtom (Dip _ as) = do { (as', ty) <- assignAtoms as ; tyDipped <- dipify ty ; pure (tyDipped, Dip tyDipped as') }
assignAtom (If _ as0 as1) = do
(as0', tys) <- assignAtoms as0
(as1', tys') <- assignAtoms as1
(StackType ins out) <- mergeStackTypes tys tys'
let resType = StackType (ins ++ [TyBuiltin () TyBool]) out
pure (resType, If resType as0' as1')
assignAtom (Case _ ls) = do
lRes <- traverse assignCase ls
resType <- mergeMany (fst3 <$> lRes)
let newLeaves = fmap dropFst lRes
pure (resType, Case resType newLeaves)
where dropFst (_, y, z) = (y, z)
assignAtoms :: [Atom b a] -> TypeM () ([Atom (StackType ()) (StackType ())], StackType ())
assignAtoms [] = pure ([], emptyStackType)
assignAtoms [a] = do
(ty, a') <- assignAtom a
pure ([a'], ty)
assignAtoms (a:as) = do
(ty, a') <- assignAtom a
(as', ty') <- assignAtoms as
(a':as' ,) <$> catTypes ty ty'
tyAtoms :: [Atom b a] -> TypeM () (StackType ())
tyAtoms [] = pure emptyStackType
tyAtoms [a] = tyAtom a
tyAtoms (a:as) = do
ty <- tyAtom a
tys <- tyAtoms as
catTypes ty tys
-- from size,
mkHKT :: Int -> Kind
mkHKT 0 = Star
mkHKT i = TyCons (mkHKT $ i - 1) Star
tyInsertLeaf :: Name b -- ^ type being declared
-> S.Set (Name b) -> (TyName a, [KempeTy b]) -> TypeM () ()
tyInsertLeaf n@(Name _ (Unique k) _) vars (Name _ (Unique i) _, ins) | S.null vars =
modifying constructorTypesLens (IM.insert i (voidStackType $ StackType ins [TyNamed undefined n])) *>
modifying kindEnvLens (IM.insert k Star)
| otherwise =
let ty = voidStackType $ StackType ins [app (TyNamed undefined n) (S.toList vars)] in
modifying constructorTypesLens (IM.insert i ty) *>
modifying kindEnvLens (IM.insert k (mkHKT $ S.size vars))
assignTyLeaf :: Name b
-> S.Set (Name b)
-> (TyName a, [KempeTy b])
-> TypeM () (TyName (StackType ()), [KempeTy ()])
assignTyLeaf n@(Name _ (Unique k) _) vars (tn@(Name _ (Unique i) _), ins) | S.null vars =
let ty = voidStackType $ StackType ins [TyNamed undefined n] in
modifying constructorTypesLens (IM.insert i ty) *>
modifying kindEnvLens (IM.insert k Star) $>
(tn $> ty, fmap void ins)
| otherwise =
let ty = voidStackType $ StackType ins [app (TyNamed undefined n) (S.toList vars)] in
modifying constructorTypesLens (IM.insert i ty) *>
modifying kindEnvLens (IM.insert k (mkHKT $ S.size vars)) $>
(tn $> ty, fmap void ins)
app :: KempeTy a -> [Name a] -> KempeTy a
app = foldr (\n ty -> TyApp undefined ty (TyVar undefined n))
kindLookup :: TyName a -> TypeM a Kind
kindLookup n@(Name _ (Unique i) l) = do
st <- gets kindEnv
case IM.lookup i st of
Just k -> pure k
Nothing -> throwError $ PoorScope l n
kindOf :: KempeTy a -> TypeM a Kind
kindOf TyBuiltin{} = pure Star
kindOf (TyNamed _ tn) = kindLookup tn
kindOf TyVar{} = pure Star
kindOf tyErr@(TyApp l ty ty') = do
k <- kindOf ty
k' <- kindOf ty'
case k of
TyCons k'' k''' -> unless (k' == k''') (throwError (IllKinded l tyErr)) $> k''
_ -> throwError (IllKinded l tyErr)
assignDecl :: KempeDecl a c b -> TypeM () (KempeDecl () (StackType ()) (StackType ()))
assignDecl (TyDecl _ tn ns ls) = TyDecl () (void tn) (void <$> ns) <$> traverse (assignTyLeaf tn (S.fromList ns)) ls
assignDecl (FunDecl _ n ins os a) = do
traverse_ kindOf (void <$> ins ++ os)
sig <- renameStack $ voidStackType $ StackType ins os
(as, inferred) <- assignAtoms a
reconcile <- mergeStackTypes sig inferred
when (inferred `lessGeneral` sig) $
throwError $ LessGeneral () sig inferred
pure $ FunDecl reconcile (n $> reconcile) (void <$> ins) (void <$> os) as
assignDecl (ExtFnDecl _ n ins os cn) = do
traverse_ kindOf (void <$> ins ++ os)
unless (length os <= 1) $
throwError $ InvalidCImport () (void n)
let sig = voidStackType $ StackType ins os
pure $ ExtFnDecl sig (n $> sig) (void <$> ins) (void <$> os) cn
assignDecl (Export _ abi n) = do
ty@(StackType _ os) <- tyLookup (void n)
unless (abi == Kabi || length os <= 1) $
throwError $ InvalidCExport () (void n)
Export ty abi <$> assignName n
-- don't need to rename cuz it's only for exports (in theory)
assignName :: Name a -> TypeM () (Name (StackType ()))
assignName n = do { ty <- tyLookup (void n) ; pure (n $> ty) }
tyHeader :: KempeDecl a c b -> TypeM () ()
tyHeader Export{} = pure ()
tyHeader (FunDecl _ (Name _ (Unique i) _) ins out _) = do
let sig = voidStackType $ StackType ins out
modifying tyEnvLens (IM.insert i sig)
tyHeader (ExtFnDecl _ n@(Name _ (Unique i) _) ins os _) = do
unless (length os <= 1) $
throwError $ InvalidCImport () (void n)
unless (null $ freeVars (ins ++ os)) $
throwError $ TyVarExt () (void n)
let sig = voidStackType $ StackType ins os -- no free variables allowed in c functions
modifying tyEnvLens (IM.insert i sig)
tyHeader TyDecl{} = pure ()
type Vars a = IM.IntMap (Name a)
-- TODO: do we want strict or lazy?
type EqState a = State (Vars a)
-- need to check stack types are less general up to "alpha-equivalence"
-- (implicit forall with every new var! in a stack type)
--
-- Basically the inferred type has to check against the type in the signature.
-- Which I'm not sure this does; it should be better-founded with an
-- explanation of why it works (I'm not sure it works)
lessGeneral :: StackType a -- ^ Inferred type
-> StackType a -- ^ Type from signature
-> Bool
lessGeneral (StackType is os) (StackType is' os') =
flip evalState mempty $
if il > il' || ol > ol'
then (||) <$> lessGenerals trimIs is' <*> lessGenerals trimOs os'
else (||) <$> lessGenerals is trimIs' <*> lessGenerals os trimOs'
where il = length is
il' = length is'
ol = length os
ol' = length os'
trimIs = drop (il-il') is
trimIs' = drop (il'-il) is'
trimOs = drop (ol-ol') os
trimOs' = drop (ol'-ol) os'
lessGeneralAtom :: KempeTy a -> KempeTy a -> EqState a Bool
lessGeneralAtom TyBuiltin{} TyVar{} = pure True
lessGeneralAtom TyApp{} TyVar{} = pure True
lessGeneralAtom (TyApp _ ty ty') (TyApp _ ty'' ty''') = (||) <$> lessGeneralAtom ty ty'' <*> lessGeneralAtom ty' ty''' -- lazy pattern match?
lessGeneralAtom _ _ = pure False
lessGenerals :: [KempeTy a] -> [KempeTy a] -> EqState a Bool
lessGenerals [] [] = pure False
lessGenerals ((TyVar _ n):tys) ((TyVar _ n'):tys') = do
st <- get
let i = unUnique $ unique n
case IM.lookup i st of
Nothing ->
modify (IM.insert i n') *>
we can skip checking ty ` lessGeneral ` ty ' at the first site
Just n'' ->
(n'' /= n' ||) <$> lessGenerals tys tys'
lessGenerals (ty:tys) (ty':tys') = (||) <$> lessGeneralAtom ty ty' <*> lessGenerals tys tys'
tyInsert :: KempeDecl a c b -> TypeM () ()
tyInsert (TyDecl _ tn ns ls) = traverse_ (tyInsertLeaf tn (S.fromList ns)) ls
tyInsert (FunDecl _ _ ins out as) = do
traverse_ kindOf (void <$> ins ++ out) -- FIXME: this gives sketchy results?
sig <- renameStack $ voidStackType $ StackType ins out
inferred <- tyAtoms as
_ <- mergeStackTypes sig inferred
when (inferred `lessGeneral` sig) $
throwError $ LessGeneral () sig inferred
tyInsert (ExtFnDecl _ _ ins outs _) = traverse_ kindOf (void <$> ins ++ outs)
tyInsert Export{} = pure ()
tyModule :: Declarations a c b -> TypeM () ()
tyModule m = traverse_ tyHeader m *> traverse_ tyInsert m
checkModule :: Declarations a c b -> TypeM () ()
checkModule m = tyModule m <* (unifyM =<< gets constraints)
assignModule :: Declarations a c b -> TypeM () (Declarations () (StackType ()) (StackType ()))
assignModule m = {-# SCC "assignModule" #-} do
{-# SCC "tyHeader" #-} traverse_ tyHeader m
m' <- traverse assignDecl m
backNames <- unifyM =<< gets constraints
pure (fmap (bimap .$ substConstraintsStack backNames) m')
-- Make sure you don't have cycles in the renames map!
replaceUnique :: Unique -> TypeM a Unique
replaceUnique u@(Unique i) = do
rSt <- gets renames
case IM.lookup i rSt of
Nothing -> pure u
Just j -> replaceUnique (Unique j)
renameIn :: KempeTy a -> TypeM a (KempeTy a)
renameIn b@TyBuiltin{} = pure b
renameIn n@TyNamed{} = pure n
renameIn (TyApp l ty ty') = TyApp l <$> renameIn ty <*> renameIn ty'
renameIn (TyVar l (Name t u l')) = do
u' <- replaceUnique u
pure $ TyVar l (Name t u' l')
-- has to use the max-iest maximum so we can't use withState
withTyState :: (TyState a -> TyState a) -> TypeM a x -> TypeM a x
withTyState modSt act = do
preSt <- get
modify modSt
res <- act
postMax <- gets maxU
put preSt
maxULens .= postMax
pure res
withName :: Name a -> TypeM a (Name a, TyState a -> TyState a)
withName (Name t (Unique i) l) = do
m <- gets maxU
let newUniq = m+1
maxULens .= newUniq
pure (Name t (Unique newUniq) l, over renamesLens (IM.insert i (m+1)))
-- freshen the names in a stack so there aren't overlaps in quanitified variables
renameStack :: StackType a -> TypeM a (StackType a)
renameStack (StackType ins outs) = do
newQs <- traverse withName (S.toList $ freeVars ins <> freeVars outs)
let (_, localRenames) = unzip newQs
newBinds = thread localRenames
withTyState newBinds $
StackType <$> traverse renameIn ins <*> traverse renameIn outs
mergeStackTypes :: StackType () -> StackType () -> TypeM () (StackType ())
mergeStackTypes st0@(StackType i0 o0) st1@(StackType i1 o1) = do
let li0 = length i0
li1 = length i1
toExpand = max (abs (li0 - li1)) (abs (length o0 - length o1))
(StackType ins os) <- (if li0 < li1 then expandType toExpand else pure) st0
(StackType ins' os') <- (if li1 < li0 then expandType toExpand else pure) st1
when ((length ins /= length ins') || (length os /= length os')) $
throwError $ MismatchedLengths () st0 st1
zipWithM_ pushConstraint ins ins'
zipWithM_ pushConstraint os os'
pure $ StackType ins os
tyPattern :: Pattern b a -> TypeM () (StackType ())
tyPattern PatternWildcard{} = do
aN <- dummyName "a"
pure $ StackType [TyVar () aN] []
tyPattern PatternInt{} = pure $ StackType [TyBuiltin () TyInt] []
tyPattern PatternBool{} = pure $ StackType [TyBuiltin () TyBool] []
tyPattern (PatternCons _ tn) = renameStack . flipStackType =<< consLookup (void tn)
assignPattern :: Pattern b a -> TypeM () (StackType (), Pattern (StackType ()) (StackType ()))
assignPattern (PatternInt _ i) =
let sTy = StackType [TyBuiltin () TyInt] []
in pure (sTy, PatternInt sTy i)
assignPattern (PatternBool _ i) =
let sTy = StackType [TyBuiltin () TyBool] []
in pure (sTy, PatternBool sTy i)
assignPattern (PatternCons _ tn) = do { ty <- renameStack . flipStackType =<< consLookup (void tn) ; pure (ty, PatternCons ty (tn $> ty)) }
assignPattern PatternWildcard{} = do
aN <- dummyName "a"
let resType = StackType [TyVar () aN] []
pure (resType, PatternWildcard resType)
mergeMany :: NonEmpty (StackType ()) -> TypeM () (StackType ())
mergeMany (t :| ts) = foldM mergeStackTypes t ts
-- assumes they have been renamed...
pushConstraint :: Ord a => KempeTy a -> KempeTy a -> TypeM a ()
pushConstraint ty ty' =
modifying constraintsLens (S.insert (ty, ty'))
expandType :: Int -> StackType () -> TypeM () (StackType ())
expandType n (StackType i o) = do
newVars <- replicateM n (dummyName "a")
let newTy = TyVar () <$> newVars
pure $ StackType (newTy ++ i) (newTy ++ o)
substConstraints :: IM.IntMap (KempeTy a) -> KempeTy a -> KempeTy a
substConstraints _ ty@TyNamed{} = ty
substConstraints _ ty@TyBuiltin{} = ty
substConstraints tys ty@(TyVar _ (Name _ (Unique k) _)) =
case IM.lookup k tys of
Just ty'@TyVar{} -> substConstraints (IM.delete k tys) ty' -- TODO: this is to prevent cyclic lookups: is it right?
Just (TyApp l ty0 ty1) -> let tys' = IM.delete k tys in TyApp l (substConstraints tys' ty0) (substConstraints tys' ty1)
Just ty' -> ty'
Nothing -> ty
substConstraints tys (TyApp l ty ty') =
TyApp l (substConstraints tys ty) (substConstraints tys ty')
substConstraintsStack :: IM.IntMap (KempeTy a) -> StackType a -> StackType a
substConstraintsStack tys (StackType is os) = {-# SCC "substConstraintsStack" #-}
let is' = substConstraints tys <$> is
os' = substConstraints tys <$> os
in StackType is' os'
-- do renaming before this
| Given @x@ and @y@ , return the ' StackType ' of @x y@
catTypes :: StackType () -- ^ @x@
-> StackType () -- ^ @y@
-> TypeM () (StackType ())
catTypes st0@(StackType _ osX) (StackType insY osY) = do
let lY = length insY
lDiff = lY - length osX
-- all of the "ins" of y have to come from x, so we expand x as needed
(StackType insX osX') <- if lDiff > 0
then expandType lDiff st0
else pure st0
zip the last ( length insY ) of osX ' with insY
zipWithM_ pushConstraint (drop (length osX' - lY) osX') insY -- TODO splitAt
pure $ StackType insX (take (length osX' - lY) osX' ++ osY)
| null | https://raw.githubusercontent.com/vmchale/kempe/23d59cb9343902aae33140e2b68ac0e4ab0a60a0/src/Kempe/TyAssign.hs | haskell | # LANGUAGE OverloadedStrings #
^ For renamer
Just need equality between simple types? (do have tyapp but yeah)
prevent cyclic lookups
| Perform substitutions before handing off to 'unifyMatch'
a type variable is always equal to itself, don't bother inserting this!
# SCC "unify" #
TODO: take constructor types as an argument?..
^ For renamer
from size,
^ type being declared
don't need to rename cuz it's only for exports (in theory)
no free variables allowed in c functions
TODO: do we want strict or lazy?
need to check stack types are less general up to "alpha-equivalence"
(implicit forall with every new var! in a stack type)
Basically the inferred type has to check against the type in the signature.
Which I'm not sure this does; it should be better-founded with an
explanation of why it works (I'm not sure it works)
^ Inferred type
^ Type from signature
lazy pattern match?
FIXME: this gives sketchy results?
# SCC "assignModule" #
# SCC "tyHeader" #
Make sure you don't have cycles in the renames map!
has to use the max-iest maximum so we can't use withState
freshen the names in a stack so there aren't overlaps in quanitified variables
assumes they have been renamed...
TODO: this is to prevent cyclic lookups: is it right?
# SCC "substConstraintsStack" #
do renaming before this
^ @x@
^ @y@
all of the "ins" of y have to come from x, so we expand x as needed
TODO splitAt | # LANGUAGE TupleSections #
| Constraint - based typing from the presentation in 's book .
module Kempe.TyAssign ( TypeM
, runTypeM
, checkModule
, assignModule
) where
import Control.Composition (thread, (.$))
import Control.Monad (foldM, replicateM, unless, when, zipWithM_)
import Control.Monad.Except (throwError)
import Control.Monad.State.Strict (State, StateT, evalState, get, gets, modify, put, runStateT)
import Data.Bifunctor (bimap, second)
import Data.Foldable (traverse_)
import Data.Functor (void, ($>))
import qualified Data.IntMap as IM
import Data.List.NonEmpty (NonEmpty (..))
import Data.Semigroup ((<>))
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Tuple.Ext (fst3)
import Kempe.AST
import Kempe.Error
import Kempe.Name
import Kempe.Unique
import Lens.Micro (Lens', over)
import Lens.Micro.Mtl (modifying, (.=))
import Prettyprinter (Doc, Pretty (pretty), vsep, (<+>))
import Prettyprinter.Debug
import Prettyprinter.Ext
type TyEnv a = IM.IntMap (StackType a)
, tyEnv :: TyEnv a
, kindEnv :: IM.IntMap Kind
, renames :: IM.IntMap Int
, constructorTypes :: IM.IntMap (StackType a)
}
instance Pretty (TyState a) where
pretty (TyState _ te _ r _ cs) =
"type environment:" <#> vsep (prettyBound <$> IM.toList te)
<#> "renames:" <#*> prettyDumpBinds r
<#> "constraints:" <#> prettyConstraints cs
prettyConstraints :: S.Set (KempeTy a, KempeTy a) -> Doc ann
prettyConstraints cs = vsep (prettyEq <$> S.toList cs)
prettyEq :: (KempeTy a, KempeTy a) -> Doc ann
prettyEq (ty, ty') = pretty ty <+> "≡" <+> pretty ty'
prettyDumpBinds :: Pretty b => IM.IntMap b -> Doc a
prettyDumpBinds b = vsep (prettyBind <$> IM.toList b)
emptyStackType :: StackType a
emptyStackType = StackType [] []
maxULens :: Lens' (TyState a) Int
maxULens f s = fmap (\x -> s { maxU = x }) (f (maxU s))
constructorTypesLens :: Lens' (TyState a) (IM.IntMap (StackType a))
constructorTypesLens f s = fmap (\x -> s { constructorTypes = x }) (f (constructorTypes s))
tyEnvLens :: Lens' (TyState a) (TyEnv a)
tyEnvLens f s = fmap (\x -> s { tyEnv = x }) (f (tyEnv s))
kindEnvLens :: Lens' (TyState a) (IM.IntMap Kind)
kindEnvLens f s = fmap (\x -> s { kindEnv = x }) (f (kindEnv s))
renamesLens :: Lens' (TyState a) (IM.IntMap Int)
renamesLens f s = fmap (\x -> s { renames = x }) (f (renames s))
constraintsLens :: Lens' (TyState a) (S.Set (KempeTy a, KempeTy a))
constraintsLens f s = fmap (\x -> s { constraints = x }) (f (constraints s))
dummyName :: T.Text -> TypeM () (Name ())
dummyName n = do
pSt <- gets maxU
Name n (Unique $ pSt + 1) ()
<$ modifying maxULens (+1)
data Kind = Star
| TyCons Kind Kind
deriving (Eq)
type TypeM a = StateT (TyState a) (Either (Error a))
type UnifyMap = IM.IntMap (KempeTy ())
inContext :: UnifyMap -> KempeTy () -> KempeTy ()
inContext um ty'@(TyVar _ (Name _ (Unique i) _)) =
case IM.lookup i um of
TODO : does this need a case for TyApp - > inContext ?
Just ty -> ty
Nothing -> ty'
inContext _ ty'@TyBuiltin{} = ty'
inContext _ ty'@TyNamed{} = ty'
inContext um (TyApp l ty ty') = TyApp l (inContext um ty) (inContext um ty')
unifyPrep :: UnifyMap
-> [(KempeTy (), KempeTy ())]
-> Either (Error ()) (IM.IntMap (KempeTy ()))
unifyPrep _ [] = Right mempty
unifyPrep um ((ty, ty'):tys) =
let ty'' = inContext um ty
ty''' = inContext um ty'
in unifyMatch um $ (ty'', ty'''):tys
unifyMatch :: UnifyMap -> [(KempeTy (), KempeTy ())] -> Either (Error ()) (IM.IntMap (KempeTy ()))
unifyMatch _ [] = Right mempty
unifyMatch um ((ty@(TyBuiltin _ b0), ty'@(TyBuiltin _ b1)):tys) | b0 == b1 = unifyPrep um tys
| otherwise = Left (UnificationFailed () ty ty')
unifyMatch um ((ty@(TyNamed _ n0), ty'@(TyNamed _ n1)):tys) | n0 == n1 = unifyPrep um tys
| otherwise = Left (UnificationFailed () (void ty) (void ty'))
unifyMatch um ((ty@(TyNamed _ _), TyVar _ (Name _ (Unique k) _)):tys) = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unifyMatch um ((TyVar _ (Name _ (Unique k) _), ty@(TyNamed _ _)):tys) = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unifyMatch um ((ty@TyBuiltin{}, TyVar _ (Name _ (Unique k) _)):tys) = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unifyMatch um ((TyVar _ (Name _ (Unique k) _), ty@(TyBuiltin _ _)):tys) = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unifyMatch _ ((ty@TyBuiltin{}, ty'@TyNamed{}):_) = Left (UnificationFailed () ty ty')
unifyMatch _ ((ty@TyNamed{}, ty'@TyBuiltin{}):_) = Left (UnificationFailed () ty ty')
unifyMatch _ ((ty@TyBuiltin{}, ty'@TyApp{}):_) = Left (UnificationFailed () ty ty')
unifyMatch _ ((ty@TyNamed{}, ty'@TyApp{}):_) = Left (UnificationFailed () ty ty')
unifyMatch _ ((ty@TyApp{}, ty'@TyBuiltin{}):_) = Left (UnificationFailed () ty ty')
unifyMatch um ((TyVar _ (Name _ (Unique k) _), ty@TyApp{}):tys) = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unifyMatch um ((ty@TyApp{}, TyVar _ (Name _ (Unique k) _)):tys) = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unifyMatch um ((TyApp _ ty ty', TyApp _ ty'' ty'''):tys) = unifyPrep um ((ty, ty'') : (ty', ty''') : tys)
unifyMatch _ ((ty@TyApp{}, ty'@TyNamed{}):_) = Left (UnificationFailed () (void ty) (void ty'))
unifyMatch um ((TyVar _ n@(Name _ (Unique k) _), ty@(TyVar _ n')):tys)
| otherwise = IM.insert k ty <$> unifyPrep (IM.insert k ty um) tys
unify :: [(KempeTy (), KempeTy ())] -> Either (Error ()) (IM.IntMap (KempeTy ()))
unify = unifyPrep IM.empty
unifyM :: S.Set (KempeTy (), KempeTy ()) -> TypeM () (IM.IntMap (KempeTy ()))
unifyM s =
Right x -> pure x
Left err -> throwError err
-> TypeM a x -> Either (Error a) (x, Int)
runTypeM maxInt = fmap (second maxU) .
flip runStateT (TyState maxInt mempty mempty mempty mempty S.empty)
typeOfBuiltin :: BuiltinFn -> TypeM () (StackType ())
typeOfBuiltin Drop = do
aN <- dummyName "a"
pure $ StackType [TyVar () aN] []
typeOfBuiltin Swap = do
aN <- dummyName "a"
bN <- dummyName "b"
pure $ StackType [TyVar () aN, TyVar () bN] [TyVar () bN, TyVar () aN]
typeOfBuiltin Dup = do
aN <- dummyName "a"
pure $ StackType [TyVar () aN] [TyVar () aN, TyVar () aN]
typeOfBuiltin IntEq = pure intRel
typeOfBuiltin IntLeq = pure intRel
typeOfBuiltin IntLt = pure intRel
typeOfBuiltin IntMod = pure intBinOp
typeOfBuiltin IntDiv = pure intBinOp
typeOfBuiltin IntPlus = pure intBinOp
typeOfBuiltin IntTimes = pure intBinOp
typeOfBuiltin IntMinus = pure intBinOp
typeOfBuiltin IntShiftR = pure intShift
typeOfBuiltin IntShiftL = pure intBinOp
typeOfBuiltin IntXor = pure intBinOp
typeOfBuiltin WordXor = pure wordBinOp
typeOfBuiltin WordPlus = pure wordBinOp
typeOfBuiltin WordTimes = pure wordBinOp
typeOfBuiltin WordShiftR = pure wordShift
typeOfBuiltin WordShiftL = pure wordShift
typeOfBuiltin IntGeq = pure intRel
typeOfBuiltin IntNeq = pure intRel
typeOfBuiltin IntGt = pure intRel
typeOfBuiltin WordMinus = pure wordBinOp
typeOfBuiltin WordDiv = pure wordBinOp
typeOfBuiltin WordMod = pure wordBinOp
typeOfBuiltin And = pure boolOp
typeOfBuiltin Or = pure boolOp
typeOfBuiltin Xor = pure boolOp
typeOfBuiltin IntNeg = pure $ StackType [TyBuiltin () TyInt] [TyBuiltin () TyInt]
typeOfBuiltin Popcount = pure $ StackType [TyBuiltin () TyWord] [TyBuiltin () TyInt]
boolOp :: StackType ()
boolOp = StackType [TyBuiltin () TyBool, TyBuiltin () TyBool] [TyBuiltin () TyBool]
intRel :: StackType ()
intRel = StackType [TyBuiltin () TyInt, TyBuiltin () TyInt] [TyBuiltin () TyBool]
intBinOp :: StackType ()
intBinOp = StackType [TyBuiltin () TyInt, TyBuiltin () TyInt] [TyBuiltin () TyInt]
intShift :: StackType ()
intShift = StackType [TyBuiltin () TyInt, TyBuiltin () TyInt] [TyBuiltin () TyInt]
wordBinOp :: StackType ()
wordBinOp = StackType [TyBuiltin () TyWord, TyBuiltin () TyWord] [TyBuiltin () TyWord]
wordShift :: StackType ()
wordShift = StackType [TyBuiltin () TyWord, TyBuiltin () TyWord] [TyBuiltin () TyWord]
tyLookup :: Name a -> TypeM a (StackType a)
tyLookup n@(Name _ (Unique i) l) = do
st <- gets tyEnv
case IM.lookup i st of
Just ty -> pure ty
Nothing -> throwError $ PoorScope l n
consLookup :: TyName a -> TypeM a (StackType a)
consLookup tn@(Name _ (Unique i) l) = do
st <- gets constructorTypes
case IM.lookup i st of
Just ty -> pure ty
Nothing -> throwError $ PoorScope l tn
expandType 1
dipify :: StackType () -> TypeM () (StackType ())
dipify (StackType is os) = do
n <- dummyName "a"
pure $ StackType (is ++ [TyVar () n]) (os ++ [TyVar () n])
tyLeaf :: (Pattern b a, [Atom b a]) -> TypeM () (StackType ())
tyLeaf (p, as) = do
tyP <- tyPattern p
tyA <- tyAtoms as
catTypes tyP tyA
assignCase :: (Pattern b a, [Atom b a]) -> TypeM () (StackType (), Pattern (StackType ()) (StackType ()), [Atom (StackType ()) (StackType ())])
assignCase (p, as) = do
(tyP, p') <- assignPattern p
(as', tyA) <- assignAtoms as
(,,) <$> catTypes tyP tyA <*> pure p' <*> pure as'
tyAtom :: Atom b a -> TypeM () (StackType ())
tyAtom (AtBuiltin _ b) = typeOfBuiltin b
tyAtom BoolLit{} = pure $ StackType [] [TyBuiltin () TyBool]
tyAtom IntLit{} = pure $ StackType [] [TyBuiltin () TyInt]
tyAtom Int8Lit{} = pure $ StackType [] [TyBuiltin () TyInt8 ]
tyAtom WordLit{} = pure $ StackType [] [TyBuiltin () TyWord]
tyAtom (AtName _ n) = renameStack =<< tyLookup (void n)
tyAtom (Dip _ as) = dipify =<< tyAtoms as
tyAtom (AtCons _ tn) = renameStack =<< consLookup (void tn)
tyAtom (If _ as as') = do
tys <- tyAtoms as
tys' <- tyAtoms as'
(StackType ins out) <- mergeStackTypes tys tys'
pure $ StackType (ins ++ [TyBuiltin () TyBool]) out
tyAtom (Case _ ls) = do
tyLs <- traverse tyLeaf ls
TODO : one - pass fold ?
mergeMany tyLs
assignAtom :: Atom b a -> TypeM () (StackType (), Atom (StackType ()) (StackType ()))
assignAtom (AtBuiltin _ b) = do { ty <- typeOfBuiltin b ; pure (ty, AtBuiltin ty b) }
assignAtom (BoolLit _ b) =
let sTy = StackType [] [TyBuiltin () TyBool]
in pure (sTy, BoolLit sTy b)
assignAtom (IntLit _ i) =
let sTy = StackType [] [TyBuiltin () TyInt]
in pure (sTy, IntLit sTy i)
assignAtom (Int8Lit _ i) =
let sTy = StackType [] [TyBuiltin () TyInt8]
in pure (sTy, Int8Lit sTy i)
assignAtom (WordLit _ u) =
let sTy = StackType [] [TyBuiltin () TyWord]
in pure (sTy, WordLit sTy u)
assignAtom (AtName _ n) = do
sTy <- renameStack =<< tyLookup (void n)
pure (sTy, AtName sTy (n $> sTy))
assignAtom (AtCons _ tn) = do
sTy <- renameStack =<< consLookup (void tn)
pure (sTy, AtCons sTy (tn $> sTy))
assignAtom (Dip _ as) = do { (as', ty) <- assignAtoms as ; tyDipped <- dipify ty ; pure (tyDipped, Dip tyDipped as') }
assignAtom (If _ as0 as1) = do
(as0', tys) <- assignAtoms as0
(as1', tys') <- assignAtoms as1
(StackType ins out) <- mergeStackTypes tys tys'
let resType = StackType (ins ++ [TyBuiltin () TyBool]) out
pure (resType, If resType as0' as1')
assignAtom (Case _ ls) = do
lRes <- traverse assignCase ls
resType <- mergeMany (fst3 <$> lRes)
let newLeaves = fmap dropFst lRes
pure (resType, Case resType newLeaves)
where dropFst (_, y, z) = (y, z)
assignAtoms :: [Atom b a] -> TypeM () ([Atom (StackType ()) (StackType ())], StackType ())
assignAtoms [] = pure ([], emptyStackType)
assignAtoms [a] = do
(ty, a') <- assignAtom a
pure ([a'], ty)
assignAtoms (a:as) = do
(ty, a') <- assignAtom a
(as', ty') <- assignAtoms as
(a':as' ,) <$> catTypes ty ty'
tyAtoms :: [Atom b a] -> TypeM () (StackType ())
tyAtoms [] = pure emptyStackType
tyAtoms [a] = tyAtom a
tyAtoms (a:as) = do
ty <- tyAtom a
tys <- tyAtoms as
catTypes ty tys
mkHKT :: Int -> Kind
mkHKT 0 = Star
mkHKT i = TyCons (mkHKT $ i - 1) Star
-> S.Set (Name b) -> (TyName a, [KempeTy b]) -> TypeM () ()
tyInsertLeaf n@(Name _ (Unique k) _) vars (Name _ (Unique i) _, ins) | S.null vars =
modifying constructorTypesLens (IM.insert i (voidStackType $ StackType ins [TyNamed undefined n])) *>
modifying kindEnvLens (IM.insert k Star)
| otherwise =
let ty = voidStackType $ StackType ins [app (TyNamed undefined n) (S.toList vars)] in
modifying constructorTypesLens (IM.insert i ty) *>
modifying kindEnvLens (IM.insert k (mkHKT $ S.size vars))
assignTyLeaf :: Name b
-> S.Set (Name b)
-> (TyName a, [KempeTy b])
-> TypeM () (TyName (StackType ()), [KempeTy ()])
assignTyLeaf n@(Name _ (Unique k) _) vars (tn@(Name _ (Unique i) _), ins) | S.null vars =
let ty = voidStackType $ StackType ins [TyNamed undefined n] in
modifying constructorTypesLens (IM.insert i ty) *>
modifying kindEnvLens (IM.insert k Star) $>
(tn $> ty, fmap void ins)
| otherwise =
let ty = voidStackType $ StackType ins [app (TyNamed undefined n) (S.toList vars)] in
modifying constructorTypesLens (IM.insert i ty) *>
modifying kindEnvLens (IM.insert k (mkHKT $ S.size vars)) $>
(tn $> ty, fmap void ins)
app :: KempeTy a -> [Name a] -> KempeTy a
app = foldr (\n ty -> TyApp undefined ty (TyVar undefined n))
kindLookup :: TyName a -> TypeM a Kind
kindLookup n@(Name _ (Unique i) l) = do
st <- gets kindEnv
case IM.lookup i st of
Just k -> pure k
Nothing -> throwError $ PoorScope l n
kindOf :: KempeTy a -> TypeM a Kind
kindOf TyBuiltin{} = pure Star
kindOf (TyNamed _ tn) = kindLookup tn
kindOf TyVar{} = pure Star
kindOf tyErr@(TyApp l ty ty') = do
k <- kindOf ty
k' <- kindOf ty'
case k of
TyCons k'' k''' -> unless (k' == k''') (throwError (IllKinded l tyErr)) $> k''
_ -> throwError (IllKinded l tyErr)
assignDecl :: KempeDecl a c b -> TypeM () (KempeDecl () (StackType ()) (StackType ()))
assignDecl (TyDecl _ tn ns ls) = TyDecl () (void tn) (void <$> ns) <$> traverse (assignTyLeaf tn (S.fromList ns)) ls
assignDecl (FunDecl _ n ins os a) = do
traverse_ kindOf (void <$> ins ++ os)
sig <- renameStack $ voidStackType $ StackType ins os
(as, inferred) <- assignAtoms a
reconcile <- mergeStackTypes sig inferred
when (inferred `lessGeneral` sig) $
throwError $ LessGeneral () sig inferred
pure $ FunDecl reconcile (n $> reconcile) (void <$> ins) (void <$> os) as
assignDecl (ExtFnDecl _ n ins os cn) = do
traverse_ kindOf (void <$> ins ++ os)
unless (length os <= 1) $
throwError $ InvalidCImport () (void n)
let sig = voidStackType $ StackType ins os
pure $ ExtFnDecl sig (n $> sig) (void <$> ins) (void <$> os) cn
assignDecl (Export _ abi n) = do
ty@(StackType _ os) <- tyLookup (void n)
unless (abi == Kabi || length os <= 1) $
throwError $ InvalidCExport () (void n)
Export ty abi <$> assignName n
assignName :: Name a -> TypeM () (Name (StackType ()))
assignName n = do { ty <- tyLookup (void n) ; pure (n $> ty) }
tyHeader :: KempeDecl a c b -> TypeM () ()
tyHeader Export{} = pure ()
tyHeader (FunDecl _ (Name _ (Unique i) _) ins out _) = do
let sig = voidStackType $ StackType ins out
modifying tyEnvLens (IM.insert i sig)
tyHeader (ExtFnDecl _ n@(Name _ (Unique i) _) ins os _) = do
unless (length os <= 1) $
throwError $ InvalidCImport () (void n)
unless (null $ freeVars (ins ++ os)) $
throwError $ TyVarExt () (void n)
modifying tyEnvLens (IM.insert i sig)
tyHeader TyDecl{} = pure ()
type Vars a = IM.IntMap (Name a)
type EqState a = State (Vars a)
-> Bool
lessGeneral (StackType is os) (StackType is' os') =
flip evalState mempty $
if il > il' || ol > ol'
then (||) <$> lessGenerals trimIs is' <*> lessGenerals trimOs os'
else (||) <$> lessGenerals is trimIs' <*> lessGenerals os trimOs'
where il = length is
il' = length is'
ol = length os
ol' = length os'
trimIs = drop (il-il') is
trimIs' = drop (il'-il) is'
trimOs = drop (ol-ol') os
trimOs' = drop (ol'-ol) os'
lessGeneralAtom :: KempeTy a -> KempeTy a -> EqState a Bool
lessGeneralAtom TyBuiltin{} TyVar{} = pure True
lessGeneralAtom TyApp{} TyVar{} = pure True
lessGeneralAtom _ _ = pure False
lessGenerals :: [KempeTy a] -> [KempeTy a] -> EqState a Bool
lessGenerals [] [] = pure False
lessGenerals ((TyVar _ n):tys) ((TyVar _ n'):tys') = do
st <- get
let i = unUnique $ unique n
case IM.lookup i st of
Nothing ->
modify (IM.insert i n') *>
we can skip checking ty ` lessGeneral ` ty ' at the first site
Just n'' ->
(n'' /= n' ||) <$> lessGenerals tys tys'
lessGenerals (ty:tys) (ty':tys') = (||) <$> lessGeneralAtom ty ty' <*> lessGenerals tys tys'
tyInsert :: KempeDecl a c b -> TypeM () ()
tyInsert (TyDecl _ tn ns ls) = traverse_ (tyInsertLeaf tn (S.fromList ns)) ls
tyInsert (FunDecl _ _ ins out as) = do
sig <- renameStack $ voidStackType $ StackType ins out
inferred <- tyAtoms as
_ <- mergeStackTypes sig inferred
when (inferred `lessGeneral` sig) $
throwError $ LessGeneral () sig inferred
tyInsert (ExtFnDecl _ _ ins outs _) = traverse_ kindOf (void <$> ins ++ outs)
tyInsert Export{} = pure ()
tyModule :: Declarations a c b -> TypeM () ()
tyModule m = traverse_ tyHeader m *> traverse_ tyInsert m
checkModule :: Declarations a c b -> TypeM () ()
checkModule m = tyModule m <* (unifyM =<< gets constraints)
assignModule :: Declarations a c b -> TypeM () (Declarations () (StackType ()) (StackType ()))
m' <- traverse assignDecl m
backNames <- unifyM =<< gets constraints
pure (fmap (bimap .$ substConstraintsStack backNames) m')
replaceUnique :: Unique -> TypeM a Unique
replaceUnique u@(Unique i) = do
rSt <- gets renames
case IM.lookup i rSt of
Nothing -> pure u
Just j -> replaceUnique (Unique j)
renameIn :: KempeTy a -> TypeM a (KempeTy a)
renameIn b@TyBuiltin{} = pure b
renameIn n@TyNamed{} = pure n
renameIn (TyApp l ty ty') = TyApp l <$> renameIn ty <*> renameIn ty'
renameIn (TyVar l (Name t u l')) = do
u' <- replaceUnique u
pure $ TyVar l (Name t u' l')
withTyState :: (TyState a -> TyState a) -> TypeM a x -> TypeM a x
withTyState modSt act = do
preSt <- get
modify modSt
res <- act
postMax <- gets maxU
put preSt
maxULens .= postMax
pure res
withName :: Name a -> TypeM a (Name a, TyState a -> TyState a)
withName (Name t (Unique i) l) = do
m <- gets maxU
let newUniq = m+1
maxULens .= newUniq
pure (Name t (Unique newUniq) l, over renamesLens (IM.insert i (m+1)))
renameStack :: StackType a -> TypeM a (StackType a)
renameStack (StackType ins outs) = do
newQs <- traverse withName (S.toList $ freeVars ins <> freeVars outs)
let (_, localRenames) = unzip newQs
newBinds = thread localRenames
withTyState newBinds $
StackType <$> traverse renameIn ins <*> traverse renameIn outs
mergeStackTypes :: StackType () -> StackType () -> TypeM () (StackType ())
mergeStackTypes st0@(StackType i0 o0) st1@(StackType i1 o1) = do
let li0 = length i0
li1 = length i1
toExpand = max (abs (li0 - li1)) (abs (length o0 - length o1))
(StackType ins os) <- (if li0 < li1 then expandType toExpand else pure) st0
(StackType ins' os') <- (if li1 < li0 then expandType toExpand else pure) st1
when ((length ins /= length ins') || (length os /= length os')) $
throwError $ MismatchedLengths () st0 st1
zipWithM_ pushConstraint ins ins'
zipWithM_ pushConstraint os os'
pure $ StackType ins os
tyPattern :: Pattern b a -> TypeM () (StackType ())
tyPattern PatternWildcard{} = do
aN <- dummyName "a"
pure $ StackType [TyVar () aN] []
tyPattern PatternInt{} = pure $ StackType [TyBuiltin () TyInt] []
tyPattern PatternBool{} = pure $ StackType [TyBuiltin () TyBool] []
tyPattern (PatternCons _ tn) = renameStack . flipStackType =<< consLookup (void tn)
assignPattern :: Pattern b a -> TypeM () (StackType (), Pattern (StackType ()) (StackType ()))
assignPattern (PatternInt _ i) =
let sTy = StackType [TyBuiltin () TyInt] []
in pure (sTy, PatternInt sTy i)
assignPattern (PatternBool _ i) =
let sTy = StackType [TyBuiltin () TyBool] []
in pure (sTy, PatternBool sTy i)
assignPattern (PatternCons _ tn) = do { ty <- renameStack . flipStackType =<< consLookup (void tn) ; pure (ty, PatternCons ty (tn $> ty)) }
assignPattern PatternWildcard{} = do
aN <- dummyName "a"
let resType = StackType [TyVar () aN] []
pure (resType, PatternWildcard resType)
mergeMany :: NonEmpty (StackType ()) -> TypeM () (StackType ())
mergeMany (t :| ts) = foldM mergeStackTypes t ts
pushConstraint :: Ord a => KempeTy a -> KempeTy a -> TypeM a ()
pushConstraint ty ty' =
modifying constraintsLens (S.insert (ty, ty'))
expandType :: Int -> StackType () -> TypeM () (StackType ())
expandType n (StackType i o) = do
newVars <- replicateM n (dummyName "a")
let newTy = TyVar () <$> newVars
pure $ StackType (newTy ++ i) (newTy ++ o)
substConstraints :: IM.IntMap (KempeTy a) -> KempeTy a -> KempeTy a
substConstraints _ ty@TyNamed{} = ty
substConstraints _ ty@TyBuiltin{} = ty
substConstraints tys ty@(TyVar _ (Name _ (Unique k) _)) =
case IM.lookup k tys of
Just (TyApp l ty0 ty1) -> let tys' = IM.delete k tys in TyApp l (substConstraints tys' ty0) (substConstraints tys' ty1)
Just ty' -> ty'
Nothing -> ty
substConstraints tys (TyApp l ty ty') =
TyApp l (substConstraints tys ty) (substConstraints tys ty')
substConstraintsStack :: IM.IntMap (KempeTy a) -> StackType a -> StackType a
let is' = substConstraints tys <$> is
os' = substConstraints tys <$> os
in StackType is' os'
| Given @x@ and @y@ , return the ' StackType ' of @x y@
-> TypeM () (StackType ())
catTypes st0@(StackType _ osX) (StackType insY osY) = do
let lY = length insY
lDiff = lY - length osX
(StackType insX osX') <- if lDiff > 0
then expandType lDiff st0
else pure st0
zip the last ( length insY ) of osX ' with insY
pure $ StackType insX (take (length osX' - lY) osX' ++ osY)
|
45faafd93f034cd0ce0432bb71e2d5673ec037738faba64f7c9f8fd1f13404b9 | MedeaMelana/Magic | Combat.hs | {-# LANGUAGE GADTs #-}
module Magic.Combat
( -- * Types
Attack(..), Block(..)
-- * Attacking restrictions
-- | Restrictions that check whether a set of attacks is legal according to the current object. Use these values for a creature's 'allowAttacks' field or for further restricting such a predicate using 'RestrictAllowAttacks' in a 'LayeredEffect'.
, selfCantAttack, selfCantAttackAlone
-- * Blocking restrictions
-- | Restrictions that check whether a set of blocks is legal according to the current object. Use these values for a creature's 'allowBlocks' field or for further restricting such a predicate using 'RestrictAllowBlocks' in a 'LayeredEffect'.
, selfCantBlock, selfCantBlockAlone
, selfCantBeBlocked
) where
import Magic.Some
import Magic.Types
import Data.Boolean (true)
import Data.List (notElem, nub)
-- | Only allow the attacks if this creature is not part of the attacking creatures.
selfCantAttack :: [Attack] -> Contextual (View Bool)
selfCantAttack ats (Some Battlefield, i) _ =
return ((Battlefield, i) `notElem` map attacker ats)
selfCantAttack _ _ _ = true
| Only allow the attacks if this creature is not part of the attacking creatures , or if there is at least one other creature attacking .
selfCantAttackAlone :: [Attack] -> Contextual (View Bool)
selfCantAttackAlone ats (Some Battlefield, i) _ =
return ((Battlefield, i) `notElem` map attacker ats || length ats > 1)
selfCantAttackAlone _ _ _ = true
-- | Only allow the blocks if this creature is not part of the blocking creatures.
selfCantBlock :: [Block] -> Contextual (View Bool)
selfCantBlock bls (Some Battlefield, i) _ =
return ((Battlefield, i) `notElem` map blocker bls)
selfCantBlock _ _ _ = true
| Only allow the blocks if this creature is not part of the blocking creatures or if at least one other creature is blocking .
selfCantBlockAlone :: [Block] -> Contextual (View Bool)
selfCantBlockAlone bls (Some Battlefield, i) _ =
return (i `notElem` blockerIds || not (null (filter (/= i) blockerIds)))
where
blockerIds = nub (map (snd . blocker) bls)
-- | Only allow the blocks if this object is not part of the creatures being blocked.
selfCantBeBlocked :: [Block] -> Contextual (View Bool)
selfCantBeBlocked bls (Some Battlefield, i) _ =
return ((Battlefield, i) `notElem` map blockee bls)
selfCantBeBlocked _ _ _ = true
| null | https://raw.githubusercontent.com/MedeaMelana/Magic/7bd87e4e1d54a7c5e5f81661196cafb87682c62a/Magic/src/Magic/Combat.hs | haskell | # LANGUAGE GADTs #
* Types
* Attacking restrictions
| Restrictions that check whether a set of attacks is legal according to the current object. Use these values for a creature's 'allowAttacks' field or for further restricting such a predicate using 'RestrictAllowAttacks' in a 'LayeredEffect'.
* Blocking restrictions
| Restrictions that check whether a set of blocks is legal according to the current object. Use these values for a creature's 'allowBlocks' field or for further restricting such a predicate using 'RestrictAllowBlocks' in a 'LayeredEffect'.
| Only allow the attacks if this creature is not part of the attacking creatures.
| Only allow the blocks if this creature is not part of the blocking creatures.
| Only allow the blocks if this object is not part of the creatures being blocked. |
module Magic.Combat
Attack(..), Block(..)
, selfCantAttack, selfCantAttackAlone
, selfCantBlock, selfCantBlockAlone
, selfCantBeBlocked
) where
import Magic.Some
import Magic.Types
import Data.Boolean (true)
import Data.List (notElem, nub)
selfCantAttack :: [Attack] -> Contextual (View Bool)
selfCantAttack ats (Some Battlefield, i) _ =
return ((Battlefield, i) `notElem` map attacker ats)
selfCantAttack _ _ _ = true
| Only allow the attacks if this creature is not part of the attacking creatures , or if there is at least one other creature attacking .
selfCantAttackAlone :: [Attack] -> Contextual (View Bool)
selfCantAttackAlone ats (Some Battlefield, i) _ =
return ((Battlefield, i) `notElem` map attacker ats || length ats > 1)
selfCantAttackAlone _ _ _ = true
selfCantBlock :: [Block] -> Contextual (View Bool)
selfCantBlock bls (Some Battlefield, i) _ =
return ((Battlefield, i) `notElem` map blocker bls)
selfCantBlock _ _ _ = true
| Only allow the blocks if this creature is not part of the blocking creatures or if at least one other creature is blocking .
selfCantBlockAlone :: [Block] -> Contextual (View Bool)
selfCantBlockAlone bls (Some Battlefield, i) _ =
return (i `notElem` blockerIds || not (null (filter (/= i) blockerIds)))
where
blockerIds = nub (map (snd . blocker) bls)
selfCantBeBlocked :: [Block] -> Contextual (View Bool)
selfCantBeBlocked bls (Some Battlefield, i) _ =
return ((Battlefield, i) `notElem` map blockee bls)
selfCantBeBlocked _ _ _ = true
|
fa575f956575ad6e1ec7dfafb286a1988769f897253b79d53ef44a41557fc4d9 | slipstream/SlipStreamServer | filter.clj | (ns com.sixsq.slipstream.db.es-rest.filter
(:refer-clojure :exclude [filter])
(:require
[clojure.string :as str]
[clojure.walk :as w]
[com.sixsq.slipstream.db.es-rest.query :as query]
[com.sixsq.slipstream.db.utils.time-utils :as time]))
(defn- strip-quotes
[s]
(subs s 1 (dec (count s))))
(defmulti convert
(fn [v]
(when (vector? v)
(first v))))
(defmethod convert :IntValue [[_ ^String s]]
[:Value (Integer/valueOf s)])
(defmethod convert :DoubleQuoteString [[_ s]]
[:Value (strip-quotes s)])
(defmethod convert :SingleQuoteString [[_ s]]
[:Value (strip-quotes s)])
(defmethod convert :BoolValue [[_ ^String s]]
[:Value (Boolean/valueOf s)])
(defmethod convert :DateValue [[_ ^String s]]
[:Value (time/to-time-or-date s)])
(defmethod convert :NullValue [[_ ^String s]]
[:Value nil])
(defmethod convert :Comp [v]
(let [args (rest v)]
(if (= 1 (count args))
(first args) ;; (a=1 and b=2) case
(let [{:keys [Attribute EqOp RelOp PrefixOp Value] :as m} (into {} args)
Op (or EqOp RelOp PrefixOp)
order (ffirst args)]
(case [Op order]
["=" :Attribute] (if (nil? Value) (query/missing Attribute) (query/eq Attribute Value))
["!=" :Attribute] (if (nil? Value) (query/exists Attribute) (query/ne Attribute Value))
["^=" :Attribute] (query/prefix Attribute Value)
[">=" :Attribute] (query/gte Attribute Value)
[">" :Attribute] (query/gt Attribute Value)
["<=" :Attribute] (query/lte Attribute Value)
["<" :Attribute] (query/lt Attribute Value)
["=" :Value] (if (nil? Value) (query/missing Attribute) (query/eq Attribute Value))
["!=" :Value] (if (nil? Value) (query/exists Attribute) (query/ne Attribute Value))
["^=" :Value] (query/prefix Attribute Value)
[">=" :Value] (query/lte Attribute Value)
[">" :Value] (query/lt Attribute Value)
["<=" :Value] (query/gte Attribute Value)
["<" :Value] (query/gt Attribute Value)
m)))))
(defmethod convert :PropExpr
[[_ Prop EqOp Value]]
[[:Attribute (str "property/" (second Prop))] EqOp Value])
(defmethod convert :AndExpr
[v]
(let [args (rest v)]
(if (= 1 (count args))
(first args)
(query/and args))))
(defmethod convert :Filter
[v]
(let [args (rest v)]
(if (= 1 (count args))
(first args)
(query/or args))))
(defmethod convert :Attribute
[v]
[:Attribute (str/replace (str/join "" (rest v)) #"/" ".")])
(defmethod convert :default
[v]
v)
(defn filter
[{:keys [filter] :as cimi-params}]
(if filter
(query/constant-score-query (w/postwalk convert filter))
(query/match-all-query)))
| null | https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/db-binding/src/com/sixsq/slipstream/db/es_rest/filter.clj | clojure | (a=1 and b=2) case | (ns com.sixsq.slipstream.db.es-rest.filter
(:refer-clojure :exclude [filter])
(:require
[clojure.string :as str]
[clojure.walk :as w]
[com.sixsq.slipstream.db.es-rest.query :as query]
[com.sixsq.slipstream.db.utils.time-utils :as time]))
(defn- strip-quotes
[s]
(subs s 1 (dec (count s))))
(defmulti convert
(fn [v]
(when (vector? v)
(first v))))
(defmethod convert :IntValue [[_ ^String s]]
[:Value (Integer/valueOf s)])
(defmethod convert :DoubleQuoteString [[_ s]]
[:Value (strip-quotes s)])
(defmethod convert :SingleQuoteString [[_ s]]
[:Value (strip-quotes s)])
(defmethod convert :BoolValue [[_ ^String s]]
[:Value (Boolean/valueOf s)])
(defmethod convert :DateValue [[_ ^String s]]
[:Value (time/to-time-or-date s)])
(defmethod convert :NullValue [[_ ^String s]]
[:Value nil])
(defmethod convert :Comp [v]
(let [args (rest v)]
(if (= 1 (count args))
(let [{:keys [Attribute EqOp RelOp PrefixOp Value] :as m} (into {} args)
Op (or EqOp RelOp PrefixOp)
order (ffirst args)]
(case [Op order]
["=" :Attribute] (if (nil? Value) (query/missing Attribute) (query/eq Attribute Value))
["!=" :Attribute] (if (nil? Value) (query/exists Attribute) (query/ne Attribute Value))
["^=" :Attribute] (query/prefix Attribute Value)
[">=" :Attribute] (query/gte Attribute Value)
[">" :Attribute] (query/gt Attribute Value)
["<=" :Attribute] (query/lte Attribute Value)
["<" :Attribute] (query/lt Attribute Value)
["=" :Value] (if (nil? Value) (query/missing Attribute) (query/eq Attribute Value))
["!=" :Value] (if (nil? Value) (query/exists Attribute) (query/ne Attribute Value))
["^=" :Value] (query/prefix Attribute Value)
[">=" :Value] (query/lte Attribute Value)
[">" :Value] (query/lt Attribute Value)
["<=" :Value] (query/gte Attribute Value)
["<" :Value] (query/gt Attribute Value)
m)))))
(defmethod convert :PropExpr
[[_ Prop EqOp Value]]
[[:Attribute (str "property/" (second Prop))] EqOp Value])
(defmethod convert :AndExpr
[v]
(let [args (rest v)]
(if (= 1 (count args))
(first args)
(query/and args))))
(defmethod convert :Filter
[v]
(let [args (rest v)]
(if (= 1 (count args))
(first args)
(query/or args))))
(defmethod convert :Attribute
[v]
[:Attribute (str/replace (str/join "" (rest v)) #"/" ".")])
(defmethod convert :default
[v]
v)
(defn filter
[{:keys [filter] :as cimi-params}]
(if filter
(query/constant-score-query (w/postwalk convert filter))
(query/match-all-query)))
|
7d5ec76b025c2767ab2d1ab1ab88fe541f2749b6e220903b83d57a7059883d4c | webcrank/webcrank.hs | Types.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE FunctionalDependencies #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
module Webcrank.Internal.Types where
import Control.Applicative
import Control.Lens
import Control.Monad.Catch
import Control.Monad.RWS
import Control.Monad.Trans.Either
import Control.Monad.Trans.Maybe
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString.UTF8 as B
import Data.CaseInsensitive (CI)
import Data.HashMap.Strict (HashMap)
import Data.List.NonEmpty (NonEmpty)
import Data.Text (Text)
import Network.HTTP.Date
import Network.HTTP.Media
import Network.HTTP.Types
import Prelude
import Webcrank.Internal.Headers
| A dictionary of functions that Webcrank needs in order to make decisions .
data ServerAPI m = ServerAPI
{ srvGetRequestMethod :: m Method
-- ^ Get the request method of the current request.
, srvGetRequestURI :: m ByteString
-- ^ The full URI of the request.
, srvGetRequestHeader :: HeaderName -> m (Maybe ByteString)
-- ^ Get the request header of the current request.
, srvGetRequestTime :: m HTTPDate
-- ^ Get the time the request was received.
}
type HeadersMap = HashMap HeaderName [ByteString]
| Content coding type , e.g. gzip , decompress . See @'encodingsProvided'@.
type Encoding = CI ByteString
| Character set type , e.g. utf-8 . See
type Charset = CI ByteString
-- | Response body type.
type Body = LB.ByteString
-- | Indicates whether client is authorized to perform the requested
-- operation on the resource. See @'isAuthorized'@.
data Authorized
= Authorized
^ Tells Webcrank that the client is authorized to perform the
-- requested operation on the resource.
| Unauthorized ByteString
^ Tells Webcrank that the client is not authorized to perform
-- the operation on the resource. The value is sent in the
- Authenticate@ header of the response ,
e.g. @Basic realm="Webcrank"@.
-- | Indicates whether the resource supports multiple character sets
or not . See
data CharsetsProvided
= NoCharset
-- ^ Indicates that the resource doesn't support any additional
-- character sets, all responses from the resource will have the
-- same character set, regardless of what the client requests.
| CharsetsProvided (NonEmpty (Charset, Body -> Body))
-- ^ The character sets the resource supports along with functions
-- for converting the response body.
-- | Weak or strong entity tags as used in HTTP ETag and @If-*-Match@ headers.
data ETag = StrongETag ByteString | WeakETag ByteString deriving Eq
instance Show ETag where
show e = B.toString $ case e of
StrongETag v -> "\"" <> v <> "\""
WeakETag v -> "W/\"" <> v <> "\""
instance RenderHeader ETag where
renderHeader = \case
StrongETag v -> quotedString v
WeakETag v -> "W/" <> quotedString v
data Halt = Halt Status | Error Status LB.ByteString
deriving (Eq, Show)
-- | Monad transformer for @'Resource'@ functions which can halt the request
-- processing early with an error or some other response. Values are created with
the smart constructors @'werror'@ and @'halt'@.
newtype HaltT m a = HaltT { unHaltT :: EitherT Halt m a }
deriving
( Functor
, Applicative
, Monad
, MonadIO
, MonadTrans
, MonadReader r
, MonadState s
, MonadWriter w
, MonadThrow
, MonadCatch
)
-- | How @POST@ requests should be treated. See @'postAction'@.
data PostAction m
= PostCreate [Text]
^ Treat @POST@s as creating new resources and respond
-- with @201 Created@, with the given path in the Location header.
| PostCreateRedir [Text]
^ Treat @POST@s as creating new resources and respond with
-- @301 See Other@, redirecting the client to the new resource.
| PostProcess (HaltT m ())
^ Treat @POST@s as a process which is executed without redirect .
| PostProcessRedir (HaltT m ByteString)
^ Treat @POST@s as a process and redirect the client to a
-- different (possibly new) resource.
data LogData = LogData
instance Monoid LogData where
mempty = LogData
mappend _ _ = LogData
| A is a dictionary of functions which are used in the Webcrank
-- decision process to determine how requests should be handled.
--
-- Each function has a type of either @m a@ or @'HaltT' m a@.
-- A resource function which yields a @HaltT m a@ value allows the function
-- to terminate the request processing early using @'halt'@ or
-- @'werror'@.
--
The defaults documented are used by the @'resource'@ smart constructor .
-- A resource that responds to @GET@ requests with an HTML response would be
-- written as
--
-- @
myResource = resource { contentTypesProvided = return $ [ ( " text / html " , return " Hello world ! " ) ] }
-- @
--
@'responseWithBody'@ and @'responseWithHtml'@ are additional
-- smart constructors useful creating resources.
data Resource m = Resource
{ serviceAvailable :: HaltT m Bool
-- ^ @False@ will result in @503 Service Unavailable@. Defaults to @True@.
, uriTooLong :: HaltT m Bool
^ @True@ will result in @414 Request Too Long@. Defaults to
, allowedMethods :: m [Method]
-- ^ If a @Method@ not in this list is requested, then a @405 Method Not
Allowed@ will be sent . Defaults to " , " HEAD"]@.
, malformedRequest :: HaltT m Bool
^ @True@ will result in @400 Bad Request@. Defaults to
, isAuthorized :: HaltT m Authorized
-- ^ If @Authorized@, the response will be @401 Unauthorized@.
@Unauthorized@ will be used as the challenge in the - Authenticate@
header , e.g. @Basic realm="Webcrank"@.
Defaults to @Authorized@.
, forbidden :: HaltT m Bool
^ @True@ will result in @403 Forbidden@. to
, validContentHeaders :: HaltT m Bool
-- ^ @False@ will result in @501 Not Implemented@. Defaults to @True@.
, knownContentType :: HaltT m Bool
^ @False@ will result in @415 Unsupported Media Type@. Defaults to
-- @True@.
, validEntityLength :: HaltT m Bool
^ @False@ will result in @413 Request Entity Too Large@. Defaults to
-- @True@.
, options :: m ResponseHeaders
-- ^ If the OPTIONS method is supported and is used, the headers that
-- should appear in the response. Defaults to @[]@.
, contentTypesProvided :: m [(MediaType, HaltT m Body)]
-- ^ Content negotiation is driven by this function. For example, if a
-- client request includes an @Accept@ header with a value that does not
-- appear as a @MediaType@ in any of the tuples, then a @406 Not
-- Acceptable@ will be sent. If there is a matching @MediaType@, that
-- function is used to create the entity when a response should include one.
-- Defaults to @[]@.
, charsetsProvided :: m CharsetsProvided
^ Used on GET requests to ensure that the entity is in @Charset@.
-- Defaults to @NoCharset@.
, encodingsProvided :: m [(Encoding, Body -> Body)]
-- ^ Used on GET requests to ensure that the body is encoded.
One useful setting is to have the function check on method , and on GET
-- requests return @[("identity", id), ("gzip", compress)]@ as this is all
-- that is needed to support gzip content encoding. Defaults to
-- @[]@.
, resourceExists :: HaltT m Bool
^ @False@ will result in @404 Not Found@. Defaults to @True@.
, generateETag :: MaybeT m ETag
^ If this returns an @ETag@ , it will be used for the ETag header and for
-- comparison in conditional requests. Defaults to @mzero@.
, lastModified :: MaybeT m HTTPDate
^ If this returns a @HTTPDate@ , it will be used for the Last - Modified header
-- and for comparison in conditional requests. Defaults to @mzero@.
, expires :: MaybeT m HTTPDate
^ If this returns a @HTTPDate@ , it will be used for the Expires header .
-- Defaults to @mzero@.
, movedPermanently :: MaybeT (HaltT m) ByteString
^ If this returns a URI , the client will receive a 301 Moved Permanently
with the URI in the Location header . Defaults to @mzero@.
, movedTemporarily :: MaybeT (HaltT m) ByteString
^ If this returns a URI , the client will receive a 307 Temporary Redirect
with URI in the Location header . Defaults to @mzero@.
, previouslyExisted :: HaltT m Bool
^ If this returns @True@ , the @movedPermanently@ and @movedTemporarily@
-- callbacks will be invoked to determine whether the response should be
301 Moved Permanently , 307 Temporary Redirect , or 410 Gone . Defaults
to
, allowMissingPost :: HaltT m Bool
-- ^ If the resource accepts POST requests to nonexistent resources, then
this should return @True@. Defaults to
, deleteResource :: HaltT m Bool
-- ^ This is called when a DELETE request should be enacted, and should return
@True@ if the deletion succeeded or has been accepted . Defaults to
-- @True@.
, deleteCompleted :: HaltT m Bool
-- ^ This is only called after a successful @deleteResource@ call, and should
-- return @False@ if the deletion was accepted but cannot yet be guaranteed to
-- have finished. Defaults to @True@.
, postAction :: m (PostAction m)
-- ^ If POST requests should be treated as a request to put content into a
-- (potentially new) resource as opposed to being a generic submission for
-- processing, then this function should return @PostCreate path@. If it
-- does return @PostCreate path@, then the rest of the request will be
treated much like a PUT to the path entry . Otherwise , if it returns
@PostProcess a@ , then the action @a@ will be run . Defaults to
-- @PostProcess $ return ()@.
, contentTypesAccepted :: m [(MediaType, HaltT m ())]
-- ^ This is used similarly to @contentTypesProvided@, except that it is
-- for incoming resource representations -- for example, @PUT@ requests.
-- Handler functions usually want to use server specific functions to
-- access the incoming request body. Defaults to @[]@.
, variances :: m [HeaderName]
-- ^ This function should return a list of strings with header names that
-- should be included in a given response's Vary header. The standard
headers ( Accept , Accept - Encoding , Accept - Charset ,
Accept - Language ) do not need to be specified here as Webcrank will add
-- the correct elements of those automatically depending on resource
-- behavior. Defaults to @[]@.
, multipleChoices :: HaltT m Bool
^ If this returns @True@ , then it is assumed that multiple
-- representations of the response are possible and a single one cannot
be automatically chosen , so a @300 Multiple Choices@ will be sent
instead of a @200 OK@. Defaults to
, isConflict :: m Bool
^ If this returns @True@ , the client will receive a 409 Conflict .
Defaults to
, finishRequest :: m ()
-- ^ Called just before the final response is constructed and sent.
}
| A wrapper for the @'ServerAPI'@ and @'Resource'@ that should be used
-- to process requests to a path.
data ResourceData m = ResourceData
{ _resourceDataServerAPI :: ServerAPI m
, _resourceDataResource :: Resource m
}
makeClassy ''ResourceData
-- | Container used to keep track of the decision state and what is known
-- about response while processing a request.
data ReqData = ReqData
{ _reqDataRespMediaType :: MediaType
, _reqDataRespCharset :: Maybe Charset
, _reqDataRespEncoding :: Maybe Encoding
, _reqDataDispPath :: [Text]
, _reqDataRespHeaders :: HeadersMap
, _reqDataRespBody :: Maybe Body
}
makeClassy ''ReqData
| null | https://raw.githubusercontent.com/webcrank/webcrank.hs/c611a12ea129383823cc627405819537c31730e4/src/Webcrank/Internal/Types.hs | haskell | # LANGUAGE OverloadedStrings #
^ Get the request method of the current request.
^ The full URI of the request.
^ Get the request header of the current request.
^ Get the time the request was received.
| Response body type.
| Indicates whether client is authorized to perform the requested
operation on the resource. See @'isAuthorized'@.
requested operation on the resource.
the operation on the resource. The value is sent in the
| Indicates whether the resource supports multiple character sets
^ Indicates that the resource doesn't support any additional
character sets, all responses from the resource will have the
same character set, regardless of what the client requests.
^ The character sets the resource supports along with functions
for converting the response body.
| Weak or strong entity tags as used in HTTP ETag and @If-*-Match@ headers.
| Monad transformer for @'Resource'@ functions which can halt the request
processing early with an error or some other response. Values are created with
| How @POST@ requests should be treated. See @'postAction'@.
with @201 Created@, with the given path in the Location header.
@301 See Other@, redirecting the client to the new resource.
different (possibly new) resource.
decision process to determine how requests should be handled.
Each function has a type of either @m a@ or @'HaltT' m a@.
A resource function which yields a @HaltT m a@ value allows the function
to terminate the request processing early using @'halt'@ or
@'werror'@.
A resource that responds to @GET@ requests with an HTML response would be
written as
@
@
smart constructors useful creating resources.
^ @False@ will result in @503 Service Unavailable@. Defaults to @True@.
^ If a @Method@ not in this list is requested, then a @405 Method Not
^ If @Authorized@, the response will be @401 Unauthorized@.
^ @False@ will result in @501 Not Implemented@. Defaults to @True@.
@True@.
@True@.
^ If the OPTIONS method is supported and is used, the headers that
should appear in the response. Defaults to @[]@.
^ Content negotiation is driven by this function. For example, if a
client request includes an @Accept@ header with a value that does not
appear as a @MediaType@ in any of the tuples, then a @406 Not
Acceptable@ will be sent. If there is a matching @MediaType@, that
function is used to create the entity when a response should include one.
Defaults to @[]@.
Defaults to @NoCharset@.
^ Used on GET requests to ensure that the body is encoded.
requests return @[("identity", id), ("gzip", compress)]@ as this is all
that is needed to support gzip content encoding. Defaults to
@[]@.
comparison in conditional requests. Defaults to @mzero@.
and for comparison in conditional requests. Defaults to @mzero@.
Defaults to @mzero@.
callbacks will be invoked to determine whether the response should be
^ If the resource accepts POST requests to nonexistent resources, then
^ This is called when a DELETE request should be enacted, and should return
@True@.
^ This is only called after a successful @deleteResource@ call, and should
return @False@ if the deletion was accepted but cannot yet be guaranteed to
have finished. Defaults to @True@.
^ If POST requests should be treated as a request to put content into a
(potentially new) resource as opposed to being a generic submission for
processing, then this function should return @PostCreate path@. If it
does return @PostCreate path@, then the rest of the request will be
@PostProcess $ return ()@.
^ This is used similarly to @contentTypesProvided@, except that it is
for incoming resource representations -- for example, @PUT@ requests.
Handler functions usually want to use server specific functions to
access the incoming request body. Defaults to @[]@.
^ This function should return a list of strings with header names that
should be included in a given response's Vary header. The standard
the correct elements of those automatically depending on resource
behavior. Defaults to @[]@.
representations of the response are possible and a single one cannot
^ Called just before the final response is constructed and sent.
to process requests to a path.
| Container used to keep track of the decision state and what is known
about response while processing a request. | # LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE FunctionalDependencies #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TemplateHaskell #
module Webcrank.Internal.Types where
import Control.Applicative
import Control.Lens
import Control.Monad.Catch
import Control.Monad.RWS
import Control.Monad.Trans.Either
import Control.Monad.Trans.Maybe
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString.UTF8 as B
import Data.CaseInsensitive (CI)
import Data.HashMap.Strict (HashMap)
import Data.List.NonEmpty (NonEmpty)
import Data.Text (Text)
import Network.HTTP.Date
import Network.HTTP.Media
import Network.HTTP.Types
import Prelude
import Webcrank.Internal.Headers
| A dictionary of functions that Webcrank needs in order to make decisions .
data ServerAPI m = ServerAPI
{ srvGetRequestMethod :: m Method
, srvGetRequestURI :: m ByteString
, srvGetRequestHeader :: HeaderName -> m (Maybe ByteString)
, srvGetRequestTime :: m HTTPDate
}
type HeadersMap = HashMap HeaderName [ByteString]
| Content coding type , e.g. gzip , decompress . See @'encodingsProvided'@.
type Encoding = CI ByteString
| Character set type , e.g. utf-8 . See
type Charset = CI ByteString
type Body = LB.ByteString
data Authorized
= Authorized
^ Tells Webcrank that the client is authorized to perform the
| Unauthorized ByteString
^ Tells Webcrank that the client is not authorized to perform
- Authenticate@ header of the response ,
e.g. @Basic realm="Webcrank"@.
or not . See
data CharsetsProvided
= NoCharset
| CharsetsProvided (NonEmpty (Charset, Body -> Body))
data ETag = StrongETag ByteString | WeakETag ByteString deriving Eq
instance Show ETag where
show e = B.toString $ case e of
StrongETag v -> "\"" <> v <> "\""
WeakETag v -> "W/\"" <> v <> "\""
instance RenderHeader ETag where
renderHeader = \case
StrongETag v -> quotedString v
WeakETag v -> "W/" <> quotedString v
data Halt = Halt Status | Error Status LB.ByteString
deriving (Eq, Show)
the smart constructors @'werror'@ and @'halt'@.
newtype HaltT m a = HaltT { unHaltT :: EitherT Halt m a }
deriving
( Functor
, Applicative
, Monad
, MonadIO
, MonadTrans
, MonadReader r
, MonadState s
, MonadWriter w
, MonadThrow
, MonadCatch
)
data PostAction m
= PostCreate [Text]
^ Treat @POST@s as creating new resources and respond
| PostCreateRedir [Text]
^ Treat @POST@s as creating new resources and respond with
| PostProcess (HaltT m ())
^ Treat @POST@s as a process which is executed without redirect .
| PostProcessRedir (HaltT m ByteString)
^ Treat @POST@s as a process and redirect the client to a
data LogData = LogData
instance Monoid LogData where
mempty = LogData
mappend _ _ = LogData
| A is a dictionary of functions which are used in the Webcrank
The defaults documented are used by the @'resource'@ smart constructor .
myResource = resource { contentTypesProvided = return $ [ ( " text / html " , return " Hello world ! " ) ] }
@'responseWithBody'@ and @'responseWithHtml'@ are additional
data Resource m = Resource
{ serviceAvailable :: HaltT m Bool
, uriTooLong :: HaltT m Bool
^ @True@ will result in @414 Request Too Long@. Defaults to
, allowedMethods :: m [Method]
Allowed@ will be sent . Defaults to " , " HEAD"]@.
, malformedRequest :: HaltT m Bool
^ @True@ will result in @400 Bad Request@. Defaults to
, isAuthorized :: HaltT m Authorized
@Unauthorized@ will be used as the challenge in the - Authenticate@
header , e.g. @Basic realm="Webcrank"@.
Defaults to @Authorized@.
, forbidden :: HaltT m Bool
^ @True@ will result in @403 Forbidden@. to
, validContentHeaders :: HaltT m Bool
, knownContentType :: HaltT m Bool
^ @False@ will result in @415 Unsupported Media Type@. Defaults to
, validEntityLength :: HaltT m Bool
^ @False@ will result in @413 Request Entity Too Large@. Defaults to
, options :: m ResponseHeaders
, contentTypesProvided :: m [(MediaType, HaltT m Body)]
, charsetsProvided :: m CharsetsProvided
^ Used on GET requests to ensure that the entity is in @Charset@.
, encodingsProvided :: m [(Encoding, Body -> Body)]
One useful setting is to have the function check on method , and on GET
, resourceExists :: HaltT m Bool
^ @False@ will result in @404 Not Found@. Defaults to @True@.
, generateETag :: MaybeT m ETag
^ If this returns an @ETag@ , it will be used for the ETag header and for
, lastModified :: MaybeT m HTTPDate
^ If this returns a @HTTPDate@ , it will be used for the Last - Modified header
, expires :: MaybeT m HTTPDate
^ If this returns a @HTTPDate@ , it will be used for the Expires header .
, movedPermanently :: MaybeT (HaltT m) ByteString
^ If this returns a URI , the client will receive a 301 Moved Permanently
with the URI in the Location header . Defaults to @mzero@.
, movedTemporarily :: MaybeT (HaltT m) ByteString
^ If this returns a URI , the client will receive a 307 Temporary Redirect
with URI in the Location header . Defaults to @mzero@.
, previouslyExisted :: HaltT m Bool
^ If this returns @True@ , the @movedPermanently@ and @movedTemporarily@
301 Moved Permanently , 307 Temporary Redirect , or 410 Gone . Defaults
to
, allowMissingPost :: HaltT m Bool
this should return @True@. Defaults to
, deleteResource :: HaltT m Bool
@True@ if the deletion succeeded or has been accepted . Defaults to
, deleteCompleted :: HaltT m Bool
, postAction :: m (PostAction m)
treated much like a PUT to the path entry . Otherwise , if it returns
@PostProcess a@ , then the action @a@ will be run . Defaults to
, contentTypesAccepted :: m [(MediaType, HaltT m ())]
, variances :: m [HeaderName]
headers ( Accept , Accept - Encoding , Accept - Charset ,
Accept - Language ) do not need to be specified here as Webcrank will add
, multipleChoices :: HaltT m Bool
^ If this returns @True@ , then it is assumed that multiple
be automatically chosen , so a @300 Multiple Choices@ will be sent
instead of a @200 OK@. Defaults to
, isConflict :: m Bool
^ If this returns @True@ , the client will receive a 409 Conflict .
Defaults to
, finishRequest :: m ()
}
| A wrapper for the @'ServerAPI'@ and @'Resource'@ that should be used
data ResourceData m = ResourceData
{ _resourceDataServerAPI :: ServerAPI m
, _resourceDataResource :: Resource m
}
makeClassy ''ResourceData
data ReqData = ReqData
{ _reqDataRespMediaType :: MediaType
, _reqDataRespCharset :: Maybe Charset
, _reqDataRespEncoding :: Maybe Encoding
, _reqDataDispPath :: [Text]
, _reqDataRespHeaders :: HeadersMap
, _reqDataRespBody :: Maybe Body
}
makeClassy ''ReqData
|
cd41987b0bb0d720d441f4787d32e7c1bae5e151c6493ee34f34e9d4534d1936 | wedesoft/sfsim25 | cloudmap.clj | (require '[clojure.core.matrix :refer (matrix eseq mmul)]
'[clojure.math :refer (to-radians)]
'[sfsim25.matrix :refer :all]
'[sfsim25.render :refer :all]
'[sfsim25.shaders :refer :all])
(import '[org.lwjgl.opengl Display DisplayMode GL11 GL12 GL13 GL20 GL30]
'[mikera.matrixx Matrix])
(Display/setTitle "scratch")
(Display/setDisplayMode (DisplayMode. 640 400))
(Display/create)
;
(def image {:width 3 :height 3 :data (float-array [0 1 0 1 0 1 0 1 0])})
(def tex {:texture (GL11/glGenTextures) :target GL13/GL_TEXTURE_CUBE_MAP :width 3 :height 3 :depth 6})
(GL11/glBindTexture GL13/GL_TEXTURE_CUBE_MAP (:texture tex))
(def buffer (make-float-buffer (:data image)))
(GL11/glTexImage2D GL13/GL_TEXTURE_CUBE_MAP_POSITIVE_X 0 GL30/GL_R32F (:width image) (:height image) 0 GL11/GL_RED GL11/GL_FLOAT buffer)
(GL11/glTexImage2D GL13/GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0 GL30/GL_R32F (:width image) (:height image) 0 GL11/GL_RED GL11/GL_FLOAT buffer)
(GL11/glTexImage2D GL13/GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0 GL30/GL_R32F (:width image) (:height image) 0 GL11/GL_RED GL11/GL_FLOAT buffer)
(GL11/glTexImage2D GL13/GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0 GL30/GL_R32F (:width image) (:height image) 0 GL11/GL_RED GL11/GL_FLOAT buffer)
(GL11/glTexImage2D GL13/GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0 GL30/GL_R32F (:width image) (:height image) 0 GL11/GL_RED GL11/GL_FLOAT buffer)
(GL11/glTexImage2D GL13/GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0 GL30/GL_R32F (:width image) (:height image) 0 GL11/GL_RED GL11/GL_FLOAT buffer)
(GL11/glTexParameteri GL13/GL_TEXTURE_CUBE_MAP GL11/GL_TEXTURE_MIN_FILTER GL11/GL_LINEAR)
(GL11/glTexParameteri GL13/GL_TEXTURE_CUBE_MAP GL11/GL_TEXTURE_MAG_FILTER GL11/GL_LINEAR)
(GL11/glTexParameteri GL13/GL_TEXTURE_CUBE_MAP GL11/GL_TEXTURE_WRAP_S GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri GL13/GL_TEXTURE_CUBE_MAP GL11/GL_TEXTURE_WRAP_T GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri GL13/GL_TEXTURE_CUBE_MAP GL12/GL_TEXTURE_WRAP_R GL12/GL_CLAMP_TO_EDGE)
(def vertex
"#version 410 core
uniform float aspect;
in vec2 point;
out VS_OUT
{
vec2 point;
} vs_out;
void main()
{
gl_Position = vec4(point, 0, 1);
vs_out.point = point * vec2(aspect, 1);
}")
(def fragment
"#version 410 core
uniform samplerCube cubemap;
uniform mat3 rotation;
in VS_OUT
{
vec2 point;
} fs_in;
out vec3 fragColor;
vec3 convert_cubemap_index(vec3 idx, int size);
void main()
{
if (length(fs_in.point) <= 1) {
float z = -sqrt(1 - fs_in.point.x * fs_in.point.x - fs_in.point.y * fs_in.point.y);
vec3 pos = vec3(fs_in.point, z);
float v = texture(cubemap, convert_cubemap_index(rotation * pos, 3)).r;
fragColor = vec3(v, v, v);
} else
fragColor = vec3(0, 0, 0);
}")
(def program (make-program :vertex [vertex] :fragment [fragment convert-cubemap-index]))
(use-program program)
(uniform-sampler program :cubemap 0)
(uniform-float program :aspect (/ (Display/getWidth) (Display/getHeight)))
(use-textures tex)
(def indices [0 1 3 2])
(def vertices [-1 -1, 1 -1, -1 1, 1 1])
(def vao (make-vertex-array-object program indices vertices [:point 2]))
(def t0 (atom (System/currentTimeMillis)))
(def angle (atom 0.0))
(while (not (Display/isCloseRequested))
(let [t1 (System/currentTimeMillis)
dt (- t1 @t0)]
(swap! angle + (* 0.001 dt))
(onscreen-render (Display/getWidth) (Display/getHeight)
(clear (matrix [0 0 0]))
(uniform-matrix3 program :rotation (mmul (rotation-y @angle) (rotation-x (to-radians 30))))
(render-quads vao))
(swap! t0 + dt)))
(destroy-vertex-array-object vao)
(destroy-program program)
(destroy-texture tex)
(Display/destroy)
| null | https://raw.githubusercontent.com/wedesoft/sfsim25/5810e261c775b21abe7b8c7d6a07de2a7398e099/etc/cloudmap.clj | clojure | (require '[clojure.core.matrix :refer (matrix eseq mmul)]
'[clojure.math :refer (to-radians)]
'[sfsim25.matrix :refer :all]
'[sfsim25.render :refer :all]
'[sfsim25.shaders :refer :all])
(import '[org.lwjgl.opengl Display DisplayMode GL11 GL12 GL13 GL20 GL30]
'[mikera.matrixx Matrix])
(Display/setTitle "scratch")
(Display/setDisplayMode (DisplayMode. 640 400))
(Display/create)
(def image {:width 3 :height 3 :data (float-array [0 1 0 1 0 1 0 1 0])})
(def tex {:texture (GL11/glGenTextures) :target GL13/GL_TEXTURE_CUBE_MAP :width 3 :height 3 :depth 6})
(GL11/glBindTexture GL13/GL_TEXTURE_CUBE_MAP (:texture tex))
(def buffer (make-float-buffer (:data image)))
(GL11/glTexImage2D GL13/GL_TEXTURE_CUBE_MAP_POSITIVE_X 0 GL30/GL_R32F (:width image) (:height image) 0 GL11/GL_RED GL11/GL_FLOAT buffer)
(GL11/glTexImage2D GL13/GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0 GL30/GL_R32F (:width image) (:height image) 0 GL11/GL_RED GL11/GL_FLOAT buffer)
(GL11/glTexImage2D GL13/GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0 GL30/GL_R32F (:width image) (:height image) 0 GL11/GL_RED GL11/GL_FLOAT buffer)
(GL11/glTexImage2D GL13/GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0 GL30/GL_R32F (:width image) (:height image) 0 GL11/GL_RED GL11/GL_FLOAT buffer)
(GL11/glTexImage2D GL13/GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0 GL30/GL_R32F (:width image) (:height image) 0 GL11/GL_RED GL11/GL_FLOAT buffer)
(GL11/glTexImage2D GL13/GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0 GL30/GL_R32F (:width image) (:height image) 0 GL11/GL_RED GL11/GL_FLOAT buffer)
(GL11/glTexParameteri GL13/GL_TEXTURE_CUBE_MAP GL11/GL_TEXTURE_MIN_FILTER GL11/GL_LINEAR)
(GL11/glTexParameteri GL13/GL_TEXTURE_CUBE_MAP GL11/GL_TEXTURE_MAG_FILTER GL11/GL_LINEAR)
(GL11/glTexParameteri GL13/GL_TEXTURE_CUBE_MAP GL11/GL_TEXTURE_WRAP_S GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri GL13/GL_TEXTURE_CUBE_MAP GL11/GL_TEXTURE_WRAP_T GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri GL13/GL_TEXTURE_CUBE_MAP GL12/GL_TEXTURE_WRAP_R GL12/GL_CLAMP_TO_EDGE)
(def vertex
"#version 410 core
out VS_OUT
{
void main()
{
}")
(def fragment
"#version 410 core
in VS_OUT
{
void main()
{
if (length(fs_in.point) <= 1) {
} else
}")
(def program (make-program :vertex [vertex] :fragment [fragment convert-cubemap-index]))
(use-program program)
(uniform-sampler program :cubemap 0)
(uniform-float program :aspect (/ (Display/getWidth) (Display/getHeight)))
(use-textures tex)
(def indices [0 1 3 2])
(def vertices [-1 -1, 1 -1, -1 1, 1 1])
(def vao (make-vertex-array-object program indices vertices [:point 2]))
(def t0 (atom (System/currentTimeMillis)))
(def angle (atom 0.0))
(while (not (Display/isCloseRequested))
(let [t1 (System/currentTimeMillis)
dt (- t1 @t0)]
(swap! angle + (* 0.001 dt))
(onscreen-render (Display/getWidth) (Display/getHeight)
(clear (matrix [0 0 0]))
(uniform-matrix3 program :rotation (mmul (rotation-y @angle) (rotation-x (to-radians 30))))
(render-quads vao))
(swap! t0 + dt)))
(destroy-vertex-array-object vao)
(destroy-program program)
(destroy-texture tex)
(Display/destroy)
| |
0f5a1bf1bdcb2acc853d561c0344fe14c9c983ef88d3067ecc570c4551acf52a | jordanthayer/ocaml-search | wrstrm.ml | $ I d : wrstream.ml , v 1.1 2003/11/18 14:15:11 ruml Exp $
stream utility code
streams are heavier than channels - they allow peeking .
they can be made from channels , strings , or arbitrary generating functions .
stream utility code
streams are heavier than channels - they allow peeking.
they can be made from channels, strings, or arbitrary generating functions.
*)
let empty_p strm =
(* odd implementation, but shouldn't need to allocate memory *)
try
Stream.empty strm;
true
with Stream.Failure -> false
let rec eat_white strm =
* eats whitespace : space , tab , linefeed , formfeed , return
match Stream.peek strm with
Some c ->
if Wrchar.white_p c
then (Stream.junk strm;
eat_white strm)
else ()
| None -> ()
let rec eat_until e strm =
* removes elements from [ ] until something equal to [ e ] is next
match Stream.peek strm with
Some x ->
if x = e
then ()
else (Stream.junk strm;
eat_until e strm)
| None -> ()
let eat_through e strm =
* removes elements from [ ] until something equal to [ e ] is removed
eat_until e strm;
Stream.junk strm
let rest_string strm =
let b = Buffer.create 10 in
try
while true do
Buffer.add_char b (Stream.next strm)
done;
failwith "stream never ended?"
with Stream.Failure ->
Buffer.contents b
(******************* a generic lexer *****************)
(** like Genlex.make_lexer but doesn't have any hang-ups about
so-called special characters. Keywords and identifiers are any
sequence of whitespace-delimited non-whitespace characters that aren't
strings or character literals or integers or floats. Skips nested
comments. *)
let rec eat_comment strm =
(** assumes opening has been read. handles nested comments *)
let finished = ref false in
while (not !finished) do
try
match Stream.next strm with
'*' -> (match Stream.next strm with
')' -> finished := true
| _ -> ())
| '(' -> (match Stream.next strm with
'*' -> eat_comment strm
| _ -> ())
| _ -> ()
with Stream.Failure -> raise Parsing.Parse_error
done
let read_char_esc strm =
(** assumes open slash has been read *)
try
let c = Stream.next strm in
match c with
'0'..'9' ->
let second = (Stream.next strm) in
char_of_int (((Wrchar.int c) * 100) +
((Wrchar.int second) * 10) +
(Wrchar.int (Stream.next strm)))
| 'n' -> '\n'
| 'r' -> '\r'
| 't' -> '\t'
| 'b' -> '\b'
| '\\' | '"' | '\'' -> c
| _ -> raise Parsing.Parse_error
with Stream.Failure -> raise Parsing.Parse_error
let read_char strm =
(** assumes opening quote has been read *)
try
match Stream.next strm with
'\\' -> read_char_esc strm
| c -> c
with Stream.Failure -> raise Parsing.Parse_error
let read_string strm =
(** assumes opening double quote has been read *)
let b = Buffer.create 80
and finished = ref false in
while (not !finished) do
try
match Stream.next strm with
'\\' -> Buffer.add_char b (read_char_esc strm)
| '"' -> finished := true
| c -> Buffer.add_char b c
with Stream.Failure -> raise Parsing.Parse_error
done;
Buffer.contents b
let test_read_string () =
let s = Wrstr.random 10 in
Wrutils.pr " string: \"%s\"\n" s;
let escaped = String.escaped s in
Wrutils.pr "escaped: \"%s\"\n" escaped;
let s2 = read_string (Stream.of_string (escaped ^ "\"")) in
Wrutils.pr " got: \"%s\"\n" s2;
if s = s2 then
Wrutils.pr "matches.\n"
else
Wrutils.pr "FAILED!!!.\n"
let read_num ?(neg = false) ?(leading = '0') strm =
(** [(+-)](0-9)*[.(0-9)*][(eE)[(-+)](0-9)*] *)
let negative = ( leading = = ' - ' )
and = ref 0 in
if leading = = ' + ' then
( )
else if Wrchar.is_digit leading then
and accum = ref 0 in
if leading == '+' then
()
else if Wrchar.is_digit leading then
*)
failwith "numbers not implemented yet"
let read_tok c strm =
(** read token, starting with [c] *)
let b = Buffer.create 80
and finished = ref false in
Buffer.add_char b c;
while (not !finished) do
try
let c = Stream.next strm in
if Wrchar.white_p c
then finished := true
else Buffer.add_char b c
with Stream.Failure -> finished := true
done;
Buffer.contents b
let make_lexer keys strm =
* returns a Genlex.token stream
let ident_or_key char =
let s = read_tok char strm in
if List.mem s keys
then Genlex.Kwd s
else Genlex.Ident s
in
let rec next_token i =
* returns an optional Genlex.token
eat_white strm;
try
let c = Stream.next strm in
match c with
'\'' -> Some (Genlex.Char (read_char strm))
| '"' -> Some (Genlex.String (read_string strm))
| '0'..'9' as c -> Some (read_num ~leading:c strm)
| '(' -> (match Stream.peek strm with
Some '*' ->
eat_comment strm;
next_token i
| _ -> Some (ident_or_key '('))
| '-' -> Some (match Stream.peek strm with
Some x when (match x with
'0'..'9' -> true
| _ -> false) ->
read_num ~neg:true strm
| _ -> ident_or_key '-')
| c -> Some (ident_or_key c)
with Stream.Failure -> None
in
Stream.from next_token
(******************* other functions ********************)
let parse_string strm =
(** given a char stream, eats whitespace then reads an OCaml
formatted string *)
eat_white strm;
assert ((Stream.peek strm) = Some '"');
Stream.junk strm;
read_string strm
let parse_strings strm =
(** given a char stream, returns list of OCaml strings *)
let rec get_more () =
eat_white strm;
if empty_p strm then
[]
else
let this = parse_string strm in
this::(get_more ())
in
get_more ()
let rec all_string_tokens strm =
* returns a list of all and any strings available at the front of
the given
the given Genlex.token strm *)
match Stream.peek strm with
Some (Genlex.String x) ->
Stream.junk strm;
x::(all_string_tokens strm)
| _ -> []
let rec parse_strings strm = parser
( * * returns a list of all and any strings available at the front of strm
let rec parse_strings strm = parser
(** returns a list of all and any strings available at the front of strm *)
[< 'Genlex.String s ; more = parse_strings strm >] -> s::more
| [< >] -> []
*)
EOF
| null | https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/wrutils/wrstrm.ml | ocaml | odd implementation, but shouldn't need to allocate memory
****************** a generic lexer ****************
* like Genlex.make_lexer but doesn't have any hang-ups about
so-called special characters. Keywords and identifiers are any
sequence of whitespace-delimited non-whitespace characters that aren't
strings or character literals or integers or floats. Skips nested
comments.
* assumes opening has been read. handles nested comments
* assumes open slash has been read
* assumes opening quote has been read
* assumes opening double quote has been read
* [(+-)](0-9)*[.(0-9)*][(eE)[(-+)](0-9)*]
* read token, starting with [c]
****************** other functions *******************
* given a char stream, eats whitespace then reads an OCaml
formatted string
* given a char stream, returns list of OCaml strings
* returns a list of all and any strings available at the front of strm | $ I d : wrstream.ml , v 1.1 2003/11/18 14:15:11 ruml Exp $
stream utility code
streams are heavier than channels - they allow peeking .
they can be made from channels , strings , or arbitrary generating functions .
stream utility code
streams are heavier than channels - they allow peeking.
they can be made from channels, strings, or arbitrary generating functions.
*)
let empty_p strm =
try
Stream.empty strm;
true
with Stream.Failure -> false
let rec eat_white strm =
* eats whitespace : space , tab , linefeed , formfeed , return
match Stream.peek strm with
Some c ->
if Wrchar.white_p c
then (Stream.junk strm;
eat_white strm)
else ()
| None -> ()
let rec eat_until e strm =
* removes elements from [ ] until something equal to [ e ] is next
match Stream.peek strm with
Some x ->
if x = e
then ()
else (Stream.junk strm;
eat_until e strm)
| None -> ()
let eat_through e strm =
* removes elements from [ ] until something equal to [ e ] is removed
eat_until e strm;
Stream.junk strm
let rest_string strm =
let b = Buffer.create 10 in
try
while true do
Buffer.add_char b (Stream.next strm)
done;
failwith "stream never ended?"
with Stream.Failure ->
Buffer.contents b
let rec eat_comment strm =
let finished = ref false in
while (not !finished) do
try
match Stream.next strm with
'*' -> (match Stream.next strm with
')' -> finished := true
| _ -> ())
| '(' -> (match Stream.next strm with
'*' -> eat_comment strm
| _ -> ())
| _ -> ()
with Stream.Failure -> raise Parsing.Parse_error
done
let read_char_esc strm =
try
let c = Stream.next strm in
match c with
'0'..'9' ->
let second = (Stream.next strm) in
char_of_int (((Wrchar.int c) * 100) +
((Wrchar.int second) * 10) +
(Wrchar.int (Stream.next strm)))
| 'n' -> '\n'
| 'r' -> '\r'
| 't' -> '\t'
| 'b' -> '\b'
| '\\' | '"' | '\'' -> c
| _ -> raise Parsing.Parse_error
with Stream.Failure -> raise Parsing.Parse_error
let read_char strm =
try
match Stream.next strm with
'\\' -> read_char_esc strm
| c -> c
with Stream.Failure -> raise Parsing.Parse_error
let read_string strm =
let b = Buffer.create 80
and finished = ref false in
while (not !finished) do
try
match Stream.next strm with
'\\' -> Buffer.add_char b (read_char_esc strm)
| '"' -> finished := true
| c -> Buffer.add_char b c
with Stream.Failure -> raise Parsing.Parse_error
done;
Buffer.contents b
let test_read_string () =
let s = Wrstr.random 10 in
Wrutils.pr " string: \"%s\"\n" s;
let escaped = String.escaped s in
Wrutils.pr "escaped: \"%s\"\n" escaped;
let s2 = read_string (Stream.of_string (escaped ^ "\"")) in
Wrutils.pr " got: \"%s\"\n" s2;
if s = s2 then
Wrutils.pr "matches.\n"
else
Wrutils.pr "FAILED!!!.\n"
let read_num ?(neg = false) ?(leading = '0') strm =
let negative = ( leading = = ' - ' )
and = ref 0 in
if leading = = ' + ' then
( )
else if Wrchar.is_digit leading then
and accum = ref 0 in
if leading == '+' then
()
else if Wrchar.is_digit leading then
*)
failwith "numbers not implemented yet"
let read_tok c strm =
let b = Buffer.create 80
and finished = ref false in
Buffer.add_char b c;
while (not !finished) do
try
let c = Stream.next strm in
if Wrchar.white_p c
then finished := true
else Buffer.add_char b c
with Stream.Failure -> finished := true
done;
Buffer.contents b
let make_lexer keys strm =
* returns a Genlex.token stream
let ident_or_key char =
let s = read_tok char strm in
if List.mem s keys
then Genlex.Kwd s
else Genlex.Ident s
in
let rec next_token i =
* returns an optional Genlex.token
eat_white strm;
try
let c = Stream.next strm in
match c with
'\'' -> Some (Genlex.Char (read_char strm))
| '"' -> Some (Genlex.String (read_string strm))
| '0'..'9' as c -> Some (read_num ~leading:c strm)
| '(' -> (match Stream.peek strm with
Some '*' ->
eat_comment strm;
next_token i
| _ -> Some (ident_or_key '('))
| '-' -> Some (match Stream.peek strm with
Some x when (match x with
'0'..'9' -> true
| _ -> false) ->
read_num ~neg:true strm
| _ -> ident_or_key '-')
| c -> Some (ident_or_key c)
with Stream.Failure -> None
in
Stream.from next_token
let parse_string strm =
eat_white strm;
assert ((Stream.peek strm) = Some '"');
Stream.junk strm;
read_string strm
let parse_strings strm =
let rec get_more () =
eat_white strm;
if empty_p strm then
[]
else
let this = parse_string strm in
this::(get_more ())
in
get_more ()
let rec all_string_tokens strm =
* returns a list of all and any strings available at the front of
the given
the given Genlex.token strm *)
match Stream.peek strm with
Some (Genlex.String x) ->
Stream.junk strm;
x::(all_string_tokens strm)
| _ -> []
let rec parse_strings strm = parser
( * * returns a list of all and any strings available at the front of strm
let rec parse_strings strm = parser
[< 'Genlex.String s ; more = parse_strings strm >] -> s::more
| [< >] -> []
*)
EOF
|
3a9ac4d9cf3edd3360dc66050af2dc08a5fac72d0d5f7f86fa4e8003a9bf3ffd | clash-lang/clash-prelude | XException.hs | |
Copyright : ( C ) 2016 , University of Twente ,
2017 , Myrtle Software Ltd , QBayLogic , Google Inc.
License : BSD2 ( see the file LICENSE )
Maintainer : < >
' X ' : An exception for uninitialized values
> > > show ( errorX " undefined " : : Integer , 4 : : Int )
" ( * * * Exception : X : undefined
CallStack ( from HasCallStack ):
...
> > > showX ( errorX " undefined " : : Integer , 4 : : Int )
" ( X,4 ) "
Copyright : (C) 2016, University of Twente,
2017, Myrtle Software Ltd, QBayLogic, Google Inc.
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <>
'X': An exception for uninitialized values
>>> show (errorX "undefined" :: Integer, 4 :: Int)
"(*** Exception: X: undefined
CallStack (from HasCallStack):
...
>>> showX (errorX "undefined" :: Integer, 4 :: Int)
"(X,4)"
-}
{-# LANGUAGE DefaultSignatures #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MagicHash #
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeOperators #-}
# LANGUAGE Trustworthy #
# OPTIONS_GHC -Wno - orphans #
module Clash.XException
( -- * 'X': An exception for uninitialized values
XException, errorX, isX, maybeX
* Printing ' X ' exceptions as \"X\ "
, ShowX (..), showsX, printX, showsPrecXWith
-- * Strict evaluation
, seqX
-- * Structured undefined
, Undefined (..)
)
where
import Control.Exception (Exception, catch, evaluate, throw)
import Control.DeepSeq (NFData, rnf)
import Data.Complex (Complex)
import Data.Foldable (toList)
import Data.Int (Int8,Int16,Int32,Int64)
import Data.Ord (Down (Down))
import Data.Ratio (Ratio)
import Data.Sequence (Seq)
import Data.Word (Word8,Word16,Word32,Word64)
import GHC.Exts (Char (C#), Double (D#), Float (F#), Int (I#), Word (W#))
import GHC.Generics
import GHC.Show (appPrec)
import GHC.Stack (HasCallStack, callStack, prettyCallStack)
import System.IO.Unsafe (unsafeDupablePerformIO)
-- | An exception representing an \"uninitialised\" value.
newtype XException = XException String
instance Show XException where
show (XException s) = s
instance Exception XException
| Like ' error ' , but throwing an ' XException ' instead of an ' ErrorCall '
--
-- The 'ShowX' methods print these error-values as \"X\"; instead of error'ing
-- out with an exception.
errorX :: HasCallStack => String -> a
errorX msg = throw (XException ("X: " ++ msg ++ "\n" ++ prettyCallStack callStack))
-- | Like 'seq', however, whereas 'seq' will always do:
--
-- > seq _|_ b = _|_
--
' ' will do :
--
> ( XException msg ) b = b
> _ | _ b = _ | _
seqX :: a -> b -> b
seqX a b = unsafeDupablePerformIO
(catch (evaluate a >> return b) (\(XException _) -> return b))
# NOINLINE seqX #
infixr 0 `seqX`
-- | Fully evaluate a value, returning 'Nothing' if is throws 'XException'.
--
> maybeX 42 = Just 42
> maybeX ( msg ) = Nothing
-- > maybeX _|_ = _|_
maybeX :: NFData a => a -> Maybe a
maybeX = either (const Nothing) Just . isX
-- | Fully evaluate a value, returning @'Left' msg@ if is throws 'XException'.
--
> isX 42 = Right 42
> isX ( XException msg ) = Left msg
-- > isX _|_ = _|_
isX :: NFData a => a -> Either String a
isX a = unsafeDupablePerformIO
(catch (evaluate (rnf a) >> return (Right a)) (\(XException msg) -> return (Left msg)))
# NOINLINE isX #
showXWith :: (a -> ShowS) -> a -> ShowS
showXWith f x =
\s -> unsafeDupablePerformIO (catch (f <$> evaluate x <*> pure s)
(\(XException _) -> return ('X': s)))
-- | Use when you want to create a 'ShowX' instance where:
--
- There is no ' Generic ' instance for your data type
- The ' Generic ' derived ShowX method would traverse into the ( hidden )
-- implementation details of your data type, and you just want to show the
-- entire value as \"X\".
--
-- Can be used like:
--
-- > data T = ...
-- >
-- > instance Show T where ...
-- >
> instance T where
-- > showsPrecX = showsPrecXWith showsPrec
showsPrecXWith :: (Int -> a -> ShowS) -> Int -> a -> ShowS
showsPrecXWith f n = showXWith (f n)
-- | Like 'shows', but values that normally throw an 'X' exception are
converted to \"X\ " , instead of error'ing out with an exception .
showsX :: ShowX a => a -> ShowS
showsX = showsPrecX 0
-- | Like 'print', but values that normally throw an 'X' exception are
converted to \"X\ " , instead of error'ing out with an exception
printX :: ShowX a => a -> IO ()
printX x = putStrLn $ showX x
-- | Like the 'Show' class, but values that normally throw an 'X' exception are
converted to \"X\ " , instead of error'ing out with an exception .
--
> > > show ( errorX " undefined " : : Integer , 4 : : Int )
-- "(*** Exception: X: undefined
CallStack ( from HasCallStack ):
-- ...
> > > showX ( errorX " undefined " : : Integer , 4 : : Int )
-- "(X,4)"
--
-- Can be derived using 'GHC.Generics':
--
-- > {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
-- >
> import Clash . Prelude
> import
-- >
-- > data T = MkTA Int | MkTB Bool
> deriving ( Show , Generic , )
class ShowX a where
-- | Like 'showsPrec', but values that normally throw an 'X' exception are
converted to \"X\ " , instead of error'ing out with an exception .
showsPrecX :: Int -> a -> ShowS
-- | Like 'show', but values that normally throw an 'X' exception are
converted to \"X\ " , instead of error'ing out with an exception .
showX :: a -> String
showX x = showsX x ""
-- | Like 'showList', but values that normally throw an 'X' exception are
converted to \"X\ " , instead of error'ing out with an exception .
showListX :: [a] -> ShowS
showListX ls s = showListX__ showsX ls s
default showsPrecX :: (Generic a, GShowX (Rep a)) => Int -> a -> ShowS
showsPrecX = genericShowsPrecX
showListX__ :: (a -> ShowS) -> [a] -> ShowS
showListX__ showx = showXWith go
where
go [] s = "[]" ++ s
go (x:xs) s = '[' : showx x (showl xs)
where
showl [] = ']':s
showl (y:ys) = ',' : showx y (showl ys)
data ShowType = Rec -- Record
| Tup -- Tuple
| Pref -- Prefix
| Inf String -- Infix
genericShowsPrecX :: (Generic a, GShowX (Rep a)) => Int -> a -> ShowS
genericShowsPrecX n = gshowsPrecX Pref n . from
instance ShowX ()
instance (ShowX a, ShowX b) => ShowX (a,b)
instance (ShowX a, ShowX b, ShowX c) => ShowX (a,b,c)
instance (ShowX a, ShowX b, ShowX c, ShowX d) => ShowX (a,b,c,d)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e) => ShowX (a,b,c,d,e)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f) => ShowX (a,b,c,d,e,f)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g) => ShowX (a,b,c,d,e,f,g)
Show is defined up to 15 - tuples , but only has Generic instances
up to 7 - tuples , hence we need these orphan instances .
deriving instance Generic ((,,,,,,,) a b c d e f g h)
deriving instance Generic ((,,,,,,,,) a b c d e f g h i)
deriving instance Generic ((,,,,,,,,,) a b c d e f g h i j)
deriving instance Generic ((,,,,,,,,,,) a b c d e f g h i j k)
deriving instance Generic ((,,,,,,,,,,,) a b c d e f g h i j k l)
deriving instance Generic ((,,,,,,,,,,,,) a b c d e f g h i j k l m)
deriving instance Generic ((,,,,,,,,,,,,,) a b c d e f g h i j k l m n)
deriving instance Generic ((,,,,,,,,,,,,,,) a b c d e f g h i j k l m n o)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h) => ShowX (a,b,c,d,e,f,g,h)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i) => ShowX (a,b,c,d,e,f,g,h,i)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i, ShowX j)
=> ShowX (a,b,c,d,e,f,g,h,i,j)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i, ShowX j, ShowX k)
=> ShowX (a,b,c,d,e,f,g,h,i,j,k)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i, ShowX j, ShowX k, ShowX l)
=> ShowX (a,b,c,d,e,f,g,h,i,j,k,l)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i, ShowX j, ShowX k, ShowX l
,ShowX m)
=> ShowX (a,b,c,d,e,f,g,h,i,j,k,l,m)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i, ShowX j, ShowX k, ShowX l
,ShowX m, ShowX n)
=> ShowX (a,b,c,d,e,f,g,h,i,j,k,l,m,n)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i, ShowX j, ShowX k, ShowX l
,ShowX m, ShowX n, ShowX o)
=> ShowX (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o)
instance {-# OVERLAPPABLE #-} ShowX a => ShowX [a] where
showsPrecX _ = showListX
instance ShowX Char where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Bool
instance ShowX Double where
showsPrecX = showsPrecXWith showsPrec
instance ShowX a => ShowX (Down a) where
showsPrecX = showsPrecXWith showsPrecX
instance (ShowX a, ShowX b) => ShowX (Either a b)
instance ShowX Float where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Int where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Int8 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Int16 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Int32 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Int64 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Integer where
showsPrecX = showsPrecXWith showsPrec
instance ShowX a => ShowX (Seq a) where
showsPrecX _ = showListX . toList
instance ShowX Word where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Word8 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Word16 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Word32 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Word64 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX a => ShowX (Maybe a)
instance ShowX a => ShowX (Ratio a) where
showsPrecX = showsPrecXWith showsPrecX
instance ShowX a => ShowX (Complex a)
instance {-# OVERLAPPING #-} ShowX String where
showsPrecX = showsPrecXWith showsPrec
class GShowX f where
gshowsPrecX :: ShowType -> Int -> f a -> ShowS
isNullary :: f a -> Bool
isNullary = error "generic showX (isNullary): unnecessary case"
instance GShowX U1 where
gshowsPrecX _ _ U1 = id
isNullary _ = True
instance (ShowX c) => GShowX (K1 i c) where
gshowsPrecX _ n (K1 a) = showsPrecX n a
isNullary _ = False
instance (GShowX a, Constructor c) => GShowX (M1 C c a) where
gshowsPrecX _ n c@(M1 x) =
case fixity of
Prefix ->
showParen (n > appPrec && not (isNullary x))
( (if conIsTuple c then id else showString (conName c))
. (if isNullary x || conIsTuple c then id else showString " ")
. showBraces t (gshowsPrecX t appPrec x))
Infix _ m -> showParen (n > m) (showBraces t (gshowsPrecX t m x))
where fixity = conFixity c
t = if conIsRecord c then Rec else
case conIsTuple c of
True -> Tup
False -> case fixity of
Prefix -> Pref
Infix _ _ -> Inf (show (conName c))
showBraces :: ShowType -> ShowS -> ShowS
showBraces Rec p = showChar '{' . p . showChar '}'
showBraces Tup p = showChar '(' . p . showChar ')'
showBraces Pref p = p
showBraces (Inf _) p = p
conIsTuple :: C1 c f p -> Bool
conIsTuple y = tupleName (conName y) where
tupleName ('(':',':_) = True
tupleName _ = False
instance (Selector s, GShowX a) => GShowX (M1 S s a) where
gshowsPrecX t n s@(M1 x) | selName s == "" = gshowsPrecX t n x
| otherwise = showString (selName s)
. showString " = "
. gshowsPrecX t 0 x
isNullary (M1 x) = isNullary x
instance (GShowX a) => GShowX (M1 D d a) where
gshowsPrecX t = showsPrecXWith go
where go n (M1 x) = gshowsPrecX t n x
instance (GShowX a, GShowX b) => GShowX (a :+: b) where
gshowsPrecX t n (L1 x) = gshowsPrecX t n x
gshowsPrecX t n (R1 x) = gshowsPrecX t n x
instance (GShowX a, GShowX b) => GShowX (a :*: b) where
gshowsPrecX t@Rec n (a :*: b) =
gshowsPrecX t n a . showString ", " . gshowsPrecX t n b
gshowsPrecX t@(Inf s) n (a :*: b) =
gshowsPrecX t n a . showString s . gshowsPrecX t n b
gshowsPrecX t@Tup n (a :*: b) =
gshowsPrecX t n a . showChar ',' . gshowsPrecX t n b
gshowsPrecX t@Pref n (a :*: b) =
gshowsPrecX t (n+1) a . showChar ' ' . gshowsPrecX t (n+1) b
-- If we have a product then it is not a nullary constructor
isNullary _ = False
types
instance GShowX UChar where
gshowsPrecX _ _ (UChar c) = showsPrec 0 (C# c) . showChar '#'
instance GShowX UDouble where
gshowsPrecX _ _ (UDouble d) = showsPrec 0 (D# d) . showString "##"
instance GShowX UFloat where
gshowsPrecX _ _ (UFloat f) = showsPrec 0 (F# f) . showChar '#'
instance GShowX UInt where
gshowsPrecX _ _ (UInt i) = showsPrec 0 (I# i) . showChar '#'
instance GShowX UWord where
gshowsPrecX _ _ (UWord w) = showsPrec 0 (W# w) . showString "##"
-- | Create a value where all the elements have an 'errorX', but the spine
-- is defined.
class Undefined a where
-- | Create a value where all the elements have an 'errorX', but the spine
-- is defined.
deepErrorX :: HasCallStack => String -> a
deepErrorX = errorX
instance Undefined ()
instance (Undefined a, Undefined b) => Undefined (a,b) where
deepErrorX x = (deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c) => Undefined (a,b,c) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d) =>
Undefined (a,b,c,d) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e) =>
Undefined (a,b,c,d,e) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f)
=> Undefined (a,b,c,d,e,f) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g)
=> Undefined (a,b,c,d,e,f,g) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h)
=> Undefined (a,b,c,d,e,f,g,h) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i)
=> Undefined (a,b,c,d,e,f,g,h,i) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i, Undefined j)
=> Undefined (a,b,c,d,e,f,g,h,i,j) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i, Undefined j
,Undefined k)
=> Undefined (a,b,c,d,e,f,g,h,i,j,k) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i, Undefined j
,Undefined k, Undefined l)
=> Undefined (a,b,c,d,e,f,g,h,i,j,k,l) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i, Undefined j
,Undefined k, Undefined l, Undefined m)
=> Undefined (a,b,c,d,e,f,g,h,i,j,k,l,m) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i, Undefined j
,Undefined k, Undefined l, Undefined m, Undefined n)
=> Undefined (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i, Undefined j
,Undefined k, Undefined l, Undefined m, Undefined n, Undefined o)
=> Undefined (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x)
instance Undefined b => Undefined (a -> b) where
deepErrorX = pure . deepErrorX
instance Undefined a => Undefined (Down a) where
deepErrorX = Down . deepErrorX
instance Undefined [a]
instance Undefined Char
instance Undefined Bool
instance Undefined Double
instance Undefined (Either a b)
instance Undefined Float
instance Undefined Int
instance Undefined Int8
instance Undefined Int16
instance Undefined Int32
instance Undefined Int64
instance Undefined Integer
instance Undefined (Seq a)
instance Undefined Word
instance Undefined Word8
instance Undefined Word16
instance Undefined Word32
instance Undefined Word64
instance Undefined (Maybe a)
instance Undefined (Ratio a)
instance Undefined (Complex a)
| null | https://raw.githubusercontent.com/clash-lang/clash-prelude/5645d8417ab495696cf4e0293796133c7fe2a9a7/src/Clash/XException.hs | haskell | # LANGUAGE DefaultSignatures #
# LANGUAGE FlexibleContexts #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeOperators #
* 'X': An exception for uninitialized values
* Strict evaluation
* Structured undefined
| An exception representing an \"uninitialised\" value.
The 'ShowX' methods print these error-values as \"X\"; instead of error'ing
out with an exception.
| Like 'seq', however, whereas 'seq' will always do:
> seq _|_ b = _|_
| Fully evaluate a value, returning 'Nothing' if is throws 'XException'.
> maybeX _|_ = _|_
| Fully evaluate a value, returning @'Left' msg@ if is throws 'XException'.
> isX _|_ = _|_
| Use when you want to create a 'ShowX' instance where:
implementation details of your data type, and you just want to show the
entire value as \"X\".
Can be used like:
> data T = ...
>
> instance Show T where ...
>
> showsPrecX = showsPrecXWith showsPrec
| Like 'shows', but values that normally throw an 'X' exception are
| Like 'print', but values that normally throw an 'X' exception are
| Like the 'Show' class, but values that normally throw an 'X' exception are
"(*** Exception: X: undefined
...
"(X,4)"
Can be derived using 'GHC.Generics':
> {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
>
>
> data T = MkTA Int | MkTB Bool
| Like 'showsPrec', but values that normally throw an 'X' exception are
| Like 'show', but values that normally throw an 'X' exception are
| Like 'showList', but values that normally throw an 'X' exception are
Record
Tuple
Prefix
Infix
# OVERLAPPABLE #
# OVERLAPPING #
If we have a product then it is not a nullary constructor
| Create a value where all the elements have an 'errorX', but the spine
is defined.
| Create a value where all the elements have an 'errorX', but the spine
is defined. | |
Copyright : ( C ) 2016 , University of Twente ,
2017 , Myrtle Software Ltd , QBayLogic , Google Inc.
License : BSD2 ( see the file LICENSE )
Maintainer : < >
' X ' : An exception for uninitialized values
> > > show ( errorX " undefined " : : Integer , 4 : : Int )
" ( * * * Exception : X : undefined
CallStack ( from HasCallStack ):
...
> > > showX ( errorX " undefined " : : Integer , 4 : : Int )
" ( X,4 ) "
Copyright : (C) 2016, University of Twente,
2017, Myrtle Software Ltd, QBayLogic, Google Inc.
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <>
'X': An exception for uninitialized values
>>> show (errorX "undefined" :: Integer, 4 :: Int)
"(*** Exception: X: undefined
CallStack (from HasCallStack):
...
>>> showX (errorX "undefined" :: Integer, 4 :: Int)
"(X,4)"
-}
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
# LANGUAGE MagicHash #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE Trustworthy #
# OPTIONS_GHC -Wno - orphans #
module Clash.XException
XException, errorX, isX, maybeX
* Printing ' X ' exceptions as \"X\ "
, ShowX (..), showsX, printX, showsPrecXWith
, seqX
, Undefined (..)
)
where
import Control.Exception (Exception, catch, evaluate, throw)
import Control.DeepSeq (NFData, rnf)
import Data.Complex (Complex)
import Data.Foldable (toList)
import Data.Int (Int8,Int16,Int32,Int64)
import Data.Ord (Down (Down))
import Data.Ratio (Ratio)
import Data.Sequence (Seq)
import Data.Word (Word8,Word16,Word32,Word64)
import GHC.Exts (Char (C#), Double (D#), Float (F#), Int (I#), Word (W#))
import GHC.Generics
import GHC.Show (appPrec)
import GHC.Stack (HasCallStack, callStack, prettyCallStack)
import System.IO.Unsafe (unsafeDupablePerformIO)
newtype XException = XException String
instance Show XException where
show (XException s) = s
instance Exception XException
| Like ' error ' , but throwing an ' XException ' instead of an ' ErrorCall '
errorX :: HasCallStack => String -> a
errorX msg = throw (XException ("X: " ++ msg ++ "\n" ++ prettyCallStack callStack))
' ' will do :
> ( XException msg ) b = b
> _ | _ b = _ | _
seqX :: a -> b -> b
seqX a b = unsafeDupablePerformIO
(catch (evaluate a >> return b) (\(XException _) -> return b))
# NOINLINE seqX #
infixr 0 `seqX`
> maybeX 42 = Just 42
> maybeX ( msg ) = Nothing
maybeX :: NFData a => a -> Maybe a
maybeX = either (const Nothing) Just . isX
> isX 42 = Right 42
> isX ( XException msg ) = Left msg
isX :: NFData a => a -> Either String a
isX a = unsafeDupablePerformIO
(catch (evaluate (rnf a) >> return (Right a)) (\(XException msg) -> return (Left msg)))
# NOINLINE isX #
showXWith :: (a -> ShowS) -> a -> ShowS
showXWith f x =
\s -> unsafeDupablePerformIO (catch (f <$> evaluate x <*> pure s)
(\(XException _) -> return ('X': s)))
- There is no ' Generic ' instance for your data type
- The ' Generic ' derived ShowX method would traverse into the ( hidden )
> instance T where
showsPrecXWith :: (Int -> a -> ShowS) -> Int -> a -> ShowS
showsPrecXWith f n = showXWith (f n)
converted to \"X\ " , instead of error'ing out with an exception .
showsX :: ShowX a => a -> ShowS
showsX = showsPrecX 0
converted to \"X\ " , instead of error'ing out with an exception
printX :: ShowX a => a -> IO ()
printX x = putStrLn $ showX x
converted to \"X\ " , instead of error'ing out with an exception .
> > > show ( errorX " undefined " : : Integer , 4 : : Int )
CallStack ( from HasCallStack ):
> > > showX ( errorX " undefined " : : Integer , 4 : : Int )
> import Clash . Prelude
> import
> deriving ( Show , Generic , )
class ShowX a where
converted to \"X\ " , instead of error'ing out with an exception .
showsPrecX :: Int -> a -> ShowS
converted to \"X\ " , instead of error'ing out with an exception .
showX :: a -> String
showX x = showsX x ""
converted to \"X\ " , instead of error'ing out with an exception .
showListX :: [a] -> ShowS
showListX ls s = showListX__ showsX ls s
default showsPrecX :: (Generic a, GShowX (Rep a)) => Int -> a -> ShowS
showsPrecX = genericShowsPrecX
showListX__ :: (a -> ShowS) -> [a] -> ShowS
showListX__ showx = showXWith go
where
go [] s = "[]" ++ s
go (x:xs) s = '[' : showx x (showl xs)
where
showl [] = ']':s
showl (y:ys) = ',' : showx y (showl ys)
genericShowsPrecX :: (Generic a, GShowX (Rep a)) => Int -> a -> ShowS
genericShowsPrecX n = gshowsPrecX Pref n . from
instance ShowX ()
instance (ShowX a, ShowX b) => ShowX (a,b)
instance (ShowX a, ShowX b, ShowX c) => ShowX (a,b,c)
instance (ShowX a, ShowX b, ShowX c, ShowX d) => ShowX (a,b,c,d)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e) => ShowX (a,b,c,d,e)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f) => ShowX (a,b,c,d,e,f)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g) => ShowX (a,b,c,d,e,f,g)
Show is defined up to 15 - tuples , but only has Generic instances
up to 7 - tuples , hence we need these orphan instances .
deriving instance Generic ((,,,,,,,) a b c d e f g h)
deriving instance Generic ((,,,,,,,,) a b c d e f g h i)
deriving instance Generic ((,,,,,,,,,) a b c d e f g h i j)
deriving instance Generic ((,,,,,,,,,,) a b c d e f g h i j k)
deriving instance Generic ((,,,,,,,,,,,) a b c d e f g h i j k l)
deriving instance Generic ((,,,,,,,,,,,,) a b c d e f g h i j k l m)
deriving instance Generic ((,,,,,,,,,,,,,) a b c d e f g h i j k l m n)
deriving instance Generic ((,,,,,,,,,,,,,,) a b c d e f g h i j k l m n o)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h) => ShowX (a,b,c,d,e,f,g,h)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i) => ShowX (a,b,c,d,e,f,g,h,i)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i, ShowX j)
=> ShowX (a,b,c,d,e,f,g,h,i,j)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i, ShowX j, ShowX k)
=> ShowX (a,b,c,d,e,f,g,h,i,j,k)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i, ShowX j, ShowX k, ShowX l)
=> ShowX (a,b,c,d,e,f,g,h,i,j,k,l)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i, ShowX j, ShowX k, ShowX l
,ShowX m)
=> ShowX (a,b,c,d,e,f,g,h,i,j,k,l,m)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i, ShowX j, ShowX k, ShowX l
,ShowX m, ShowX n)
=> ShowX (a,b,c,d,e,f,g,h,i,j,k,l,m,n)
instance (ShowX a, ShowX b, ShowX c, ShowX d, ShowX e, ShowX f, ShowX g, ShowX h, ShowX i, ShowX j, ShowX k, ShowX l
,ShowX m, ShowX n, ShowX o)
=> ShowX (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o)
showsPrecX _ = showListX
instance ShowX Char where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Bool
instance ShowX Double where
showsPrecX = showsPrecXWith showsPrec
instance ShowX a => ShowX (Down a) where
showsPrecX = showsPrecXWith showsPrecX
instance (ShowX a, ShowX b) => ShowX (Either a b)
instance ShowX Float where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Int where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Int8 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Int16 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Int32 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Int64 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Integer where
showsPrecX = showsPrecXWith showsPrec
instance ShowX a => ShowX (Seq a) where
showsPrecX _ = showListX . toList
instance ShowX Word where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Word8 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Word16 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Word32 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX Word64 where
showsPrecX = showsPrecXWith showsPrec
instance ShowX a => ShowX (Maybe a)
instance ShowX a => ShowX (Ratio a) where
showsPrecX = showsPrecXWith showsPrecX
instance ShowX a => ShowX (Complex a)
showsPrecX = showsPrecXWith showsPrec
class GShowX f where
gshowsPrecX :: ShowType -> Int -> f a -> ShowS
isNullary :: f a -> Bool
isNullary = error "generic showX (isNullary): unnecessary case"
instance GShowX U1 where
gshowsPrecX _ _ U1 = id
isNullary _ = True
instance (ShowX c) => GShowX (K1 i c) where
gshowsPrecX _ n (K1 a) = showsPrecX n a
isNullary _ = False
instance (GShowX a, Constructor c) => GShowX (M1 C c a) where
gshowsPrecX _ n c@(M1 x) =
case fixity of
Prefix ->
showParen (n > appPrec && not (isNullary x))
( (if conIsTuple c then id else showString (conName c))
. (if isNullary x || conIsTuple c then id else showString " ")
. showBraces t (gshowsPrecX t appPrec x))
Infix _ m -> showParen (n > m) (showBraces t (gshowsPrecX t m x))
where fixity = conFixity c
t = if conIsRecord c then Rec else
case conIsTuple c of
True -> Tup
False -> case fixity of
Prefix -> Pref
Infix _ _ -> Inf (show (conName c))
showBraces :: ShowType -> ShowS -> ShowS
showBraces Rec p = showChar '{' . p . showChar '}'
showBraces Tup p = showChar '(' . p . showChar ')'
showBraces Pref p = p
showBraces (Inf _) p = p
conIsTuple :: C1 c f p -> Bool
conIsTuple y = tupleName (conName y) where
tupleName ('(':',':_) = True
tupleName _ = False
instance (Selector s, GShowX a) => GShowX (M1 S s a) where
gshowsPrecX t n s@(M1 x) | selName s == "" = gshowsPrecX t n x
| otherwise = showString (selName s)
. showString " = "
. gshowsPrecX t 0 x
isNullary (M1 x) = isNullary x
instance (GShowX a) => GShowX (M1 D d a) where
gshowsPrecX t = showsPrecXWith go
where go n (M1 x) = gshowsPrecX t n x
instance (GShowX a, GShowX b) => GShowX (a :+: b) where
gshowsPrecX t n (L1 x) = gshowsPrecX t n x
gshowsPrecX t n (R1 x) = gshowsPrecX t n x
instance (GShowX a, GShowX b) => GShowX (a :*: b) where
gshowsPrecX t@Rec n (a :*: b) =
gshowsPrecX t n a . showString ", " . gshowsPrecX t n b
gshowsPrecX t@(Inf s) n (a :*: b) =
gshowsPrecX t n a . showString s . gshowsPrecX t n b
gshowsPrecX t@Tup n (a :*: b) =
gshowsPrecX t n a . showChar ',' . gshowsPrecX t n b
gshowsPrecX t@Pref n (a :*: b) =
gshowsPrecX t (n+1) a . showChar ' ' . gshowsPrecX t (n+1) b
isNullary _ = False
types
instance GShowX UChar where
gshowsPrecX _ _ (UChar c) = showsPrec 0 (C# c) . showChar '#'
instance GShowX UDouble where
gshowsPrecX _ _ (UDouble d) = showsPrec 0 (D# d) . showString "##"
instance GShowX UFloat where
gshowsPrecX _ _ (UFloat f) = showsPrec 0 (F# f) . showChar '#'
instance GShowX UInt where
gshowsPrecX _ _ (UInt i) = showsPrec 0 (I# i) . showChar '#'
instance GShowX UWord where
gshowsPrecX _ _ (UWord w) = showsPrec 0 (W# w) . showString "##"
class Undefined a where
deepErrorX :: HasCallStack => String -> a
deepErrorX = errorX
instance Undefined ()
instance (Undefined a, Undefined b) => Undefined (a,b) where
deepErrorX x = (deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c) => Undefined (a,b,c) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d) =>
Undefined (a,b,c,d) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e) =>
Undefined (a,b,c,d,e) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f)
=> Undefined (a,b,c,d,e,f) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g)
=> Undefined (a,b,c,d,e,f,g) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h)
=> Undefined (a,b,c,d,e,f,g,h) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i)
=> Undefined (a,b,c,d,e,f,g,h,i) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i, Undefined j)
=> Undefined (a,b,c,d,e,f,g,h,i,j) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i, Undefined j
,Undefined k)
=> Undefined (a,b,c,d,e,f,g,h,i,j,k) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i, Undefined j
,Undefined k, Undefined l)
=> Undefined (a,b,c,d,e,f,g,h,i,j,k,l) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i, Undefined j
,Undefined k, Undefined l, Undefined m)
=> Undefined (a,b,c,d,e,f,g,h,i,j,k,l,m) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i, Undefined j
,Undefined k, Undefined l, Undefined m, Undefined n)
=> Undefined (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x)
instance (Undefined a, Undefined b, Undefined c, Undefined d, Undefined e
,Undefined f, Undefined g, Undefined h, Undefined i, Undefined j
,Undefined k, Undefined l, Undefined m, Undefined n, Undefined o)
=> Undefined (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where
deepErrorX x = (deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x,deepErrorX x
,deepErrorX x,deepErrorX x,deepErrorX x)
instance Undefined b => Undefined (a -> b) where
deepErrorX = pure . deepErrorX
instance Undefined a => Undefined (Down a) where
deepErrorX = Down . deepErrorX
instance Undefined [a]
instance Undefined Char
instance Undefined Bool
instance Undefined Double
instance Undefined (Either a b)
instance Undefined Float
instance Undefined Int
instance Undefined Int8
instance Undefined Int16
instance Undefined Int32
instance Undefined Int64
instance Undefined Integer
instance Undefined (Seq a)
instance Undefined Word
instance Undefined Word8
instance Undefined Word16
instance Undefined Word32
instance Undefined Word64
instance Undefined (Maybe a)
instance Undefined (Ratio a)
instance Undefined (Complex a)
|
9c3d97488bfdcb15e34b0ef02c8413aa60718fb0564f2ece57ddf970e9e6e1ae | Liqwid-Labs/liqwid-plutarch-extra | Orphans.hs | # LANGUAGE PolyKinds #
# LANGUAGE QuantifiedConstraints #
-- The whole point of this module
# OPTIONS_GHC -Wno - orphans #
| Module : . Orphans
Description : Orphan instances for Plutarch and types , including
JSON serialization .
Description: Orphan instances for Plutarch and Plutus types, including
JSON serialization.
-}
module Plutarch.Orphans () where
import Codec.Serialise (Serialise, deserialiseOrFail, serialise)
import Data.Aeson ((.:), (.=))
import Data.Aeson qualified as Aeson
import Data.Aeson.Types (Parser, parserThrowError)
import Data.ByteString qualified as ByteStringStrict
import Data.ByteString.Base16 qualified as Base16
import Data.ByteString.Lazy (fromStrict, toStrict)
import Data.ByteString.Short (fromShort, toShort)
import Data.Coerce (Coercible, coerce)
import Data.Functor ((<&>))
import Data.Ratio (Ratio, denominator, numerator, (%))
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Text.Encoding (encodeUtf8)
import Data.Text.Encoding qualified as Text.Encoding
import Data.Vector qualified as Vector
import Plutarch.Api.V2 (PDatumHash (PDatumHash))
import Plutarch.Builtin (PIsData (pdataImpl, pfromDataImpl))
import Plutarch.Extra.TermCont (ptryFromC)
import Plutarch.TryFrom (PTryFrom (ptryFrom'), PTryFromExcess)
import Plutarch.Unsafe (punsafeCoerce)
--------------------------------------------------------------------------------
import Plutarch.Script (Script, deserialiseScript, serialiseScript)
import PlutusLedgerApi.V1.Bytes (bytes, encodeByteString, fromHex)
import PlutusLedgerApi.V1.Value (tokenName)
import PlutusLedgerApi.V2 (
BuiltinByteString,
BuiltinData (BuiltinData),
Credential (PubKeyCredential, ScriptCredential),
CurrencySymbol (CurrencySymbol, unCurrencySymbol),
Data (I, List),
Datum,
LedgerBytes (LedgerBytes),
POSIXTime (POSIXTime),
PubKeyHash (PubKeyHash),
ScriptHash (ScriptHash),
StakingCredential (StakingHash, StakingPtr),
TokenName (TokenName),
TxId (TxId),
TxOutRef,
fromBuiltin,
toBuiltin,
)
import PlutusTx (FromData (fromBuiltinData), ToData (toBuiltinData))
--------------------------------------------------------------------------------
tryDecode :: Text -> Either String ByteStringStrict.ByteString
tryDecode = Base16.decode . encodeUtf8
decodeByteString :: Aeson.Value -> Parser ByteStringStrict.ByteString
decodeByteString = Aeson.withText "ByteString" (either fail pure . tryDecode)
--------------------------------------------------------------------------------
newtype Flip f a b = Flip (f b a) deriving stock (Generic)
-- | @since 3.0.3
instance (PIsData a) => PIsData (PAsData a) where
pfromDataImpl = punsafeCoerce
pdataImpl = pdataImpl . pfromData
-- | @since 3.0.3
instance PTryFrom PData (PAsData PDatumHash) where
type PTryFromExcess PData (PAsData PDatumHash) = Flip Term PDatumHash
ptryFrom' opq = runTermCont $ do
unwrapped <- pfromData . fst <$> ptryFromC @(PAsData PByteString) opq
tcont $ \f ->
pif
Blake2b_256 hash : 256 bits/32 bytes .
(plengthBS # unwrapped #== 32)
(f ())
(ptraceError "ptryFrom(PDatumHash): must be 32 bytes long")
pure (punsafeCoerce opq, pcon $ PDatumHash unwrapped)
-- | @since 3.0.3
instance PTryFrom PData (PAsData PUnit)
----------------------------------------
-- Instances for Ratios
instance ToData (Ratio Integer) where
toBuiltinData rat =
BuiltinData $
List
[ I $ numerator rat
, I $ denominator rat
]
instance FromData (Ratio Integer) where
fromBuiltinData (BuiltinData (List [I num, I denom])) =
pure $ num % if num == 0 then 1 else denom
fromBuiltinData _ = Nothing
----------------------------------------
-- Aeson (JSON) instances
| Represent a ByteString as a hex - encoded JSON String
newtype AsBase16Bytes (a :: Type) = AsBase16Bytes a
{- | Represent any serializable value as a hex-encoded JSON String of its
serialization
-}
newtype AsBase16Codec (a :: Type) = AsBase16Codec a
--------------------
-- Instances for `deriving via`
@ since 3.6.1
instance
(Coercible a LedgerBytes) =>
Aeson.ToJSON (AsBase16Bytes a)
where
toJSON =
Aeson.String
. encodeByteString
. bytes
. coerce @(AsBase16Bytes a) @LedgerBytes
toEncoding =
Aeson.toEncoding @Text
. encodeByteString
. bytes
. coerce @(AsBase16Bytes a) @LedgerBytes
@ since 3.6.1
instance
(Coercible LedgerBytes a) =>
Aeson.FromJSON (AsBase16Bytes a)
where
parseJSON v =
Aeson.parseJSON @Text v
>>= either
(parserThrowError [] . show)
( pure
. coerce @_
@(AsBase16Bytes a)
)
. fromHex
. encodeUtf8
@ since 3.6.1
instance (Serialise a) => Aeson.ToJSON (AsBase16Codec a) where
toJSON (AsBase16Codec x) =
Aeson.String
. encodeByteString
. toStrict
. serialise @a
$ x
toEncoding (AsBase16Codec x) =
Aeson.toEncoding @Text
. encodeByteString
. toStrict
. serialise @a
$ x
@ since 3.6.1
instance (Serialise a) => Aeson.FromJSON (AsBase16Codec a) where
parseJSON v = do
eitherLedgerBytes <-
fromHex . encodeUtf8
<$> Aeson.parseJSON @Text v
b <- case eitherLedgerBytes of
(Left err) -> parserThrowError [] $ show err
(Right lb) -> pure $ bytes lb
case deserialiseOrFail (fromStrict b) of
(Left err) -> parserThrowError [] $ show err
(Right r) -> pure $ AsBase16Codec r
-- @since X.Y.Z
deriving via (AsBase16Codec Datum) instance Aeson.ToJSON Datum
-- @since X.Y.Z
deriving via (AsBase16Codec Datum) instance Aeson.FromJSON Datum
@ since 3.6.1
deriving via (AsBase16Bytes TxId) instance Aeson.ToJSON TxId
@ since 3.6.1
deriving via (AsBase16Bytes TxId) instance Aeson.FromJSON TxId
@ since 3.6.1
deriving anyclass instance Aeson.ToJSON TxOutRef
@ since 3.6.1
deriving anyclass instance Aeson.FromJSON TxOutRef
@ since 3.20.2
instance Aeson.ToJSON CurrencySymbol where
toJSON c =
Aeson.object
[
( "unCurrencySymbol"
, Aeson.String
. encodeByteString
. fromBuiltin
. unCurrencySymbol
$ c
)
]
@ since 3.20.2
instance Aeson.FromJSON CurrencySymbol where
parseJSON =
Aeson.withObject "CurrencySymbol" $ \object -> do
raw <- object .: "unCurrencySymbol"
bytes' <- decodeByteString raw
pure $ CurrencySymbol $ toBuiltin bytes'
Copied from an old version of Plutarch :
-output-hk/plutus/blob/4fd86930f1dc628a816adf5f5d854b3fec578312/plutus-ledger-api/src/Plutus/V1/Ledger/Value.hs#L155
note [ token names ]
How to properly roundtrip a token name that is not valid UTF-8 through PureScript
without a big rewrite of the API ?
We prefix it with a zero byte so we can recognize it when we get a bytestring value back ,
and we serialize it base16 encoded , with 0x in front so it will look as a hex string .
( Browsers do n't render the zero byte . )
-output-hk/plutus/blob/4fd86930f1dc628a816adf5f5d854b3fec578312/plutus-ledger-api/src/Plutus/V1/Ledger/Value.hs#L155
note [Roundtripping token names]
How to properly roundtrip a token name that is not valid UTF-8 through PureScript
without a big rewrite of the API?
We prefix it with a zero byte so we can recognize it when we get a bytestring value back,
and we serialize it base16 encoded, with 0x in front so it will look as a hex string.
(Browsers don't render the zero byte.)
-}
@ since 3.20.2
instance Aeson.ToJSON TokenName where
toJSON =
Aeson.object
. pure
. (,) "unTokenName"
. Aeson.toJSON
. fromTokenName
(Text.cons '\NUL' . asBase16)
( \t -> case Text.take 1 t of
"\NUL" -> Text.concat ["\NUL\NUL", t]
_ -> t
)
where
fromTokenName ::
(ByteStringStrict.ByteString -> r) ->
(Text -> r) ->
TokenName ->
r
fromTokenName handleBytestring handleText (TokenName bs) =
either (\_ -> handleBytestring $ fromBuiltin bs) handleText $
Text.Encoding.decodeUtf8' (fromBuiltin bs)
asBase16 :: ByteStringStrict.ByteString -> Text
asBase16 bs = Text.concat ["0x", encodeByteString bs]
@ since 3.20.2
instance Aeson.FromJSON TokenName where
parseJSON =
Aeson.withObject "TokenName" $ \object -> do
raw <- object .: "unTokenName"
fromJSONText raw
where
fromJSONText t = case Text.take 3 t of
"\NUL0x" -> either fail (pure . tokenName) . tryDecode . Text.drop 3 $ t
"\NUL\NUL\NUL" ->
pure . tokenName . Text.Encoding.encodeUtf8 . Text.drop 2 $ t
_ -> pure . tokenName . Text.Encoding.encodeUtf8 $ t
@ since 3.6.1
deriving via
(AsBase16Bytes ScriptHash)
instance
(Aeson.ToJSON ScriptHash)
@ since 3.6.1
deriving via
(AsBase16Bytes ScriptHash)
instance
(Aeson.FromJSON ScriptHash)
@ since 3.6.1
deriving via
Integer
instance
(Aeson.ToJSON POSIXTime)
@ since 3.6.1
deriving via
Integer
instance
(Aeson.FromJSON POSIXTime)
@ since 3.6.1
deriving via
(AsBase16Bytes BuiltinByteString)
instance
(Aeson.ToJSON BuiltinByteString)
@ since 3.6.1
deriving via
(AsBase16Bytes BuiltinByteString)
instance
(Aeson.FromJSON BuiltinByteString)
@ since 3.6.1
instance Aeson.ToJSON Script where
toJSON =
Aeson.String
. encodeByteString
. fromShort
. serialiseScript
@ since 3.6.1
instance Aeson.FromJSON Script where
parseJSON v =
Aeson.parseJSON @Text v
<&> deserialiseScript
. toShort
. encodeUtf8
@ since 3.16.0
deriving via
BuiltinByteString
instance
(Aeson.ToJSON PubKeyHash)
@ since 3.16.0
deriving via
BuiltinByteString
instance
(Aeson.FromJSON PubKeyHash)
--------------------------------------------------------------------------------
-- manual instances
@ since 3.16.0
instance Aeson.ToJSON StakingCredential where
toJSON (StakingHash cred) =
Aeson.object
[ "contents" .= Aeson.toJSON cred
, "tag" .= Aeson.String "StakingHash"
]
toJSON (StakingPtr x y z) =
Aeson.object
[ "contents"
.= Aeson.Array
( Vector.fromList
(Aeson.toJSON <$> [x, y, z])
)
, "tag" .= Aeson.String "StakingPtr"
]
toEncoding (StakingHash cred) =
Aeson.pairs
( "contents"
.= cred
<> "tag"
.= Aeson.String "StakingHash"
)
toEncoding (StakingPtr x y z) =
Aeson.pairs
( "contents"
.= [x, y, z]
<> "tag"
.= Aeson.String "StakingPtr"
)
@since 3.16.0
instance Aeson.FromJSON StakingCredential where
parseJSON = Aeson.withObject "StakingCredential" $ \v -> do
contents <- v .: "contents"
tag <- v .: "tag"
case tag of
"StakingHash" -> StakingHash <$> Aeson.parseJSON contents
"StakingPtr" -> parseStakingPtr contents
_ -> fail $ "Expected StakingHash or StakingPtr, got " <> tag
where
parseStakingPtr :: Aeson.Value -> Parser StakingCredential
parseStakingPtr v =
Aeson.parseJSONList v >>= \case
[x, y, z] -> pure $ StakingPtr x y z
xs ->
fail $
"expected an array of length 3, but got length "
<> show (length xs)
@since 3.16.0
instance Aeson.ToJSON Credential where
toJSON (PubKeyCredential cred) =
Aeson.object
[ "contents" .= Aeson.toJSON cred
, "tag" .= Aeson.String "PubKeyCredential"
]
toJSON (ScriptCredential cred) =
Aeson.object
[ "contents" .= Aeson.toJSON cred
, "tag" .= Aeson.String "ScriptCredential"
]
toEncoding (PubKeyCredential cred) =
Aeson.pairs
( "contents"
.= cred
<> "tag"
.= Aeson.String "PubKeyCredential"
)
toEncoding (ScriptCredential cred) =
Aeson.pairs
( "contents"
.= cred
<> "tag"
.= Aeson.String "ScriptCredential"
)
@since 3.16.0
instance Aeson.FromJSON Credential where
parseJSON = Aeson.withObject "Credential" $ \v -> do
contents <- v .: "contents"
tag <- v .: "tag"
case tag of
"PubKeyCredential" -> PubKeyCredential <$> Aeson.parseJSON contents
"ScriptCredential" -> ScriptCredential <$> Aeson.parseJSON contents
_ -> fail $ "Expected PubKeyCredential or ScriptCredential, got " <> tag
| null | https://raw.githubusercontent.com/Liqwid-Labs/liqwid-plutarch-extra/f9fa149db0b640c87268ee8865d4dd4175470937/src/Plutarch/Orphans.hs | haskell | The whole point of this module
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| @since 3.0.3
| @since 3.0.3
| @since 3.0.3
--------------------------------------
Instances for Ratios
--------------------------------------
Aeson (JSON) instances
| Represent any serializable value as a hex-encoded JSON String of its
serialization
------------------
Instances for `deriving via`
@since X.Y.Z
@since X.Y.Z
------------------------------------------------------------------------------
manual instances | # LANGUAGE PolyKinds #
# LANGUAGE QuantifiedConstraints #
# OPTIONS_GHC -Wno - orphans #
| Module : . Orphans
Description : Orphan instances for Plutarch and types , including
JSON serialization .
Description: Orphan instances for Plutarch and Plutus types, including
JSON serialization.
-}
module Plutarch.Orphans () where
import Codec.Serialise (Serialise, deserialiseOrFail, serialise)
import Data.Aeson ((.:), (.=))
import Data.Aeson qualified as Aeson
import Data.Aeson.Types (Parser, parserThrowError)
import Data.ByteString qualified as ByteStringStrict
import Data.ByteString.Base16 qualified as Base16
import Data.ByteString.Lazy (fromStrict, toStrict)
import Data.ByteString.Short (fromShort, toShort)
import Data.Coerce (Coercible, coerce)
import Data.Functor ((<&>))
import Data.Ratio (Ratio, denominator, numerator, (%))
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Text.Encoding (encodeUtf8)
import Data.Text.Encoding qualified as Text.Encoding
import Data.Vector qualified as Vector
import Plutarch.Api.V2 (PDatumHash (PDatumHash))
import Plutarch.Builtin (PIsData (pdataImpl, pfromDataImpl))
import Plutarch.Extra.TermCont (ptryFromC)
import Plutarch.TryFrom (PTryFrom (ptryFrom'), PTryFromExcess)
import Plutarch.Unsafe (punsafeCoerce)
import Plutarch.Script (Script, deserialiseScript, serialiseScript)
import PlutusLedgerApi.V1.Bytes (bytes, encodeByteString, fromHex)
import PlutusLedgerApi.V1.Value (tokenName)
import PlutusLedgerApi.V2 (
BuiltinByteString,
BuiltinData (BuiltinData),
Credential (PubKeyCredential, ScriptCredential),
CurrencySymbol (CurrencySymbol, unCurrencySymbol),
Data (I, List),
Datum,
LedgerBytes (LedgerBytes),
POSIXTime (POSIXTime),
PubKeyHash (PubKeyHash),
ScriptHash (ScriptHash),
StakingCredential (StakingHash, StakingPtr),
TokenName (TokenName),
TxId (TxId),
TxOutRef,
fromBuiltin,
toBuiltin,
)
import PlutusTx (FromData (fromBuiltinData), ToData (toBuiltinData))
tryDecode :: Text -> Either String ByteStringStrict.ByteString
tryDecode = Base16.decode . encodeUtf8
decodeByteString :: Aeson.Value -> Parser ByteStringStrict.ByteString
decodeByteString = Aeson.withText "ByteString" (either fail pure . tryDecode)
newtype Flip f a b = Flip (f b a) deriving stock (Generic)
instance (PIsData a) => PIsData (PAsData a) where
pfromDataImpl = punsafeCoerce
pdataImpl = pdataImpl . pfromData
instance PTryFrom PData (PAsData PDatumHash) where
type PTryFromExcess PData (PAsData PDatumHash) = Flip Term PDatumHash
ptryFrom' opq = runTermCont $ do
unwrapped <- pfromData . fst <$> ptryFromC @(PAsData PByteString) opq
tcont $ \f ->
pif
Blake2b_256 hash : 256 bits/32 bytes .
(plengthBS # unwrapped #== 32)
(f ())
(ptraceError "ptryFrom(PDatumHash): must be 32 bytes long")
pure (punsafeCoerce opq, pcon $ PDatumHash unwrapped)
instance PTryFrom PData (PAsData PUnit)
instance ToData (Ratio Integer) where
toBuiltinData rat =
BuiltinData $
List
[ I $ numerator rat
, I $ denominator rat
]
instance FromData (Ratio Integer) where
fromBuiltinData (BuiltinData (List [I num, I denom])) =
pure $ num % if num == 0 then 1 else denom
fromBuiltinData _ = Nothing
| Represent a ByteString as a hex - encoded JSON String
newtype AsBase16Bytes (a :: Type) = AsBase16Bytes a
newtype AsBase16Codec (a :: Type) = AsBase16Codec a
@ since 3.6.1
instance
(Coercible a LedgerBytes) =>
Aeson.ToJSON (AsBase16Bytes a)
where
toJSON =
Aeson.String
. encodeByteString
. bytes
. coerce @(AsBase16Bytes a) @LedgerBytes
toEncoding =
Aeson.toEncoding @Text
. encodeByteString
. bytes
. coerce @(AsBase16Bytes a) @LedgerBytes
@ since 3.6.1
instance
(Coercible LedgerBytes a) =>
Aeson.FromJSON (AsBase16Bytes a)
where
parseJSON v =
Aeson.parseJSON @Text v
>>= either
(parserThrowError [] . show)
( pure
. coerce @_
@(AsBase16Bytes a)
)
. fromHex
. encodeUtf8
@ since 3.6.1
instance (Serialise a) => Aeson.ToJSON (AsBase16Codec a) where
toJSON (AsBase16Codec x) =
Aeson.String
. encodeByteString
. toStrict
. serialise @a
$ x
toEncoding (AsBase16Codec x) =
Aeson.toEncoding @Text
. encodeByteString
. toStrict
. serialise @a
$ x
@ since 3.6.1
instance (Serialise a) => Aeson.FromJSON (AsBase16Codec a) where
parseJSON v = do
eitherLedgerBytes <-
fromHex . encodeUtf8
<$> Aeson.parseJSON @Text v
b <- case eitherLedgerBytes of
(Left err) -> parserThrowError [] $ show err
(Right lb) -> pure $ bytes lb
case deserialiseOrFail (fromStrict b) of
(Left err) -> parserThrowError [] $ show err
(Right r) -> pure $ AsBase16Codec r
deriving via (AsBase16Codec Datum) instance Aeson.ToJSON Datum
deriving via (AsBase16Codec Datum) instance Aeson.FromJSON Datum
@ since 3.6.1
deriving via (AsBase16Bytes TxId) instance Aeson.ToJSON TxId
@ since 3.6.1
deriving via (AsBase16Bytes TxId) instance Aeson.FromJSON TxId
@ since 3.6.1
deriving anyclass instance Aeson.ToJSON TxOutRef
@ since 3.6.1
deriving anyclass instance Aeson.FromJSON TxOutRef
@ since 3.20.2
instance Aeson.ToJSON CurrencySymbol where
toJSON c =
Aeson.object
[
( "unCurrencySymbol"
, Aeson.String
. encodeByteString
. fromBuiltin
. unCurrencySymbol
$ c
)
]
@ since 3.20.2
instance Aeson.FromJSON CurrencySymbol where
parseJSON =
Aeson.withObject "CurrencySymbol" $ \object -> do
raw <- object .: "unCurrencySymbol"
bytes' <- decodeByteString raw
pure $ CurrencySymbol $ toBuiltin bytes'
Copied from an old version of Plutarch :
-output-hk/plutus/blob/4fd86930f1dc628a816adf5f5d854b3fec578312/plutus-ledger-api/src/Plutus/V1/Ledger/Value.hs#L155
note [ token names ]
How to properly roundtrip a token name that is not valid UTF-8 through PureScript
without a big rewrite of the API ?
We prefix it with a zero byte so we can recognize it when we get a bytestring value back ,
and we serialize it base16 encoded , with 0x in front so it will look as a hex string .
( Browsers do n't render the zero byte . )
-output-hk/plutus/blob/4fd86930f1dc628a816adf5f5d854b3fec578312/plutus-ledger-api/src/Plutus/V1/Ledger/Value.hs#L155
note [Roundtripping token names]
How to properly roundtrip a token name that is not valid UTF-8 through PureScript
without a big rewrite of the API?
We prefix it with a zero byte so we can recognize it when we get a bytestring value back,
and we serialize it base16 encoded, with 0x in front so it will look as a hex string.
(Browsers don't render the zero byte.)
-}
@ since 3.20.2
instance Aeson.ToJSON TokenName where
toJSON =
Aeson.object
. pure
. (,) "unTokenName"
. Aeson.toJSON
. fromTokenName
(Text.cons '\NUL' . asBase16)
( \t -> case Text.take 1 t of
"\NUL" -> Text.concat ["\NUL\NUL", t]
_ -> t
)
where
fromTokenName ::
(ByteStringStrict.ByteString -> r) ->
(Text -> r) ->
TokenName ->
r
fromTokenName handleBytestring handleText (TokenName bs) =
either (\_ -> handleBytestring $ fromBuiltin bs) handleText $
Text.Encoding.decodeUtf8' (fromBuiltin bs)
asBase16 :: ByteStringStrict.ByteString -> Text
asBase16 bs = Text.concat ["0x", encodeByteString bs]
@ since 3.20.2
instance Aeson.FromJSON TokenName where
parseJSON =
Aeson.withObject "TokenName" $ \object -> do
raw <- object .: "unTokenName"
fromJSONText raw
where
fromJSONText t = case Text.take 3 t of
"\NUL0x" -> either fail (pure . tokenName) . tryDecode . Text.drop 3 $ t
"\NUL\NUL\NUL" ->
pure . tokenName . Text.Encoding.encodeUtf8 . Text.drop 2 $ t
_ -> pure . tokenName . Text.Encoding.encodeUtf8 $ t
@ since 3.6.1
deriving via
(AsBase16Bytes ScriptHash)
instance
(Aeson.ToJSON ScriptHash)
@ since 3.6.1
deriving via
(AsBase16Bytes ScriptHash)
instance
(Aeson.FromJSON ScriptHash)
@ since 3.6.1
deriving via
Integer
instance
(Aeson.ToJSON POSIXTime)
@ since 3.6.1
deriving via
Integer
instance
(Aeson.FromJSON POSIXTime)
@ since 3.6.1
deriving via
(AsBase16Bytes BuiltinByteString)
instance
(Aeson.ToJSON BuiltinByteString)
@ since 3.6.1
deriving via
(AsBase16Bytes BuiltinByteString)
instance
(Aeson.FromJSON BuiltinByteString)
@ since 3.6.1
instance Aeson.ToJSON Script where
toJSON =
Aeson.String
. encodeByteString
. fromShort
. serialiseScript
@ since 3.6.1
instance Aeson.FromJSON Script where
parseJSON v =
Aeson.parseJSON @Text v
<&> deserialiseScript
. toShort
. encodeUtf8
@ since 3.16.0
deriving via
BuiltinByteString
instance
(Aeson.ToJSON PubKeyHash)
@ since 3.16.0
deriving via
BuiltinByteString
instance
(Aeson.FromJSON PubKeyHash)
@ since 3.16.0
instance Aeson.ToJSON StakingCredential where
toJSON (StakingHash cred) =
Aeson.object
[ "contents" .= Aeson.toJSON cred
, "tag" .= Aeson.String "StakingHash"
]
toJSON (StakingPtr x y z) =
Aeson.object
[ "contents"
.= Aeson.Array
( Vector.fromList
(Aeson.toJSON <$> [x, y, z])
)
, "tag" .= Aeson.String "StakingPtr"
]
toEncoding (StakingHash cred) =
Aeson.pairs
( "contents"
.= cred
<> "tag"
.= Aeson.String "StakingHash"
)
toEncoding (StakingPtr x y z) =
Aeson.pairs
( "contents"
.= [x, y, z]
<> "tag"
.= Aeson.String "StakingPtr"
)
@since 3.16.0
instance Aeson.FromJSON StakingCredential where
parseJSON = Aeson.withObject "StakingCredential" $ \v -> do
contents <- v .: "contents"
tag <- v .: "tag"
case tag of
"StakingHash" -> StakingHash <$> Aeson.parseJSON contents
"StakingPtr" -> parseStakingPtr contents
_ -> fail $ "Expected StakingHash or StakingPtr, got " <> tag
where
parseStakingPtr :: Aeson.Value -> Parser StakingCredential
parseStakingPtr v =
Aeson.parseJSONList v >>= \case
[x, y, z] -> pure $ StakingPtr x y z
xs ->
fail $
"expected an array of length 3, but got length "
<> show (length xs)
@since 3.16.0
instance Aeson.ToJSON Credential where
toJSON (PubKeyCredential cred) =
Aeson.object
[ "contents" .= Aeson.toJSON cred
, "tag" .= Aeson.String "PubKeyCredential"
]
toJSON (ScriptCredential cred) =
Aeson.object
[ "contents" .= Aeson.toJSON cred
, "tag" .= Aeson.String "ScriptCredential"
]
toEncoding (PubKeyCredential cred) =
Aeson.pairs
( "contents"
.= cred
<> "tag"
.= Aeson.String "PubKeyCredential"
)
toEncoding (ScriptCredential cred) =
Aeson.pairs
( "contents"
.= cred
<> "tag"
.= Aeson.String "ScriptCredential"
)
@since 3.16.0
instance Aeson.FromJSON Credential where
parseJSON = Aeson.withObject "Credential" $ \v -> do
contents <- v .: "contents"
tag <- v .: "tag"
case tag of
"PubKeyCredential" -> PubKeyCredential <$> Aeson.parseJSON contents
"ScriptCredential" -> ScriptCredential <$> Aeson.parseJSON contents
_ -> fail $ "Expected PubKeyCredential or ScriptCredential, got " <> tag
|
c7209d08fbf27755efc6ca577b2176ad5779407f72c853bacaa51edcc2639077 | yetibot/core | irc.clj | (ns yetibot.core.adapters.irc
(:require
[clojure.set :refer [difference union intersection]]
[clojure.spec.alpha :as s]
[yetibot.core.adapters.adapter :as a]
[taoensso.timbre :as log :refer [info debug]]
[throttler.core :refer [throttle-fn]]
[irclj
[core :as irc]
[connection :as irc-conn]]
[yetibot.core.models.users :as users]
[yetibot.core.models.channel :as channel]
[clojure.string :refer [split-lines join includes?]]
[yetibot.core.chat :refer [base-chat-source chat-source
chat-data-structure send-msg-for-each
*target* *adapter*] :as chat]
[yetibot.core.handler :refer [handle-raw]]))
(s/def ::type string?)
(s/def ::host string?)
(s/def ::port string?)
(s/def ::ssl string?)
(s/def ::username string?)
(s/def ::password string?)
(s/def ::config (s/keys :req-un [::type]
:opt-un [::username
::ssl
::host
::port
::password]))
(declare join-or-part-with-current-channels connect start stop)
(defn channels [{:keys [current-channels] :as a}] @current-channels)
(def wait-before-reconnect
"We need to delay before attempting to reconnect or else IRC will think the
username is still taken since it waits awhile to show the user as offline."
30000)
(def irc-max-message-length 420)
(defn split-msg-into-irc-max-length-chunks [msg]
(map join (partition-all irc-max-message-length msg)))
(defn reconnect [adapter reason]
(log/info reason ", trying to reconnect in" wait-before-reconnect "ms")
(stop adapter)
(Thread/sleep wait-before-reconnect)
(start adapter))
(def send-msg
"Rate-limited function for sending messages to IRC. It's rate limited in order
to prevent 'Excess Flood' kicks"
(throttle-fn
(fn [{:keys [conn] :as adapter} msg]
(log/info "send message to channel" *target*)
(try
(if (> (count msg) irc-max-message-length)
(doall (map
(partial send-msg adapter)
(split-msg-into-irc-max-length-chunks msg)))
(irc/message @conn *target* msg))
(catch java.net.SocketException e
; it must have disconnect, try reconnecting again
TODO add better retry , like Slack
(reconnect adapter "SocketException"))))
1 :second 5))
(defn- create-user [info]
(let [username (:nick info)
id (:user info)]
(users/create-user username (merge info {:id id}))))
(def prepare-paste
"Since pastes are sent as individual messages, blank lines would get
translated into \"No Results\" by the chat namespace. Instead of a blank
line, map it into a single space."
(comp (fn [coll] (map #(if (empty? %) " " %) coll))
split-lines))
(defn send-paste
"In IRC there are new newlines. Each line must be sent as a separate message, so
split it and send one for each"
[a p] (send-msg-for-each (prepare-paste p)))
(defn reload-and-reset-config!
"Reloads config from disk, then uses adapter uuid to lookup the correct config
map for this instance and resets the config atom with it."
[{:keys [channel-config] :as a}]
(let [uuid (a/uuid a)
new-conf (channel/get-yetibot-channels uuid)]
(info "reloaded config, now:" new-conf)
(reset! channel-config new-conf)))
(defn set-channels-config
"Accepts a function that will be passed the current channels config. Return
value of function will be used to set the new channels config"
[adapter f]
(let [uuid (a/uuid adapter)]
(channel/set-yetibot-channels uuid (f (channels adapter)))
(reload-and-reset-config! adapter)))
(defn add-channel-to-config [a channel]
(log/info "add channel" channel "to irc config")
(log/info
(set-channels-config a #(set (conj % channel)))))
(defn remove-channel-from-config [a channel]
(log/info "remove channel from irc config")
(set-channels-config a (comp set (partial filter #(not= % channel)))))
(defn join-channel [a channel]
(add-channel-to-config a channel)
(join-or-part-with-current-channels a)
(str "Joined " channel))
(defn leave-channel [a channel]
(remove-channel-from-config a channel)
(join-or-part-with-current-channels a)
(str "Left " channel))
(defn fetch-users [a]
(doall (map #(irc-conn/write-irc-line @(:conn a) "WHO" %) (channels a))))
(defn recognized-chan? [a chan] ((set (channels a)) chan))
(defn construct-yetibot-from-nick [nick]
{:username nick
:id (str "~" nick) })
(defn handle-message
"Recieve and handle messages from IRC. This can either be in channels yetibot
is listening in, or it can be a private message. If yetibot does not
recognize the :target, reply back to user with PRIVMSG."
[a irc info]
(log/info "handle-message" (pr-str info))
(let [config (:config a)
{yetibot-nick :nick} @irc
yetibot-user (construct-yetibot-from-nick yetibot-nick)
user-id (:user info)
chan (or (recognized-chan? a (:target info)) (:nick info))
user (users/get-user (chat-source chan) user-id)]
(log/info "handle message" info "from" chan yetibot-user)
(binding [*target* chan]
(handle-raw (chat-source chan)
user :message yetibot-user {:body (:text info)}))))
(defn handle-part
"Event that fires when someone leaves a channel that Yetibot is listening in"
[a irc {:keys [params] :as info}]
(log/debug "handle-part" (pr-str info))
(let [target (first params)]
(binding [*target* target]
(handle-raw (chat-source (first params))
(create-user info) :leave
(construct-yetibot-from-nick (:nick @irc))
{}))))
(defn handle-join [a irc {:keys [params] :as info}]
(log/debug "handle-join" info)
(let [target (first params)]
(binding [*target* target]
(handle-raw (chat-source target)
(create-user info) :enter
(construct-yetibot-from-nick (:nick @irc))
{}))))
(defn handle-nick [a _ info]
(let [[nick] (:params info)
id (:user info)]
(users/update-user
(chat-source (first (:params info))) id {:username nick :name nick})))
(defn handle-who-reply [a _ info]
(log/debug "352" info)
(let [{[_ channel user _ _ nick] :params} info]
(log/info "add user" channel user nick)
(users/add-user (chat-source channel)
(create-user {:user user :nick nick}))))
(defn next-nick [nick]
"Select next alternative nick"
;; rfc1459:
;; Each client is distinguished from other clients by a unique
nickname having a maximum length of nine ( 9 ) characters .
(let [nick-len (count nick)]
(if (< nick-len 9)
(str nick "_")
(loop [nick (vec nick) i (dec nick-len)]
(when (>= i 0)
(let [c (Character/digit (nth nick i) 10)
overflow? (= c 9)
next-nick (assoc nick i (mod (inc c) 10))]
(if overflow?
(recur next-nick (dec i))
(clojure.string/join next-nick))))))))
(defn handle-nick-in-use [a _ info]
(log/debug "433" info)
(let [{[_ nick] :params} info
{:keys [nick-state]} a
{:keys [retries nick]} @nick-state
can-retry? (< retries 10)
next-nick (when can-retry? (next-nick nick))
next-state (when next-nick {:retries (inc retries) :nick next-nick})]
(reset! nick-state next-state)
(if next-state
(reconnect a (str "nick " nick " is already in use"))
(log/info "Nick retries exhausted."))))
(defn handle-invite [a _ info]
(log/info "handle invite" info)
(join-channel a (second (:params info))))
(defn handle-notice [a _ info]
(log/debug "handle notice" info)
(let [info-msg (second (:params info))]
(when (includes? info-msg "throttled due to flooding")
(log/warn "NOTICE: " info-msg))))
(defn handle-raw-log [adapter _ b c]
(log/trace b c))
(defn handle-kick [a _ {:keys [params] :as info}]
(log/info "kicked" (pr-str info))
(leave-channel a (first params)))
(defn handle-end-of-names
"Callback for end of names list from IRC. Currently not doing anything with it."
[adapter irc event]
(let [users (-> @irc :channels vals first :users)]))
(defn callbacks
"Build a map of event handlers, with the adapter partially applied to each
handler.
Note: even though the handlers get the adapter as their first arg, some of
the functions they call still rely on *adapter* to be correctly bound. Fix
this!
As a hack, we can re-bind here."
[adapter]
(into {}
(for [[event-name event-handler]
{:privmsg #'handle-message
:raw-log #'handle-raw-log
:part #'handle-part
:kick #'handle-kick
:join #'handle-join
:notice #'handle-notice
:nick #'handle-nick
:invite #'handle-invite
:366 #'handle-end-of-names
:352 #'handle-who-reply
:433 #'handle-nick-in-use}]
[event-name
these are the args passed from irclj event fire
(fn [& event-args]
;; the hack. gross 😭
(binding [*adapter* adapter]
(apply (partial event-handler adapter) event-args)))])))
(defn connect [{:keys [config conn nick-state] :as a}]
(when-not @nick-state
(reset!
nick-state
{:retries 0
:nick (or (:username config) (str "yetibot_" (rand-int 1000)))}))
(let [username (:nick @nick-state)
host (or (:host config) "irc.freenode.net")
port (read-string (or (:port config) "6667"))
ssl? (boolean (:ssl config))]
(info "Connecting to IRC"
{:host host :port port :ssl? ssl? :username username})
(reset!
conn
(irc/connect host port username
:ssl? ssl?
:callbacks (callbacks a)))))
(defn join-or-part-with-current-channels
"Determine the diff between current-channels and configured channels to
determine which to join and part. After resolving the diff, set
current-channels equal to configured channels."
[{:keys [conn channel-config current-channels] :as adapter}]
(let [configured-channels @channel-config
to-part (difference @current-channels configured-channels)
to-join (difference configured-channels @current-channels)]
(info "configured-channels" configured-channels)
(debug "channels" @current-channels)
(debug "to-part" to-part)
(debug "to-join" to-join)
(reset! current-channels configured-channels)
(doall (map #(irc/join @conn %) to-join))
(doall (map #(irc/part @conn %) to-part))
(fetch-users adapter)))
(defn part
"Not currently used"
[{:keys [conn]} channel]
(when conn (irc/part @conn channel)))
(defn start
"Join and fetch all users with WHO <channel>"
[{:keys [channel-config config conn nick-state] :as adapter}]
(binding [*adapter* adapter]
(info "starting IRC with" config)
(info "*adapter* is" (log/color-str :blue (pr-str *adapter*)))
(reload-and-reset-config! adapter)
(connect adapter)
(join-or-part-with-current-channels adapter)))
(defn stop
"Kill the irc conection"
[{:keys [current-channels conn]}]
(when-let [c @conn] (irc/kill c))
(reset! current-channels #{})
(reset! conn nil))
(defrecord IRC
[config channel-config current-channels conn nick-state]
; config
; Holds the immutable configuration for a single IRC Adapter instance.
; channel-config
Loaded from database . It stores the IRC channels that Yetibot should
join on startup . When is commanded to join or leave channels ,
; channel-config is updated and persisted to the database.
; current-channels
Atom holding the set of current channels that is listening on . This
; is necessary to track in addition to channel-config in order to diff
; channels when modifying config to know which ones to part or join.
; conn
An atom that holds the IRC connection
a/Adapter
(a/uuid [_] (:name config))
(a/platform-name [_] "IRC")
(a/channels [a] (channels a))
(a/send-paste [a msg] (send-paste a msg))
(a/send-msg [a msg] (send-msg a msg))
(a/join [a channel] (join-channel a channel))
(a/leave [a channel] (leave-channel a channel))
(a/chat-source [_ channel] (chat-source channel))
(a/stop [adapter] (stop adapter))
(a/connected? [_] (when-let [c @conn] (-> c deref :ready? deref)))
TODO implement
TODO implement
(a/start [adapter] (start adapter)))
(defn make-irc
[config]
(->IRC config (atom {}) (atom #{}) (atom nil) (atom nil)))
| null | https://raw.githubusercontent.com/yetibot/core/e35cc772622e91aec3ad7f411a99fff09acbd3f9/src/yetibot/core/adapters/irc.clj | clojure | it must have disconnect, try reconnecting again
rfc1459:
Each client is distinguished from other clients by a unique
the hack. gross 😭
config
Holds the immutable configuration for a single IRC Adapter instance.
channel-config
channel-config is updated and persisted to the database.
current-channels
is necessary to track in addition to channel-config in order to diff
channels when modifying config to know which ones to part or join.
conn | (ns yetibot.core.adapters.irc
(:require
[clojure.set :refer [difference union intersection]]
[clojure.spec.alpha :as s]
[yetibot.core.adapters.adapter :as a]
[taoensso.timbre :as log :refer [info debug]]
[throttler.core :refer [throttle-fn]]
[irclj
[core :as irc]
[connection :as irc-conn]]
[yetibot.core.models.users :as users]
[yetibot.core.models.channel :as channel]
[clojure.string :refer [split-lines join includes?]]
[yetibot.core.chat :refer [base-chat-source chat-source
chat-data-structure send-msg-for-each
*target* *adapter*] :as chat]
[yetibot.core.handler :refer [handle-raw]]))
(s/def ::type string?)
(s/def ::host string?)
(s/def ::port string?)
(s/def ::ssl string?)
(s/def ::username string?)
(s/def ::password string?)
(s/def ::config (s/keys :req-un [::type]
:opt-un [::username
::ssl
::host
::port
::password]))
(declare join-or-part-with-current-channels connect start stop)
(defn channels [{:keys [current-channels] :as a}] @current-channels)
(def wait-before-reconnect
"We need to delay before attempting to reconnect or else IRC will think the
username is still taken since it waits awhile to show the user as offline."
30000)
(def irc-max-message-length 420)
(defn split-msg-into-irc-max-length-chunks [msg]
(map join (partition-all irc-max-message-length msg)))
(defn reconnect [adapter reason]
(log/info reason ", trying to reconnect in" wait-before-reconnect "ms")
(stop adapter)
(Thread/sleep wait-before-reconnect)
(start adapter))
(def send-msg
"Rate-limited function for sending messages to IRC. It's rate limited in order
to prevent 'Excess Flood' kicks"
(throttle-fn
(fn [{:keys [conn] :as adapter} msg]
(log/info "send message to channel" *target*)
(try
(if (> (count msg) irc-max-message-length)
(doall (map
(partial send-msg adapter)
(split-msg-into-irc-max-length-chunks msg)))
(irc/message @conn *target* msg))
(catch java.net.SocketException e
TODO add better retry , like Slack
(reconnect adapter "SocketException"))))
1 :second 5))
(defn- create-user [info]
(let [username (:nick info)
id (:user info)]
(users/create-user username (merge info {:id id}))))
(def prepare-paste
"Since pastes are sent as individual messages, blank lines would get
translated into \"No Results\" by the chat namespace. Instead of a blank
line, map it into a single space."
(comp (fn [coll] (map #(if (empty? %) " " %) coll))
split-lines))
(defn send-paste
"In IRC there are new newlines. Each line must be sent as a separate message, so
split it and send one for each"
[a p] (send-msg-for-each (prepare-paste p)))
(defn reload-and-reset-config!
"Reloads config from disk, then uses adapter uuid to lookup the correct config
map for this instance and resets the config atom with it."
[{:keys [channel-config] :as a}]
(let [uuid (a/uuid a)
new-conf (channel/get-yetibot-channels uuid)]
(info "reloaded config, now:" new-conf)
(reset! channel-config new-conf)))
(defn set-channels-config
"Accepts a function that will be passed the current channels config. Return
value of function will be used to set the new channels config"
[adapter f]
(let [uuid (a/uuid adapter)]
(channel/set-yetibot-channels uuid (f (channels adapter)))
(reload-and-reset-config! adapter)))
(defn add-channel-to-config [a channel]
(log/info "add channel" channel "to irc config")
(log/info
(set-channels-config a #(set (conj % channel)))))
(defn remove-channel-from-config [a channel]
(log/info "remove channel from irc config")
(set-channels-config a (comp set (partial filter #(not= % channel)))))
(defn join-channel [a channel]
(add-channel-to-config a channel)
(join-or-part-with-current-channels a)
(str "Joined " channel))
(defn leave-channel [a channel]
(remove-channel-from-config a channel)
(join-or-part-with-current-channels a)
(str "Left " channel))
(defn fetch-users [a]
(doall (map #(irc-conn/write-irc-line @(:conn a) "WHO" %) (channels a))))
(defn recognized-chan? [a chan] ((set (channels a)) chan))
(defn construct-yetibot-from-nick [nick]
{:username nick
:id (str "~" nick) })
(defn handle-message
"Recieve and handle messages from IRC. This can either be in channels yetibot
is listening in, or it can be a private message. If yetibot does not
recognize the :target, reply back to user with PRIVMSG."
[a irc info]
(log/info "handle-message" (pr-str info))
(let [config (:config a)
{yetibot-nick :nick} @irc
yetibot-user (construct-yetibot-from-nick yetibot-nick)
user-id (:user info)
chan (or (recognized-chan? a (:target info)) (:nick info))
user (users/get-user (chat-source chan) user-id)]
(log/info "handle message" info "from" chan yetibot-user)
(binding [*target* chan]
(handle-raw (chat-source chan)
user :message yetibot-user {:body (:text info)}))))
(defn handle-part
"Event that fires when someone leaves a channel that Yetibot is listening in"
[a irc {:keys [params] :as info}]
(log/debug "handle-part" (pr-str info))
(let [target (first params)]
(binding [*target* target]
(handle-raw (chat-source (first params))
(create-user info) :leave
(construct-yetibot-from-nick (:nick @irc))
{}))))
(defn handle-join [a irc {:keys [params] :as info}]
(log/debug "handle-join" info)
(let [target (first params)]
(binding [*target* target]
(handle-raw (chat-source target)
(create-user info) :enter
(construct-yetibot-from-nick (:nick @irc))
{}))))
(defn handle-nick [a _ info]
(let [[nick] (:params info)
id (:user info)]
(users/update-user
(chat-source (first (:params info))) id {:username nick :name nick})))
(defn handle-who-reply [a _ info]
(log/debug "352" info)
(let [{[_ channel user _ _ nick] :params} info]
(log/info "add user" channel user nick)
(users/add-user (chat-source channel)
(create-user {:user user :nick nick}))))
(defn next-nick [nick]
"Select next alternative nick"
nickname having a maximum length of nine ( 9 ) characters .
(let [nick-len (count nick)]
(if (< nick-len 9)
(str nick "_")
(loop [nick (vec nick) i (dec nick-len)]
(when (>= i 0)
(let [c (Character/digit (nth nick i) 10)
overflow? (= c 9)
next-nick (assoc nick i (mod (inc c) 10))]
(if overflow?
(recur next-nick (dec i))
(clojure.string/join next-nick))))))))
(defn handle-nick-in-use [a _ info]
(log/debug "433" info)
(let [{[_ nick] :params} info
{:keys [nick-state]} a
{:keys [retries nick]} @nick-state
can-retry? (< retries 10)
next-nick (when can-retry? (next-nick nick))
next-state (when next-nick {:retries (inc retries) :nick next-nick})]
(reset! nick-state next-state)
(if next-state
(reconnect a (str "nick " nick " is already in use"))
(log/info "Nick retries exhausted."))))
(defn handle-invite [a _ info]
(log/info "handle invite" info)
(join-channel a (second (:params info))))
(defn handle-notice [a _ info]
(log/debug "handle notice" info)
(let [info-msg (second (:params info))]
(when (includes? info-msg "throttled due to flooding")
(log/warn "NOTICE: " info-msg))))
(defn handle-raw-log [adapter _ b c]
(log/trace b c))
(defn handle-kick [a _ {:keys [params] :as info}]
(log/info "kicked" (pr-str info))
(leave-channel a (first params)))
(defn handle-end-of-names
"Callback for end of names list from IRC. Currently not doing anything with it."
[adapter irc event]
(let [users (-> @irc :channels vals first :users)]))
(defn callbacks
"Build a map of event handlers, with the adapter partially applied to each
handler.
Note: even though the handlers get the adapter as their first arg, some of
the functions they call still rely on *adapter* to be correctly bound. Fix
this!
As a hack, we can re-bind here."
[adapter]
(into {}
(for [[event-name event-handler]
{:privmsg #'handle-message
:raw-log #'handle-raw-log
:part #'handle-part
:kick #'handle-kick
:join #'handle-join
:notice #'handle-notice
:nick #'handle-nick
:invite #'handle-invite
:366 #'handle-end-of-names
:352 #'handle-who-reply
:433 #'handle-nick-in-use}]
[event-name
these are the args passed from irclj event fire
(fn [& event-args]
(binding [*adapter* adapter]
(apply (partial event-handler adapter) event-args)))])))
(defn connect [{:keys [config conn nick-state] :as a}]
(when-not @nick-state
(reset!
nick-state
{:retries 0
:nick (or (:username config) (str "yetibot_" (rand-int 1000)))}))
(let [username (:nick @nick-state)
host (or (:host config) "irc.freenode.net")
port (read-string (or (:port config) "6667"))
ssl? (boolean (:ssl config))]
(info "Connecting to IRC"
{:host host :port port :ssl? ssl? :username username})
(reset!
conn
(irc/connect host port username
:ssl? ssl?
:callbacks (callbacks a)))))
(defn join-or-part-with-current-channels
"Determine the diff between current-channels and configured channels to
determine which to join and part. After resolving the diff, set
current-channels equal to configured channels."
[{:keys [conn channel-config current-channels] :as adapter}]
(let [configured-channels @channel-config
to-part (difference @current-channels configured-channels)
to-join (difference configured-channels @current-channels)]
(info "configured-channels" configured-channels)
(debug "channels" @current-channels)
(debug "to-part" to-part)
(debug "to-join" to-join)
(reset! current-channels configured-channels)
(doall (map #(irc/join @conn %) to-join))
(doall (map #(irc/part @conn %) to-part))
(fetch-users adapter)))
(defn part
"Not currently used"
[{:keys [conn]} channel]
(when conn (irc/part @conn channel)))
(defn start
"Join and fetch all users with WHO <channel>"
[{:keys [channel-config config conn nick-state] :as adapter}]
(binding [*adapter* adapter]
(info "starting IRC with" config)
(info "*adapter* is" (log/color-str :blue (pr-str *adapter*)))
(reload-and-reset-config! adapter)
(connect adapter)
(join-or-part-with-current-channels adapter)))
(defn stop
"Kill the irc conection"
[{:keys [current-channels conn]}]
(when-let [c @conn] (irc/kill c))
(reset! current-channels #{})
(reset! conn nil))
(defrecord IRC
[config channel-config current-channels conn nick-state]
Loaded from database . It stores the IRC channels that Yetibot should
join on startup . When is commanded to join or leave channels ,
Atom holding the set of current channels that is listening on . This
An atom that holds the IRC connection
a/Adapter
(a/uuid [_] (:name config))
(a/platform-name [_] "IRC")
(a/channels [a] (channels a))
(a/send-paste [a msg] (send-paste a msg))
(a/send-msg [a msg] (send-msg a msg))
(a/join [a channel] (join-channel a channel))
(a/leave [a channel] (leave-channel a channel))
(a/chat-source [_ channel] (chat-source channel))
(a/stop [adapter] (stop adapter))
(a/connected? [_] (when-let [c @conn] (-> c deref :ready? deref)))
TODO implement
TODO implement
(a/start [adapter] (start adapter)))
(defn make-irc
[config]
(->IRC config (atom {}) (atom #{}) (atom nil) (atom nil)))
|
ebc6fb797c09f7f1138c6bc482edc02cc21f96d4864ff789c4462c0bfffaf26a | Javran/unicode-general-category | GeneralCategory.hs | | This module simply re - exports predicate functions from latest Unicode version
-- (as of package release).
module Data.Char.GeneralCategory
( module Data.Char.GeneralCategory.V13_0_0
)
where
import Data.Char.GeneralCategory.V13_0_0 hiding (genCatDb)
| null | https://raw.githubusercontent.com/Javran/unicode-general-category/754d53dfda54cdf8b1159e30d6949ffd623c8900/src/Data/Char/GeneralCategory.hs | haskell | (as of package release). | | This module simply re - exports predicate functions from latest Unicode version
module Data.Char.GeneralCategory
( module Data.Char.GeneralCategory.V13_0_0
)
where
import Data.Char.GeneralCategory.V13_0_0 hiding (genCatDb)
|
a8813a9b0c081e761d2825fccfbc5c760d248e4d8976a954a6150fdb9a50a0a1 | willghatch/racket-rash | rc17-demo-modbeg.rkt | #lang racket/base
(provide
(all-from-out rash/demo/setup)
(except-out (all-from-out racket/base) #%module-begin #%top-interaction)
(rename-out [basic-rash-module-begin #%module-begin]
[basic-rash-top-interaction #%top-interaction])
(all-from-out rash)
app
def
)
(require
rash/demo/setup
rash
(for-syntax
racket/base
syntax/parse
))
(define-rash-module-begin basic-rash-module-begin basic-rash-top-interaction
#:in (current-input-port)
#:out (current-output-port)
#:err (current-error-port)
#:starter =unix-pipe=
)
#;(define-syntax basic-rash-module-begin
(make-rash-module-begin-transformer #:in (current-input-port)
#:out (current-output-port)
#:err (current-error-port)
#:default-starter #'=quoting-basic-unix-pipe=
;#:default-line-macro #'pipeline-line-macro
))
;;; additional demo definitions
(define-line-macro app (syntax-parser [(_ arg ...) #'(arg ...)]))
(define-line-macro def (syntax-parser [(_ def-form arg ...)
#'(define def-form
(do-line-macro arg ...))]))
| null | https://raw.githubusercontent.com/willghatch/racket-rash/c40c5adfedf632bc1fdbad3e0e2763b134ee3ff5/rash-demos/rash/demo/rc17-demo-modbeg.rkt | racket | (define-syntax basic-rash-module-begin
#:default-line-macro #'pipeline-line-macro
additional demo definitions | #lang racket/base
(provide
(all-from-out rash/demo/setup)
(except-out (all-from-out racket/base) #%module-begin #%top-interaction)
(rename-out [basic-rash-module-begin #%module-begin]
[basic-rash-top-interaction #%top-interaction])
(all-from-out rash)
app
def
)
(require
rash/demo/setup
rash
(for-syntax
racket/base
syntax/parse
))
(define-rash-module-begin basic-rash-module-begin basic-rash-top-interaction
#:in (current-input-port)
#:out (current-output-port)
#:err (current-error-port)
#:starter =unix-pipe=
)
(make-rash-module-begin-transformer #:in (current-input-port)
#:out (current-output-port)
#:err (current-error-port)
#:default-starter #'=quoting-basic-unix-pipe=
))
(define-line-macro app (syntax-parser [(_ arg ...) #'(arg ...)]))
(define-line-macro def (syntax-parser [(_ def-form arg ...)
#'(define def-form
(do-line-macro arg ...))]))
|
dedd3cabf94eb9734ec837c2999f37e5836f7f856ccdeafee7d1f59e7d2db78f | Frama-C/Frama-C-snapshot | Why3Provers.ml | (**************************************************************************)
(* *)
This file is part of WP plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2019
CEA ( Commissariat a l'energie atomique et aux energies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(* -------------------------------------------------------------------------- *)
(* --- Why3 Config & Provers --- *)
(* -------------------------------------------------------------------------- *)
let cfg = lazy
begin
try
Why3.Whyconf.read_config None
with exn ->
Wp_parameters.abort "%a" Why3.Exn_printer.exn_printer exn
end
let version = Why3.Config.version
let config () = Lazy.force cfg
let set_procs = Why3.Controller_itp.set_session_max_tasks
let configure =
let todo = ref true in
begin fun () ->
if !todo then
begin
let args = Array.of_list ("why3"::Wp_parameters.Why3Flags.get ()) in
begin try
Arg.parse_argv ~current:(ref 0) args
(Why3.Debug.Args.[desc_debug;desc_debug_all;desc_debug_list])
(fun _ -> raise (Arg.Help "Unknown why3 option"))
"Why3 options"
with Arg.Bad s -> Wp_parameters.abort "%s" s
end;
ignore (Why3.Debug.Args.option_list ());
Why3.Debug.Args.set_flags_selected ();
todo := false
end
end
type t = Why3.Whyconf.prover
let find_opt s =
try
let config = Lazy.force cfg in
let filter = Why3.Whyconf.parse_filter_prover s in
let filter = Why3.Whyconf.filter_prover_with_shortcut config filter in
Some ((Why3.Whyconf.filter_one_prover config filter).Why3.Whyconf.prover)
with
| Why3.Whyconf.ProverNotFound _
| Why3.Whyconf.ParseFilterProver _
| Why3.Whyconf.ProverAmbiguity _ ->
None
let find ?donotfail s =
try
try
let config = Lazy.force cfg in
let filter = Why3.Whyconf.parse_filter_prover s in
let filter = Why3.Whyconf.filter_prover_with_shortcut config filter in
(Why3.Whyconf.filter_one_prover config filter).Why3.Whyconf.prover
with
| Why3.Whyconf.ProverNotFound _ as exn when donotfail <> None ->
Wp_parameters.warning ~once:true "%a" Why3.Exn_printer.exn_printer exn;
* from Why3.Whyconf.parse_filter_prover
let sl = Why3.Strings.rev_split ',' s in
(* reverse order *)
let prover_name, prover_version, prover_altern =
match sl with
| [name] -> name,"",""
| [version;name] -> name,version,""
| [altern;version;name] -> name,version,altern
| _ -> raise (Why3.Whyconf.ParseFilterProver s) in
{ Why3.Whyconf.prover_name; Why3.Whyconf.prover_version; Why3.Whyconf.prover_altern }
with
| ( Why3.Whyconf.ProverNotFound _
| Why3.Whyconf.ParseFilterProver _
| Why3.Whyconf.ProverAmbiguity _ ) as exn ->
Wp_parameters.abort "%a" Why3.Exn_printer.exn_printer exn
let print = Why3.Whyconf.prover_parseable_format
let title p = Pretty_utils.sfprintf "%a" Why3.Whyconf.print_prover p
let compare = Why3.Whyconf.Prover.compare
let provers () =
Why3.Whyconf.Mprover.keys (Why3.Whyconf.get_provers (config ()))
let provers_set () : Why3.Whyconf.Sprover.t =
Why3.Whyconf.Mprover.domain (Why3.Whyconf.get_provers (config ()))
let is_available p =
Why3.Whyconf.Mprover.mem p (Why3.Whyconf.get_provers (config ()))
let has_shortcut p s =
match Why3.Wstdlib.Mstr.find_opt s
(Why3.Whyconf.get_prover_shortcuts (config ())) with
| None -> false
| Some p' -> Why3.Whyconf.Prover.equal p p'
| null | https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/wp/Why3Provers.ml | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
--------------------------------------------------------------------------
--- Why3 Config & Provers ---
--------------------------------------------------------------------------
reverse order | This file is part of WP plug - in of Frama - C.
Copyright ( C ) 2007 - 2019
CEA ( Commissariat a l'energie atomique et aux energies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
let cfg = lazy
begin
try
Why3.Whyconf.read_config None
with exn ->
Wp_parameters.abort "%a" Why3.Exn_printer.exn_printer exn
end
let version = Why3.Config.version
let config () = Lazy.force cfg
let set_procs = Why3.Controller_itp.set_session_max_tasks
let configure =
let todo = ref true in
begin fun () ->
if !todo then
begin
let args = Array.of_list ("why3"::Wp_parameters.Why3Flags.get ()) in
begin try
Arg.parse_argv ~current:(ref 0) args
(Why3.Debug.Args.[desc_debug;desc_debug_all;desc_debug_list])
(fun _ -> raise (Arg.Help "Unknown why3 option"))
"Why3 options"
with Arg.Bad s -> Wp_parameters.abort "%s" s
end;
ignore (Why3.Debug.Args.option_list ());
Why3.Debug.Args.set_flags_selected ();
todo := false
end
end
type t = Why3.Whyconf.prover
let find_opt s =
try
let config = Lazy.force cfg in
let filter = Why3.Whyconf.parse_filter_prover s in
let filter = Why3.Whyconf.filter_prover_with_shortcut config filter in
Some ((Why3.Whyconf.filter_one_prover config filter).Why3.Whyconf.prover)
with
| Why3.Whyconf.ProverNotFound _
| Why3.Whyconf.ParseFilterProver _
| Why3.Whyconf.ProverAmbiguity _ ->
None
let find ?donotfail s =
try
try
let config = Lazy.force cfg in
let filter = Why3.Whyconf.parse_filter_prover s in
let filter = Why3.Whyconf.filter_prover_with_shortcut config filter in
(Why3.Whyconf.filter_one_prover config filter).Why3.Whyconf.prover
with
| Why3.Whyconf.ProverNotFound _ as exn when donotfail <> None ->
Wp_parameters.warning ~once:true "%a" Why3.Exn_printer.exn_printer exn;
* from Why3.Whyconf.parse_filter_prover
let sl = Why3.Strings.rev_split ',' s in
let prover_name, prover_version, prover_altern =
match sl with
| [name] -> name,"",""
| [version;name] -> name,version,""
| [altern;version;name] -> name,version,altern
| _ -> raise (Why3.Whyconf.ParseFilterProver s) in
{ Why3.Whyconf.prover_name; Why3.Whyconf.prover_version; Why3.Whyconf.prover_altern }
with
| ( Why3.Whyconf.ProverNotFound _
| Why3.Whyconf.ParseFilterProver _
| Why3.Whyconf.ProverAmbiguity _ ) as exn ->
Wp_parameters.abort "%a" Why3.Exn_printer.exn_printer exn
let print = Why3.Whyconf.prover_parseable_format
let title p = Pretty_utils.sfprintf "%a" Why3.Whyconf.print_prover p
let compare = Why3.Whyconf.Prover.compare
let provers () =
Why3.Whyconf.Mprover.keys (Why3.Whyconf.get_provers (config ()))
let provers_set () : Why3.Whyconf.Sprover.t =
Why3.Whyconf.Mprover.domain (Why3.Whyconf.get_provers (config ()))
let is_available p =
Why3.Whyconf.Mprover.mem p (Why3.Whyconf.get_provers (config ()))
let has_shortcut p s =
match Why3.Wstdlib.Mstr.find_opt s
(Why3.Whyconf.get_prover_shortcuts (config ())) with
| None -> false
| Some p' -> Why3.Whyconf.Prover.equal p p'
|
68a80a7e4501f66eb1e5aa4eeb8e97eb48fc823faf4607c8e9d1346cd3eb7cf3 | metaocaml/ber-metaocaml | finaliser.ml | (* TEST
*)
let m = 1000
let m' = 100
let k = m*10
* the printing are not stable between ocamlc and ocamlopt
let debug = false
let gc_print where _ =
if debug then
let stat = Gc.quick_stat () in
Printf.printf "minor: %i major: %i %s\n%!"
stat.Gc.minor_collections
stat.Gc.major_collections
where
let r = Array.init m (fun _ -> Array.make m 1)
let () =
gc_print "[Before]" ();
let rec aux n =
if n < k then begin
r.(n mod m) <- (Array.make m' n);
begin match n mod m with
| 0 ->
* finalise first major
gc_print (Printf.sprintf "[Create %i first]" n) ();
Gc.finalise (gc_print (Printf.sprintf "[Finalise %i first]" n)) r.(0)
| 1 ->
(** finalise last major *)
gc_print (Printf.sprintf "[Create %i last]" n) ();
Gc.finalise_last
(gc_print (Printf.sprintf "[Finalise %i last]" n)) r.(1)
| 2 ->
* finalise first minor
let m = ref 1 in
gc_print (Printf.sprintf "[Create %i first minor]" n) ();
Gc.finalise
(gc_print (Printf.sprintf "[Finalise %i first minor]" n)) m
| 3 ->
(** finalise last minor *)
let m = ref 1 in
gc_print (Printf.sprintf "[Create %i last minor]" n) ();
Gc.finalise_last
(gc_print (Printf.sprintf "[Finalise %i last minor]" n)) m
| 4 ->
* finalise first - last major
gc_print (Printf.sprintf "[Create %i first]" n) ();
Gc.finalise (gc_print (Printf.sprintf "[Finalise %i first]" n)) r.(4);
Gc.finalise_last
(gc_print (Printf.sprintf "[Finalise %i first]" n)) r.(4)
| _ -> ()
end;
aux (n + 1)
end
in
aux 0;
gc_print "[Full major]" ();
Gc.full_major ();
gc_print "[Second full major]" ();
Gc.full_major ();
gc_print "[Third full major]" ();
Gc.full_major ();
()
let () = flush stdout
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/misc/finaliser.ml | ocaml | TEST
* finalise last major
* finalise last minor |
let m = 1000
let m' = 100
let k = m*10
* the printing are not stable between ocamlc and ocamlopt
let debug = false
let gc_print where _ =
if debug then
let stat = Gc.quick_stat () in
Printf.printf "minor: %i major: %i %s\n%!"
stat.Gc.minor_collections
stat.Gc.major_collections
where
let r = Array.init m (fun _ -> Array.make m 1)
let () =
gc_print "[Before]" ();
let rec aux n =
if n < k then begin
r.(n mod m) <- (Array.make m' n);
begin match n mod m with
| 0 ->
* finalise first major
gc_print (Printf.sprintf "[Create %i first]" n) ();
Gc.finalise (gc_print (Printf.sprintf "[Finalise %i first]" n)) r.(0)
| 1 ->
gc_print (Printf.sprintf "[Create %i last]" n) ();
Gc.finalise_last
(gc_print (Printf.sprintf "[Finalise %i last]" n)) r.(1)
| 2 ->
* finalise first minor
let m = ref 1 in
gc_print (Printf.sprintf "[Create %i first minor]" n) ();
Gc.finalise
(gc_print (Printf.sprintf "[Finalise %i first minor]" n)) m
| 3 ->
let m = ref 1 in
gc_print (Printf.sprintf "[Create %i last minor]" n) ();
Gc.finalise_last
(gc_print (Printf.sprintf "[Finalise %i last minor]" n)) m
| 4 ->
* finalise first - last major
gc_print (Printf.sprintf "[Create %i first]" n) ();
Gc.finalise (gc_print (Printf.sprintf "[Finalise %i first]" n)) r.(4);
Gc.finalise_last
(gc_print (Printf.sprintf "[Finalise %i first]" n)) r.(4)
| _ -> ()
end;
aux (n + 1)
end
in
aux 0;
gc_print "[Full major]" ();
Gc.full_major ();
gc_print "[Second full major]" ();
Gc.full_major ();
gc_print "[Third full major]" ();
Gc.full_major ();
()
let () = flush stdout
|
2fecc85ebc3609cf3b150238ec3d53dd2e4492bcbed49321ab04332974227a81 | wjrforcyber/SystemT | Double.hs | {-# LANGUAGE OverloadedStrings #-}
-- | Predecessor
module Lang.L6.Examples.Double where
import Lang.L6.Eval.EEval
import Lang.L6.Examples.Add (addHs)
import Lang.L6.Examples.Base
import Test.QuickCheck ((===))
import qualified Test.QuickCheck as QC
| Double in Haskell
doubleHs :: Nat -> Nat
doubleHs Zero = Zero
doubleHs n = addHs n n
| type of Double in L6
doubleTy :: Ty
doubleTy = TFun TNat TNat
doubleExp :: Exp
doubleExp =
ELam
"nat_n"
TNat
( EIter
(EVar "nat_n")
( ELam
"nat_t"
TNat
(ESucc (EVar "nat_t"))
)
(EVar "nat_n")
)
-- | check that both versions agree
doubleProp :: QC.Property
doubleProp = QC.property $ \n ->
toNat (evalStar $ EApp doubleExp (fromNat n)) === Just (doubleHs n)
doubleProg :: Program
doubleProg = Program "double" doubleTy doubleExp doubleProp
| null | https://raw.githubusercontent.com/wjrforcyber/SystemT/6e3248a2f734ac86c7fc3b7d407ce1a7e3c66048/src/Lang/L6/Examples/Double.hs | haskell | # LANGUAGE OverloadedStrings #
| Predecessor
| check that both versions agree |
module Lang.L6.Examples.Double where
import Lang.L6.Eval.EEval
import Lang.L6.Examples.Add (addHs)
import Lang.L6.Examples.Base
import Test.QuickCheck ((===))
import qualified Test.QuickCheck as QC
| Double in Haskell
doubleHs :: Nat -> Nat
doubleHs Zero = Zero
doubleHs n = addHs n n
| type of Double in L6
doubleTy :: Ty
doubleTy = TFun TNat TNat
doubleExp :: Exp
doubleExp =
ELam
"nat_n"
TNat
( EIter
(EVar "nat_n")
( ELam
"nat_t"
TNat
(ESucc (EVar "nat_t"))
)
(EVar "nat_n")
)
doubleProp :: QC.Property
doubleProp = QC.property $ \n ->
toNat (evalStar $ EApp doubleExp (fromNat n)) === Just (doubleHs n)
doubleProg :: Program
doubleProg = Program "double" doubleTy doubleExp doubleProp
|
e9b1bcdb5ed2816e531a4b026f056d5f6728f748227d6e7af45a4ed6ab308c8c | Frama-C/Frama-C-snapshot | numerors_float.mli | (**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2019
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
open Numerors_utils
(*-----------------------------------------------------------------------------
* Generic signature for a module representing float numbers
*---------------------------------------------------------------------------*)
type t
val pretty : Format.formatter -> t -> unit
(** Returns a t element representing a positive infinite value *)
val pos_inf : Precisions.t -> t
(** Returns a t element representing a negative infinite value *)
val neg_inf : Precisions.t -> t
* Returns a t element representing a positive zero value
val pos_zero : Precisions.t -> t
* Returns a t element representing a negative zero value
val neg_zero : Precisions.t -> t
* This function returns a float of precision ? prec containing the machine
epsilon divided by two for the mandatory precision parameter . We divide it
by two because we are only interested in the rounding to nearest mode .
epsilon divided by two for the mandatory precision parameter. We divide it
by two because we are only interested in the rounding to nearest mode. *)
val machine_epsilon : ?prec:Precisions.t -> Precisions.t -> t
* This function returns a float of precision ? prec containing the machine
delta of the mandatory precision parameter also divided by two for the same
reason as machine_epsilon .
delta of the mandatory precision parameter also divided by two for the same
reason as machine_epsilon. *)
val machine_delta : ?prec:Precisions.t -> Precisions.t -> t
* Maximal positive float in the precision
val maximal_pos_float : prec:Precisions.t -> t
(** Maximal negative float in the precision *)
val maximal_neg_float : prec:Precisions.t -> t
* The functions of_<typ > ~rnd ~prec x return a float of precision < prec >
containing the value of x ( of type < typ > ) rounding to < rnd > . The default
values are prec = Precisions . Real and rnd = Rounding . Near
containing the value of x (of type <typ>) rounding to <rnd>. The default
values are prec=Precisions.Real and rnd=Rounding.Near *)
val of_int : ?rnd:Rounding.t -> ?prec:Precisions.t -> int -> t
val of_float : ?rnd:Rounding.t -> ?prec:Precisions.t -> float -> t
val of_string : ?rnd:Rounding.t -> ?prec:Precisions.t -> string -> t
(** Change the precision *)
val change_prec : rnd:Rounding.t -> prec:Precisions.t -> t -> t
(** Comparison functions *)
val compare : t -> t -> int
val eq : t -> t -> bool
val le : t -> t -> bool
val lt : t -> t -> bool
val ge : t -> t -> bool
val gt : t -> t -> bool
val min : t -> t -> t
val max : t -> t -> t
* Check if its input is a NaN
val is_nan : t -> bool
(** Check if its input is an infinite value *)
val is_inf : t -> bool
* Check if its input is positive ( is_pos NaN = true )
val is_pos : t -> bool
* Check if its input is negative ( is_neg NaN = false )
val is_neg : t -> bool
* Check if its input is a zero ( positive or negative )
val is_a_zero : t -> bool
* Check if its input is a positive zero
val is_pos_zero : t -> bool
* Check if its input is a negative zero
val is_neg_zero : t -> bool
* Check if its input is strictly positive ( non zero )
val is_strictly_pos : t -> bool
(** Check if its input is strictly negative (non zero) *)
val is_strictly_neg : t -> bool
* Returns the sign of its input . The sign of a NaN is Positive
val sign : t -> Sign.t
(** Returns the precision of its input *)
val prec : t -> Precisions.t
(** Returns the exponent of its input *)
val exponent : t -> int
* Returns the significand of its input . This function is known to generate a
core dump if the version of your MPFR library is the 3.0.1 . The version 4.0
of the library does not have the bug anymore .
core dump if the version of your MPFR library is the 3.0.1. The version 4.0
of the library does not have the bug anymore. *)
val significand : t -> t
(** Returns a element containing the same value as <dst> but with the sign
of <src> *)
val apply_sign : src:t -> dst:t -> t
(** Returns the previous floating point number of the same precision *)
val prev_float : t -> t
(** Returns the following floating point number of the same precision *)
val next_float : t -> t
(** Negation *)
val neg : t -> t
(** Absolute value *)
val abs : t -> t
* The following functions perform floating - point arithmetic operations at
the precision < prec > and using the rounding mode < rnd > . Their default
values are prec = Precisions . Real and rnd = Rounding . Near . The inputs are
" casted " to the asked precision if necessary before computing the
operation
the precision <prec> and using the rounding mode <rnd>. Their default
values are prec=Precisions.Real and rnd=Rounding.Near. The inputs are
"casted" to the asked precision if necessary before computing the
operation *)
val add : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t -> t
val sub : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t -> t
val mul : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t -> t
val div : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t -> t
val pow : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t -> t
val pow_int : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> int -> t
val square : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
val sqrt : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
val log : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
val exp : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
val sin : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
val cos : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
val tan : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
| null | https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/value/values/numerors/numerors_float.mli | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
-----------------------------------------------------------------------------
* Generic signature for a module representing float numbers
*---------------------------------------------------------------------------
* Returns a t element representing a positive infinite value
* Returns a t element representing a negative infinite value
* Maximal negative float in the precision
* Change the precision
* Comparison functions
* Check if its input is an infinite value
* Check if its input is strictly negative (non zero)
* Returns the precision of its input
* Returns the exponent of its input
* Returns a element containing the same value as <dst> but with the sign
of <src>
* Returns the previous floating point number of the same precision
* Returns the following floating point number of the same precision
* Negation
* Absolute value | This file is part of Frama - C.
Copyright ( C ) 2007 - 2019
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Numerors_utils
type t
val pretty : Format.formatter -> t -> unit
val pos_inf : Precisions.t -> t
val neg_inf : Precisions.t -> t
* Returns a t element representing a positive zero value
val pos_zero : Precisions.t -> t
* Returns a t element representing a negative zero value
val neg_zero : Precisions.t -> t
* This function returns a float of precision ? prec containing the machine
epsilon divided by two for the mandatory precision parameter . We divide it
by two because we are only interested in the rounding to nearest mode .
epsilon divided by two for the mandatory precision parameter. We divide it
by two because we are only interested in the rounding to nearest mode. *)
val machine_epsilon : ?prec:Precisions.t -> Precisions.t -> t
* This function returns a float of precision ? prec containing the machine
delta of the mandatory precision parameter also divided by two for the same
reason as machine_epsilon .
delta of the mandatory precision parameter also divided by two for the same
reason as machine_epsilon. *)
val machine_delta : ?prec:Precisions.t -> Precisions.t -> t
* Maximal positive float in the precision
val maximal_pos_float : prec:Precisions.t -> t
val maximal_neg_float : prec:Precisions.t -> t
* The functions of_<typ > ~rnd ~prec x return a float of precision < prec >
containing the value of x ( of type < typ > ) rounding to < rnd > . The default
values are prec = Precisions . Real and rnd = Rounding . Near
containing the value of x (of type <typ>) rounding to <rnd>. The default
values are prec=Precisions.Real and rnd=Rounding.Near *)
val of_int : ?rnd:Rounding.t -> ?prec:Precisions.t -> int -> t
val of_float : ?rnd:Rounding.t -> ?prec:Precisions.t -> float -> t
val of_string : ?rnd:Rounding.t -> ?prec:Precisions.t -> string -> t
val change_prec : rnd:Rounding.t -> prec:Precisions.t -> t -> t
val compare : t -> t -> int
val eq : t -> t -> bool
val le : t -> t -> bool
val lt : t -> t -> bool
val ge : t -> t -> bool
val gt : t -> t -> bool
val min : t -> t -> t
val max : t -> t -> t
* Check if its input is a NaN
val is_nan : t -> bool
val is_inf : t -> bool
* Check if its input is positive ( is_pos NaN = true )
val is_pos : t -> bool
* Check if its input is negative ( is_neg NaN = false )
val is_neg : t -> bool
* Check if its input is a zero ( positive or negative )
val is_a_zero : t -> bool
* Check if its input is a positive zero
val is_pos_zero : t -> bool
* Check if its input is a negative zero
val is_neg_zero : t -> bool
* Check if its input is strictly positive ( non zero )
val is_strictly_pos : t -> bool
val is_strictly_neg : t -> bool
* Returns the sign of its input . The sign of a NaN is Positive
val sign : t -> Sign.t
val prec : t -> Precisions.t
val exponent : t -> int
* Returns the significand of its input . This function is known to generate a
core dump if the version of your MPFR library is the 3.0.1 . The version 4.0
of the library does not have the bug anymore .
core dump if the version of your MPFR library is the 3.0.1. The version 4.0
of the library does not have the bug anymore. *)
val significand : t -> t
val apply_sign : src:t -> dst:t -> t
val prev_float : t -> t
val next_float : t -> t
val neg : t -> t
val abs : t -> t
* The following functions perform floating - point arithmetic operations at
the precision < prec > and using the rounding mode < rnd > . Their default
values are prec = Precisions . Real and rnd = Rounding . Near . The inputs are
" casted " to the asked precision if necessary before computing the
operation
the precision <prec> and using the rounding mode <rnd>. Their default
values are prec=Precisions.Real and rnd=Rounding.Near. The inputs are
"casted" to the asked precision if necessary before computing the
operation *)
val add : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t -> t
val sub : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t -> t
val mul : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t -> t
val div : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t -> t
val pow : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t -> t
val pow_int : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> int -> t
val square : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
val sqrt : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
val log : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
val exp : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
val sin : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
val cos : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
val tan : ?rnd:Rounding.t -> ?prec:Precisions.t -> t -> t
|
347f32512b2c41acf72f0247a19e9a7dea9671665fbebfd3e8812559fc99a5b6 | footprintanalytics/footprint-web | streaming_response.clj | (ns metabase.async.streaming-response
(:require [cheshire.core :as json]
[clojure.core.async :as a]
[clojure.tools.logging :as log]
compojure.response
[metabase.async.streaming-response.thread-pool :as thread-pool]
[metabase.async.util :as async.u]
[metabase.server.protocols :as server.protocols]
[metabase.util :as u]
[metabase.util.i18n :refer [trs]]
[potemkin.types :as p.types]
[pretty.core :as pretty]
[ring.util.response :as response]
[ring.util.servlet :as servlet])
(:import [java.io BufferedWriter OutputStream OutputStreamWriter]
java.nio.ByteBuffer
[java.nio.channels ClosedChannelException SocketChannel]
java.nio.charset.StandardCharsets
java.util.zip.GZIPOutputStream
javax.servlet.AsyncContext
javax.servlet.http.HttpServletResponse
org.eclipse.jetty.io.EofException
org.eclipse.jetty.server.Request))
(defn- write-to-output-stream!
([^OutputStream os x]
(if (int? x)
(.write os ^int x)
(.write os ^bytes x)))
([^OutputStream os ^bytes ba ^Integer offset ^Integer len]
(.write os ba offset len)))
(defn- ex-status-code [e]
(or (some #((some-fn :status-code :status) (ex-data %))
(take-while some? (iterate ex-cause e)))
500))
(defn- format-exception [e]
(assoc (Throwable->map e) :_status (ex-status-code e)))
(defn write-error!
"Write an error to the output stream, formatting it nicely. Closes output stream afterwards."
[^OutputStream os obj]
(cond
(some #(instance? % obj)
[InterruptedException EofException])
(log/trace "Error is an InterruptedException or EofException, not writing to output stream")
(instance? Throwable obj)
(recur os (format-exception obj))
:else
(with-open [os os]
(log/trace (u/pprint-to-str (list 'write-error! obj)))
(try
(with-open [writer (BufferedWriter. (OutputStreamWriter. os StandardCharsets/UTF_8))]
(json/generate-stream obj writer))
(catch EofException _)
(catch Throwable e
(log/error e (trs "Error writing error to output stream") obj))))))
(defn- do-f* [f ^OutputStream os _finished-chan canceled-chan]
(try
(f os canceled-chan)
(catch EofException _
(a/>!! canceled-chan ::jetty-eof)
nil)
(catch InterruptedException _
(a/>!! canceled-chan ::thread-interrupted)
nil)
(catch Throwable e
(log/error e (trs "Caught unexpected Exception in streaming response body"))
(write-error! os e)
nil)))
(defn- do-f-async
"Runs `f` asynchronously on the streaming response `thread-pool`, returning immediately. When `f` finishes, completes (i.e., closes) Jetty
`async-context`."
[^AsyncContext async-context f ^OutputStream os finished-chan canceled-chan]
{:pre [(some? os)]}
(let [task (^:once fn* []
(try
(do-f* f os finished-chan canceled-chan)
(catch Throwable e
(log/error e (trs "bound-fn caught unexpected Exception"))
(a/>!! finished-chan :unexpected-error))
(finally
(a/>!! finished-chan (if (a/poll! canceled-chan)
:canceled
:completed))
(a/close! finished-chan)
(a/close! canceled-chan)
(.complete async-context))))]
(.submit (thread-pool/thread-pool) ^Runnable task)
nil))
` ring.middleware.gzip ` does n't work on our StreamingResponse class .
(defn- should-gzip-response?
"Does the client accept GZIP-encoded responses?"
[{{:strs [accept-encoding]} :headers}]
(some->> accept-encoding (re-find #"gzip|\*")))
(defn- output-stream-delay [gzip? ^HttpServletResponse response]
(if gzip?
(delay
(GZIPOutputStream. (.getOutputStream response) true))
(delay
(.getOutputStream response))))
(defn- delay-output-stream
"An OutputStream proxy that fetches the actual output stream by dereffing a delay (or other dereffable) before first
use."
[dlay]
(proxy [OutputStream] []
(close []
(.close ^OutputStream @dlay))
(flush []
(.flush ^OutputStream @dlay))
(write
([x]
(write-to-output-stream! @dlay x))
([ba offset length]
(write-to-output-stream! @dlay ba offset length)))))
(def ^:private async-cancellation-poll-interval-ms
"How often to check whether the request was canceled by the client."
1000)
(defn- canceled?
"Check whether the HTTP request has been canceled by the client.
This function attempts to read a single byte from the underlying TCP socket; if the request is canceled, `.read`
will return `-1`. Otherwise, since the entire request has already been read, `.read` *should* probably complete
immediately, returning `0`."
[^Request request]
(try
(let [^SocketChannel channel (.. request getHttpChannel getEndPoint getTransport)
buf (ByteBuffer/allocate 1)
status (.read channel buf)]
(log/tracef "Check cancelation status: .read returned %d" status)
(neg? status))
(catch InterruptedException _
false)
(catch ClosedChannelException _
true)
(catch Throwable e
(log/error e (trs "Error determining whether HTTP request was canceled"))
false)))
(def ^:private async-cancellation-poll-timeout-ms
"How long to wait for the cancelation check to complete (it should usually complete immediately -- see above -- but if
it doesn't, we don't want to block forever)."
1000)
(defn- start-async-cancel-loop!
"Starts an async loop that checks whether the client has canceled HTTP `request` at some interval. If the client has
canceled the request, this sends a message to `canceled-chan`."
[request finished-chan canceled-chan]
(a/go-loop []
(let [poll-timeout-chan (a/timeout async-cancellation-poll-interval-ms)
[_ port] (a/alts! [poll-timeout-chan finished-chan])]
(when (= port poll-timeout-chan)
(log/tracef "Checking cancelation status after waiting %s" (u/format-milliseconds async-cancellation-poll-interval-ms))
(let [canceled-status-chan (async.u/cancelable-thread (canceled? request))
status-timeout-chan (a/timeout async-cancellation-poll-timeout-ms)
[canceled? port] (a/alts! [finished-chan canceled-status-chan status-timeout-chan])]
if ` canceled - status - chan ` * was n't * the first channel to return ( i.e. , we either timed out or the request
;; was completed) then close `canceled-status-chan` which will kill the underlying thread
(a/close! canceled-status-chan)
(when (= port status-timeout-chan)
(log/debug (trs "Check cancelation status timed out after {0}"
(u/format-milliseconds async-cancellation-poll-timeout-ms))))
(when (not= port finished-chan)
(if canceled?
(a/>! canceled-chan ::request-canceled)
(recur))))))))
(defn- respond
[{:keys [^HttpServletResponse response ^AsyncContext async-context request-map response-map request]}
f {:keys [content-type status headers], :as _options} finished-chan]
(let [canceled-chan (a/promise-chan)]
(try
(.setStatus response (or status 202))
(let [gzip? (should-gzip-response? request-map)
headers (cond-> (assoc (merge headers (:headers response-map)) "Content-Type" content-type)
gzip? (assoc "Content-Encoding" "gzip"))]
(#'servlet/set-headers response headers)
(let [output-stream-delay (output-stream-delay gzip? response)
delay-os (delay-output-stream output-stream-delay)]
(start-async-cancel-loop! request finished-chan canceled-chan)
(do-f-async async-context f delay-os finished-chan canceled-chan)))
(catch Throwable e
(log/error e (trs "Unexpected exception in do-f-async"))
(try
(.sendError response 500 (.getMessage e))
(catch Throwable e
(log/error e (trs "Unexpected exception writing error response"))))
(a/>!! finished-chan :unexpected-error)
(a/close! finished-chan)
(a/close! canceled-chan)
(.complete async-context)))))
(declare render)
(p.types/deftype+ StreamingResponse [f options donechan]
pretty/PrettyPrintable
(pretty [_]
(list (pretty/qualify-symbol-for-*ns* `->StreamingResponse) f options donechan))
server.protocols/Respond
(respond [_this context]
(respond context f options donechan))
;; sync responses only (in some cases?)
compojure.response/Renderable
(render [this request]
(render this (should-gzip-response? request)))
;; async responses only
compojure.response/Sendable
(send* [this request respond* _]
(respond* (compojure.response/render this request))))
TODO -- do n't think any of this is needed any mo
(defn- render [^StreamingResponse streaming-response gzip?]
(let [{:keys [headers content-type], :as options} (.options streaming-response)]
(assoc (response/response (if gzip?
(StreamingResponse. (.f streaming-response)
(assoc options :gzip? true)
(.donechan streaming-response))
streaming-response))
:headers (cond-> (assoc headers "Content-Type" content-type)
gzip? (assoc "Content-Encoding" "gzip"))
:status 202)))
(defn finished-chan
"Fetch a promise channel that will get a message when a `StreamingResponse` is completely finished. Provided primarily
for logging purposes."
[^StreamingResponse response]
(.donechan response))
(defn streaming-response*
"Impl for `streaming-response` macro."
[f options]
(->StreamingResponse f options (a/promise-chan)))
(defmacro streaming-response
"Create an API response that streams results to an `OutputStream`.
Minimal example:
(streaming-response {:content-type \"application/json; charset=utf-8\"} [os canceled-chan]
(write-something-to-stream! os))
`f` should block until it is completely finished writing to the stream, which will be closed thereafter.
`canceled-chan` can be monitored to see if the request is canceled before results are fully written to the stream.
Current options:
* `:content-type` -- string content type to return in the results. This is required!
* `:headers` -- other headers to include in the API response."
{:style/indent 2, :arglists '([options [os-binding canceled-chan-binding] & body])}
[options [os-binding canceled-chan-binding :as bindings] & body]
{:pre [(= (count bindings) 2)]}
`(streaming-response* (bound-fn [~(vary-meta os-binding assoc :tag 'java.io.OutputStream) ~canceled-chan-binding] ~@body)
~options))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/src/metabase/async/streaming_response.clj | clojure | if the request is canceled, `.read`
was completed) then close `canceled-status-chan` which will kill the underlying thread
sync responses only (in some cases?)
async responses only | (ns metabase.async.streaming-response
(:require [cheshire.core :as json]
[clojure.core.async :as a]
[clojure.tools.logging :as log]
compojure.response
[metabase.async.streaming-response.thread-pool :as thread-pool]
[metabase.async.util :as async.u]
[metabase.server.protocols :as server.protocols]
[metabase.util :as u]
[metabase.util.i18n :refer [trs]]
[potemkin.types :as p.types]
[pretty.core :as pretty]
[ring.util.response :as response]
[ring.util.servlet :as servlet])
(:import [java.io BufferedWriter OutputStream OutputStreamWriter]
java.nio.ByteBuffer
[java.nio.channels ClosedChannelException SocketChannel]
java.nio.charset.StandardCharsets
java.util.zip.GZIPOutputStream
javax.servlet.AsyncContext
javax.servlet.http.HttpServletResponse
org.eclipse.jetty.io.EofException
org.eclipse.jetty.server.Request))
(defn- write-to-output-stream!
([^OutputStream os x]
(if (int? x)
(.write os ^int x)
(.write os ^bytes x)))
([^OutputStream os ^bytes ba ^Integer offset ^Integer len]
(.write os ba offset len)))
(defn- ex-status-code [e]
(or (some #((some-fn :status-code :status) (ex-data %))
(take-while some? (iterate ex-cause e)))
500))
(defn- format-exception [e]
(assoc (Throwable->map e) :_status (ex-status-code e)))
(defn write-error!
"Write an error to the output stream, formatting it nicely. Closes output stream afterwards."
[^OutputStream os obj]
(cond
(some #(instance? % obj)
[InterruptedException EofException])
(log/trace "Error is an InterruptedException or EofException, not writing to output stream")
(instance? Throwable obj)
(recur os (format-exception obj))
:else
(with-open [os os]
(log/trace (u/pprint-to-str (list 'write-error! obj)))
(try
(with-open [writer (BufferedWriter. (OutputStreamWriter. os StandardCharsets/UTF_8))]
(json/generate-stream obj writer))
(catch EofException _)
(catch Throwable e
(log/error e (trs "Error writing error to output stream") obj))))))
(defn- do-f* [f ^OutputStream os _finished-chan canceled-chan]
(try
(f os canceled-chan)
(catch EofException _
(a/>!! canceled-chan ::jetty-eof)
nil)
(catch InterruptedException _
(a/>!! canceled-chan ::thread-interrupted)
nil)
(catch Throwable e
(log/error e (trs "Caught unexpected Exception in streaming response body"))
(write-error! os e)
nil)))
(defn- do-f-async
"Runs `f` asynchronously on the streaming response `thread-pool`, returning immediately. When `f` finishes, completes (i.e., closes) Jetty
`async-context`."
[^AsyncContext async-context f ^OutputStream os finished-chan canceled-chan]
{:pre [(some? os)]}
(let [task (^:once fn* []
(try
(do-f* f os finished-chan canceled-chan)
(catch Throwable e
(log/error e (trs "bound-fn caught unexpected Exception"))
(a/>!! finished-chan :unexpected-error))
(finally
(a/>!! finished-chan (if (a/poll! canceled-chan)
:canceled
:completed))
(a/close! finished-chan)
(a/close! canceled-chan)
(.complete async-context))))]
(.submit (thread-pool/thread-pool) ^Runnable task)
nil))
` ring.middleware.gzip ` does n't work on our StreamingResponse class .
(defn- should-gzip-response?
"Does the client accept GZIP-encoded responses?"
[{{:strs [accept-encoding]} :headers}]
(some->> accept-encoding (re-find #"gzip|\*")))
(defn- output-stream-delay [gzip? ^HttpServletResponse response]
(if gzip?
(delay
(GZIPOutputStream. (.getOutputStream response) true))
(delay
(.getOutputStream response))))
(defn- delay-output-stream
"An OutputStream proxy that fetches the actual output stream by dereffing a delay (or other dereffable) before first
use."
[dlay]
(proxy [OutputStream] []
(close []
(.close ^OutputStream @dlay))
(flush []
(.flush ^OutputStream @dlay))
(write
([x]
(write-to-output-stream! @dlay x))
([ba offset length]
(write-to-output-stream! @dlay ba offset length)))))
(def ^:private async-cancellation-poll-interval-ms
"How often to check whether the request was canceled by the client."
1000)
(defn- canceled?
"Check whether the HTTP request has been canceled by the client.
will return `-1`. Otherwise, since the entire request has already been read, `.read` *should* probably complete
immediately, returning `0`."
[^Request request]
(try
(let [^SocketChannel channel (.. request getHttpChannel getEndPoint getTransport)
buf (ByteBuffer/allocate 1)
status (.read channel buf)]
(log/tracef "Check cancelation status: .read returned %d" status)
(neg? status))
(catch InterruptedException _
false)
(catch ClosedChannelException _
true)
(catch Throwable e
(log/error e (trs "Error determining whether HTTP request was canceled"))
false)))
(def ^:private async-cancellation-poll-timeout-ms
"How long to wait for the cancelation check to complete (it should usually complete immediately -- see above -- but if
it doesn't, we don't want to block forever)."
1000)
(defn- start-async-cancel-loop!
"Starts an async loop that checks whether the client has canceled HTTP `request` at some interval. If the client has
canceled the request, this sends a message to `canceled-chan`."
[request finished-chan canceled-chan]
(a/go-loop []
(let [poll-timeout-chan (a/timeout async-cancellation-poll-interval-ms)
[_ port] (a/alts! [poll-timeout-chan finished-chan])]
(when (= port poll-timeout-chan)
(log/tracef "Checking cancelation status after waiting %s" (u/format-milliseconds async-cancellation-poll-interval-ms))
(let [canceled-status-chan (async.u/cancelable-thread (canceled? request))
status-timeout-chan (a/timeout async-cancellation-poll-timeout-ms)
[canceled? port] (a/alts! [finished-chan canceled-status-chan status-timeout-chan])]
if ` canceled - status - chan ` * was n't * the first channel to return ( i.e. , we either timed out or the request
(a/close! canceled-status-chan)
(when (= port status-timeout-chan)
(log/debug (trs "Check cancelation status timed out after {0}"
(u/format-milliseconds async-cancellation-poll-timeout-ms))))
(when (not= port finished-chan)
(if canceled?
(a/>! canceled-chan ::request-canceled)
(recur))))))))
(defn- respond
[{:keys [^HttpServletResponse response ^AsyncContext async-context request-map response-map request]}
f {:keys [content-type status headers], :as _options} finished-chan]
(let [canceled-chan (a/promise-chan)]
(try
(.setStatus response (or status 202))
(let [gzip? (should-gzip-response? request-map)
headers (cond-> (assoc (merge headers (:headers response-map)) "Content-Type" content-type)
gzip? (assoc "Content-Encoding" "gzip"))]
(#'servlet/set-headers response headers)
(let [output-stream-delay (output-stream-delay gzip? response)
delay-os (delay-output-stream output-stream-delay)]
(start-async-cancel-loop! request finished-chan canceled-chan)
(do-f-async async-context f delay-os finished-chan canceled-chan)))
(catch Throwable e
(log/error e (trs "Unexpected exception in do-f-async"))
(try
(.sendError response 500 (.getMessage e))
(catch Throwable e
(log/error e (trs "Unexpected exception writing error response"))))
(a/>!! finished-chan :unexpected-error)
(a/close! finished-chan)
(a/close! canceled-chan)
(.complete async-context)))))
(declare render)
(p.types/deftype+ StreamingResponse [f options donechan]
pretty/PrettyPrintable
(pretty [_]
(list (pretty/qualify-symbol-for-*ns* `->StreamingResponse) f options donechan))
server.protocols/Respond
(respond [_this context]
(respond context f options donechan))
compojure.response/Renderable
(render [this request]
(render this (should-gzip-response? request)))
compojure.response/Sendable
(send* [this request respond* _]
(respond* (compojure.response/render this request))))
TODO -- do n't think any of this is needed any mo
(defn- render [^StreamingResponse streaming-response gzip?]
(let [{:keys [headers content-type], :as options} (.options streaming-response)]
(assoc (response/response (if gzip?
(StreamingResponse. (.f streaming-response)
(assoc options :gzip? true)
(.donechan streaming-response))
streaming-response))
:headers (cond-> (assoc headers "Content-Type" content-type)
gzip? (assoc "Content-Encoding" "gzip"))
:status 202)))
(defn finished-chan
"Fetch a promise channel that will get a message when a `StreamingResponse` is completely finished. Provided primarily
for logging purposes."
[^StreamingResponse response]
(.donechan response))
(defn streaming-response*
"Impl for `streaming-response` macro."
[f options]
(->StreamingResponse f options (a/promise-chan)))
(defmacro streaming-response
"Create an API response that streams results to an `OutputStream`.
Minimal example:
(streaming-response {:content-type \"application/json; charset=utf-8\"} [os canceled-chan]
(write-something-to-stream! os))
`f` should block until it is completely finished writing to the stream, which will be closed thereafter.
`canceled-chan` can be monitored to see if the request is canceled before results are fully written to the stream.
Current options:
* `:content-type` -- string content type to return in the results. This is required!
* `:headers` -- other headers to include in the API response."
{:style/indent 2, :arglists '([options [os-binding canceled-chan-binding] & body])}
[options [os-binding canceled-chan-binding :as bindings] & body]
{:pre [(= (count bindings) 2)]}
`(streaming-response* (bound-fn [~(vary-meta os-binding assoc :tag 'java.io.OutputStream) ~canceled-chan-binding] ~@body)
~options))
|
525fc14f28cfa81402509bebcf1b6a9daf812dad89385cdd921649d59ad82728 | xvw/preface | functor.ml | open QCheck2
module Suite
(R : Model.COVARIANT_1)
(F : Preface_specs.FUNCTOR with type 'a t = 'a R.t)
(A : Model.T0)
(B : Model.T0)
(C : Model.T0) =
struct
module Laws = Preface_laws.Functor.For (F)
let print pp = Format.asprintf "%a" (R.pp pp)
let functor_1 count =
let generator = R.generator A.generator in
let print = print A.pp in
Util.test ~count ~print generator Laws.functor_1 (fun lhs rhs x ->
let left = lhs x
and right = rhs x in
R.equal A.equal left right )
;;
let functor_2 count =
let generator =
let f = fun1 A.observable B.generator
and g = fun1 C.observable A.generator in
Gen.tup3 f g (R.generator C.generator)
in
let print (_, _, x) = print C.pp x in
Util.test ~count ~print generator Laws.functor_2 (fun lhs rhs (ff, gg, x) ->
let f = Fn.apply ff
and g = Fn.apply gg in
let left = lhs f g x
and right = rhs f g x in
R.equal B.equal left right )
;;
let tests ~count = [ functor_1 count; functor_2 count ]
end
| null | https://raw.githubusercontent.com/xvw/preface/84a297e1ee2967ad4341dca875da8d2dc6d7638c/lib/preface_qcheck/functor.ml | ocaml | open QCheck2
module Suite
(R : Model.COVARIANT_1)
(F : Preface_specs.FUNCTOR with type 'a t = 'a R.t)
(A : Model.T0)
(B : Model.T0)
(C : Model.T0) =
struct
module Laws = Preface_laws.Functor.For (F)
let print pp = Format.asprintf "%a" (R.pp pp)
let functor_1 count =
let generator = R.generator A.generator in
let print = print A.pp in
Util.test ~count ~print generator Laws.functor_1 (fun lhs rhs x ->
let left = lhs x
and right = rhs x in
R.equal A.equal left right )
;;
let functor_2 count =
let generator =
let f = fun1 A.observable B.generator
and g = fun1 C.observable A.generator in
Gen.tup3 f g (R.generator C.generator)
in
let print (_, _, x) = print C.pp x in
Util.test ~count ~print generator Laws.functor_2 (fun lhs rhs (ff, gg, x) ->
let f = Fn.apply ff
and g = Fn.apply gg in
let left = lhs f g x
and right = rhs f g x in
R.equal B.equal left right )
;;
let tests ~count = [ functor_1 count; functor_2 count ]
end
| |
1776a82e197a34011342f4ea1540ab13125a8ae36d22d4335e1f9f584de00355 | namin/biohacker | biotransformation.lisp |
(setq *substrate-atom-bond-graph* (adj-list 'etoh))
( ( O ( 2 1 ) ( 3 1 ) )
( H ( 1 1 ) )
( C ( 1 1 ) ( 4 1 ) )
( C ( 3 1 ) ) )
(setq *substrate-pattern* (adj-list '|Alcohols|))
( ( O ( 2 1 ) )
( R ( 1 1 ) ) )
(setq *product-template* (adj-list '|an aldehyde|))
( ( H ( 4 1 ) )
( O ( 4 2 ) )
( R ( 4 1 ) )
( C ( 1 1 ) ( 2 2 ) ( 3 1 ) ) )
(setq *product-atom-bond-graph* (adj-list 'acetald))
( ( O ( 3 2 ) )
( H ( 3 1 ) )
( C ( 2 1 ) ( 1 2 ) ( 4 1 ) )
( C ( 3 1 ) ) )
(setq *pattern-substrate-bindings* (match-substrate-pattern *substrate-atom-bond-graph* *substrate-pattern*))
( # ( HEAD 1 3 2 C H H H H H )
; (O R H))
(cpd-adj-list-structure-equal? (*product-atom-bond-graph* (adj-list 'acetald))
;
;; For efficiency and error avoidance, match-kb without match-h should followed with match-single with match-h on query results.
(defun match-substrate-pattern (substrate pattern &key (substrate-format :adj-list) (pattern-format :adj-list))
(multiple-value-bind (pattern-atom-bond-graph
substrate-atom-bond-graph
substrate-pattern-bindings
pattern-substrate-bindings
pattern-atom-list)
(match-single (hydrogenate pattern) substrate
:query-format pattern-format
:ref-format substrate-format
:match-h? t
:verbose? t
:match-charge? nil)
(if pattern-substrate-bindings
(list pattern-substrate-bindings pattern-atom-list))))
(defun make-biotransformation-rule (rule-trigger rule-template)
;; To effectively substitute the rule pattern with the template, it is only necessary to keep track of the
;; R groups, and rest can be recomputed.
(list rule-trigger rule-template))
| null | https://raw.githubusercontent.com/namin/biohacker/6b5da4c51c9caa6b5e1a68b046af171708d1af64/metabolizer/biotransformation.lisp | lisp | (O R H))
For efficiency and error avoidance, match-kb without match-h should followed with match-single with match-h on query results.
To effectively substitute the rule pattern with the template, it is only necessary to keep track of the
R groups, and rest can be recomputed. |
(setq *substrate-atom-bond-graph* (adj-list 'etoh))
( ( O ( 2 1 ) ( 3 1 ) )
( H ( 1 1 ) )
( C ( 1 1 ) ( 4 1 ) )
( C ( 3 1 ) ) )
(setq *substrate-pattern* (adj-list '|Alcohols|))
( ( O ( 2 1 ) )
( R ( 1 1 ) ) )
(setq *product-template* (adj-list '|an aldehyde|))
( ( H ( 4 1 ) )
( O ( 4 2 ) )
( R ( 4 1 ) )
( C ( 1 1 ) ( 2 2 ) ( 3 1 ) ) )
(setq *product-atom-bond-graph* (adj-list 'acetald))
( ( O ( 3 2 ) )
( H ( 3 1 ) )
( C ( 2 1 ) ( 1 2 ) ( 4 1 ) )
( C ( 3 1 ) ) )
(setq *pattern-substrate-bindings* (match-substrate-pattern *substrate-atom-bond-graph* *substrate-pattern*))
( # ( HEAD 1 3 2 C H H H H H )
(cpd-adj-list-structure-equal? (*product-atom-bond-graph* (adj-list 'acetald))
(defun match-substrate-pattern (substrate pattern &key (substrate-format :adj-list) (pattern-format :adj-list))
(multiple-value-bind (pattern-atom-bond-graph
substrate-atom-bond-graph
substrate-pattern-bindings
pattern-substrate-bindings
pattern-atom-list)
(match-single (hydrogenate pattern) substrate
:query-format pattern-format
:ref-format substrate-format
:match-h? t
:verbose? t
:match-charge? nil)
(if pattern-substrate-bindings
(list pattern-substrate-bindings pattern-atom-list))))
(defun make-biotransformation-rule (rule-trigger rule-template)
(list rule-trigger rule-template))
|
910c9c1ffe9b49ed570098ed99eae47ddf38f24987523af72c10041e910dccf4 | TrustInSoft/tis-interpreter | clabels.mli | Modified by TrustInSoft
(**************************************************************************)
(* *)
This file is part of WP plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(* -------------------------------------------------------------------------- *)
(** Normalized C-labels *)
(* -------------------------------------------------------------------------- *)
(**
Structural representation of logic labels.
Compatible with pervasives comparison and structural equality.
*)
type c_label =
| Here
| Init
| Pre
| Post
| Exit
* Label name , stmt - id .
* stmt - id
| LabelParam of string (** Logic label name in user-defined
function or predicate *)
val equal : c_label -> c_label -> bool
module T : sig type t = c_label val compare : t -> t -> int end
module LabelMap : FCMap.S with type key = c_label
module LabelSet : FCSet.S with type elt = c_label
* @return a label that represent the first point of a loop body .
val loop_head_label : Cil_types.stmt -> Cil_types.logic_label
(** create a virtual label to a statement (it can have no label) *)
val mk_logic_label : Cil_types.stmt -> Cil_types.logic_label
val mk_stmt_label : Cil_types.stmt -> c_label
val mk_loop_label : Cil_types.stmt -> c_label
val c_label : Cil_types.logic_label -> c_label
*
Assumes the logic label only comes from normalized labels .
This is the case inside [ Wp ] module , where all ACSL formula comes
from [ WpAnnot ] , which in turns always preprocess the labels
through [ NormAtLabels ] .
Assumes the logic label only comes from normalized labels.
This is the case inside [Wp] module, where all ACSL formula comes
from [WpAnnot], which in turns always preprocess the labels
through [NormAtLabels].
*)
val pretty : Format.formatter -> c_label -> unit
open Cil_types
val lookup_name : c_label -> string
val lookup : (logic_label * logic_label) list -> string -> c_label
(** [lookup bindings lparam] retrieves the actual label
for the label in [bindings] for label parameter [lparam]. *)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/wp/clabels.mli | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
--------------------------------------------------------------------------
* Normalized C-labels
--------------------------------------------------------------------------
*
Structural representation of logic labels.
Compatible with pervasives comparison and structural equality.
* Logic label name in user-defined
function or predicate
* create a virtual label to a statement (it can have no label)
* [lookup bindings lparam] retrieves the actual label
for the label in [bindings] for label parameter [lparam]. | Modified by TrustInSoft
This file is part of WP plug - in of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
type c_label =
| Here
| Init
| Pre
| Post
| Exit
* Label name , stmt - id .
* stmt - id
val equal : c_label -> c_label -> bool
module T : sig type t = c_label val compare : t -> t -> int end
module LabelMap : FCMap.S with type key = c_label
module LabelSet : FCSet.S with type elt = c_label
* @return a label that represent the first point of a loop body .
val loop_head_label : Cil_types.stmt -> Cil_types.logic_label
val mk_logic_label : Cil_types.stmt -> Cil_types.logic_label
val mk_stmt_label : Cil_types.stmt -> c_label
val mk_loop_label : Cil_types.stmt -> c_label
val c_label : Cil_types.logic_label -> c_label
*
Assumes the logic label only comes from normalized labels .
This is the case inside [ Wp ] module , where all ACSL formula comes
from [ WpAnnot ] , which in turns always preprocess the labels
through [ NormAtLabels ] .
Assumes the logic label only comes from normalized labels.
This is the case inside [Wp] module, where all ACSL formula comes
from [WpAnnot], which in turns always preprocess the labels
through [NormAtLabels].
*)
val pretty : Format.formatter -> c_label -> unit
open Cil_types
val lookup_name : c_label -> string
val lookup : (logic_label * logic_label) list -> string -> c_label
|
dea3e9cf4861150f20fd93f5ad6abba5bf6546d26707fd7433223540b2b0e130 | rlepigre/ocaml-imagelib | aflrunner.ml | let perform () =
let chunk_reader = ImageUtil_unix.chunk_reader_of_path Sys.argv.(2) in
let extension filename =
let ri =
try 1 (* the . itself *) + String.rindex filename '.'
with Not_found -> invalid_arg "filename without extension"
in
String.(sub filename ri @@ (length filename) - ri)
in
let f ~extension chunk_reader = match Sys.argv.(1) with
| "size" -> ignore @@ ImageLib.size ~extension chunk_reader
| _ -> ignore @@ ImageLib.openfile ~extension chunk_reader in
match f ~extension:(extension Sys.argv.(2)) chunk_reader with
| _ -> ()
| exception Out_of_memory -> ()
| exception End_of_file -> ()
| exception Image.Corrupted_image _ -> ()
| exception Image.Not_yet_implemented _ -> ()
let () = AflPersistent.run perform
| null | https://raw.githubusercontent.com/rlepigre/ocaml-imagelib/7adfb768533b03ad188097cb2ec92301ca35e5ad/tests/aflrunner.ml | ocaml | the . itself | let perform () =
let chunk_reader = ImageUtil_unix.chunk_reader_of_path Sys.argv.(2) in
let extension filename =
let ri =
with Not_found -> invalid_arg "filename without extension"
in
String.(sub filename ri @@ (length filename) - ri)
in
let f ~extension chunk_reader = match Sys.argv.(1) with
| "size" -> ignore @@ ImageLib.size ~extension chunk_reader
| _ -> ignore @@ ImageLib.openfile ~extension chunk_reader in
match f ~extension:(extension Sys.argv.(2)) chunk_reader with
| _ -> ()
| exception Out_of_memory -> ()
| exception End_of_file -> ()
| exception Image.Corrupted_image _ -> ()
| exception Image.Not_yet_implemented _ -> ()
let () = AflPersistent.run perform
|
85675e31db95d506ff105432a66c57fb12bad49f0a9764f866a1f99b03864a55 | slipstream/SlipStreamServer | credential_cloud.cljc | (ns com.sixsq.slipstream.ssclj.resources.spec.credential-cloud
(:require
[clojure.spec.alpha :as s]
[com.sixsq.slipstream.ssclj.resources.spec.credential :as cred]
[com.sixsq.slipstream.ssclj.resources.spec.credential-template]
[com.sixsq.slipstream.ssclj.util.spec :as su]))
(s/def ::disabledMonitoring boolean?)
(def credential-keys-spec (su/merge-keys-specs [cred/credential-keys-spec
{:opt-un [::disabledMonitoring]}]))
| null | https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/cimi/src/com/sixsq/slipstream/ssclj/resources/spec/credential_cloud.cljc | clojure | (ns com.sixsq.slipstream.ssclj.resources.spec.credential-cloud
(:require
[clojure.spec.alpha :as s]
[com.sixsq.slipstream.ssclj.resources.spec.credential :as cred]
[com.sixsq.slipstream.ssclj.resources.spec.credential-template]
[com.sixsq.slipstream.ssclj.util.spec :as su]))
(s/def ::disabledMonitoring boolean?)
(def credential-keys-spec (su/merge-keys-specs [cred/credential-keys-spec
{:opt-un [::disabledMonitoring]}]))
| |
60fd8c17a48da1361a10e69fb2b0e924e597b73e3574e10f560702e94f994ee4 | zkat/sheeple | utils.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;;
;;;; This file is part of Sheeple
;;;; utils.lisp
;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :sheeple)
(def-suite utils :in sheeple)
(in-suite sheeple)
(test ensure-list
(is (null (ensure-list nil)))
(is (equal '(1) (ensure-list 1)))
(is (equal '(1) (ensure-list '(1)))))
(test fun
(is (functionp (fun (* 2 _))))
(is (= 5 (funcall (fun (+ 3 _)) 2))))
(test collect)
(test memq)
(test maybe-weak-pointer-value)
| null | https://raw.githubusercontent.com/zkat/sheeple/5393c74737ccf22c3fd5f390076b75c38453cb04/tests/utils.lisp | lisp | -*- Mode: lisp; indent-tabs-mode: nil -*-
This file is part of Sheeple
utils.lisp
|
(in-package :sheeple)
(def-suite utils :in sheeple)
(in-suite sheeple)
(test ensure-list
(is (null (ensure-list nil)))
(is (equal '(1) (ensure-list 1)))
(is (equal '(1) (ensure-list '(1)))))
(test fun
(is (functionp (fun (* 2 _))))
(is (= 5 (funcall (fun (+ 3 _)) 2))))
(test collect)
(test memq)
(test maybe-weak-pointer-value)
|
07e696080e2e42df53a57ec58a008ab8f55c4ad41b20c49165631104ce715981 | hercules-ci/hercules-ci-agent | EffectInfo.hs | {-# LANGUAGE DeriveAnyClass #-}
module Hercules.API.Effects.EffectInfo where
import Hercules.API.Build.DerivationInfo.DerivationInput (DerivationInput)
import Hercules.API.Effects.EffectEvent (EffectEvent)
import Hercules.API.Effects.EffectReference (EffectReference)
import Hercules.API.Prelude
import Hercules.API.Projects.Job (Job)
import Hercules.API.Projects.Project (Project)
import Hercules.API.Projects.SimpleJob (SimpleJob)
data EffectStatus
= Waiting
| Running
| Failed
| DependencyFailed
| Successful
| Cancelled
deriving (Generic, Show, Eq, NFData, ToJSON, FromJSON, ToSchema)
data EffectInfo = EffectInfo
{ status :: EffectStatus,
jobId :: Id Job,
projectId :: Id Project,
platform :: Text,
requiredSystemFeatures :: [Text],
inputDerivations :: [DerivationInput],
events :: [[EffectEvent]],
waitingForEffects :: [EffectReference],
waitingForJobs :: [SimpleJob],
mayCancel :: Bool,
TODO : remove and update / fix codegen
}
deriving (Generic, Show, Eq, NFData, ToJSON, FromJSON, ToSchema)
| null | https://raw.githubusercontent.com/hercules-ci/hercules-ci-agent/9a04295f6c63d2389fb5eb1bf472b9f385e9f706/hercules-ci-api/src/Hercules/API/Effects/EffectInfo.hs | haskell | # LANGUAGE DeriveAnyClass # |
module Hercules.API.Effects.EffectInfo where
import Hercules.API.Build.DerivationInfo.DerivationInput (DerivationInput)
import Hercules.API.Effects.EffectEvent (EffectEvent)
import Hercules.API.Effects.EffectReference (EffectReference)
import Hercules.API.Prelude
import Hercules.API.Projects.Job (Job)
import Hercules.API.Projects.Project (Project)
import Hercules.API.Projects.SimpleJob (SimpleJob)
data EffectStatus
= Waiting
| Running
| Failed
| DependencyFailed
| Successful
| Cancelled
deriving (Generic, Show, Eq, NFData, ToJSON, FromJSON, ToSchema)
data EffectInfo = EffectInfo
{ status :: EffectStatus,
jobId :: Id Job,
projectId :: Id Project,
platform :: Text,
requiredSystemFeatures :: [Text],
inputDerivations :: [DerivationInput],
events :: [[EffectEvent]],
waitingForEffects :: [EffectReference],
waitingForJobs :: [SimpleJob],
mayCancel :: Bool,
TODO : remove and update / fix codegen
}
deriving (Generic, Show, Eq, NFData, ToJSON, FromJSON, ToSchema)
|
d66ecf092bb7eedd1e873792e175fcfd74a9aa88bb66332ffed014bf13cda259 | marigold-dev/deku | operation.ml | open Deku_stdlib
open Deku_crypto
open Deku_concepts
open Deku_ledger
exception Invalid_signature
exception Invalid_source
type operation =
| Operation_ticket_transfer of {
sender : Address.t;
receiver : Address.t;
ticket_id : Ticket_id.t;
amount : Amount.t;
}
| Operation_vm_transaction of {
sender : Address.t;
operation : Ocaml_wasm_vm.Operation_payload.t;
}
| Operation_withdraw of {
sender : Address.t;
owner : Deku_tezos.Address.t;
ticket_id : Ticket_id.t;
amount : Amount.t;
}
| Operation_noop of { sender : Address.t }
and t = operation [@@deriving show]
let encoding =
TODO : bench Data_encoding.union vs Data_encoding.matching
let open Data_encoding in
union ~tag_size:`Uint8
[
case ~title:"ticket_transfer" (Tag 0)
(Data_encoding.dynamic_size
(obj5
(req "type" (constant "ticket_transfer"))
(req "sender" (Data_encoding.dynamic_size Address.encoding))
(req "receiver" (Data_encoding.dynamic_size Address.encoding))
(req "ticket_id" Ticket_id.encoding)
(req "amount" Amount.encoding)))
(fun operation ->
match operation with
| Operation_ticket_transfer { sender; receiver; ticket_id; amount } ->
Some ((), sender, receiver, ticket_id, amount)
| _ -> None)
(fun ((), sender, receiver, ticket_id, amount) ->
Operation_ticket_transfer { sender; receiver; ticket_id; amount });
case ~title:"vm_transaction" (Tag 1)
(obj3
(req "type" (constant "vm_transaction"))
(req "sender" (Data_encoding.dynamic_size Address.encoding))
(req "operation" Ocaml_wasm_vm.Operation_payload.encoding))
(fun operation ->
match operation with
| Operation_vm_transaction { sender; operation } ->
Some ((), sender, operation)
| _ -> None)
(fun ((), sender, operation) ->
Operation_vm_transaction { sender; operation });
case ~title:"withdraw" (Tag 2)
(obj5
(req "type" (constant "withdraw"))
(req "sender" (Data_encoding.dynamic_size Address.encoding))
(req "ticket_id" Ticket_id.encoding)
(req "amount" Amount.encoding)
(req "owner" Deku_tezos.Address.encoding))
(fun operation ->
match operation with
| Operation_withdraw { sender; owner; ticket_id; amount } ->
Some ((), sender, ticket_id, amount, owner)
| _ -> None)
(fun ((), sender, ticket_id, amount, owner) ->
Operation_withdraw { sender; owner; ticket_id; amount });
case ~title:"noop" (Tag 3)
(obj2 (req "type" (constant "noop")) (req "sender" Address.encoding))
(fun operation ->
match operation with
| Operation_noop { sender } -> Some ((), sender)
| _ -> None)
(fun ((), sender) -> Operation_noop { sender });
]
let%expect_test "Operation encoding" =
let address =
Address.of_b58 "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE" |> Option.get
in
let tezos_address =
Deku_tezos.Address.of_string "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE"
|> Option.get
in
let contract_address =
Deku_tezos.Contract_hash.of_b58 "KT1LiabSxPyVUmVZCqHneCFLJrqQcLHkmX9d"
|> Option.get
in
let ticketer = Ticket_id.Tezos contract_address in
let ticket_id = Ticket_id.make ticketer (Bytes.of_string "hello") in
let show_op op =
let json = Data_encoding.Json.construct encoding op in
Format.printf "%a\n---------\n%!" Data_encoding.Json.pp json
in
show_op
@@ Operation_ticket_transfer
{ sender = address; receiver = address; ticket_id; amount = Amount.zero };
let operation =
let open Ocaml_wasm_vm in
let argument = Value.(Union (Left (Union (Right (Int (Z.of_int 5)))))) in
let operation = Operation.Call { address; argument } in
Operation_payload.{ operation; tickets = [ (ticket_id, Amount.zero) ] }
in
(* TODO: this one is a big ugly with nested "operation" keys. We should fix it. *)
show_op @@ Operation_vm_transaction { sender = address; operation };
show_op
@@ Operation_withdraw
{
sender = address;
owner = tezos_address;
ticket_id;
amount = Amount.zero;
};
show_op @@ Operation_noop { sender = address };
[%expect
{|
{ "type": "ticket_transfer",
"sender": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"receiver": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"ticket_id": [ "KT1LiabSxPyVUmVZCqHneCFLJrqQcLHkmX9d", "68656c6c6f" ],
"amount": "0" }
---------
{ "type": "vm_transaction", "sender": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"operation":
{ "operation":
{ "address": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"argument":
[ "Union", [ "Left", [ "Union", [ "Right", [ "Int", "5" ] ] ] ] ] },
"tickets":
[ [ [ "KT1LiabSxPyVUmVZCqHneCFLJrqQcLHkmX9d", "68656c6c6f" ], "0" ] ] } }
---------
{ "type": "withdraw", "sender": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"ticket_id": [ "KT1LiabSxPyVUmVZCqHneCFLJrqQcLHkmX9d", "68656c6c6f" ],
"amount": "0", "owner": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE" }
---------
{ "type": "noop", "sender": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE" }
--------- |}]
module Initial = struct
type initial_operation =
| Initial_operation of {
hash : Operation_hash.t;
nonce : Nonce.t;
level : Level.t;
operation : operation;
}
and t = initial_operation [@@deriving show]
type hash_repr = Nonce.t * Level.t * operation
let hash_encoding : hash_repr Data_encoding.t =
let open Data_encoding in
obj3
(req "nonce" Nonce.encoding)
(req "level" Level.encoding)
(req "operation" encoding)
let hash ~nonce ~level ~operation =
let binary =
Data_encoding.Binary.to_string_exn hash_encoding (nonce, level, operation)
in
let binary = "\x80" ^ binary in
Operation_hash.hash binary
let make ~nonce ~level ~operation =
let hash = hash ~nonce ~level ~operation in
Initial_operation { hash; nonce; level; operation }
let encoding =
let open Data_encoding in
conv
(fun (Initial_operation { hash = _; nonce; level; operation }) ->
(nonce, level, operation))
(fun (nonce, level, operation) ->
let hash = hash ~nonce ~level ~operation in
Initial_operation { hash; nonce; level; operation })
hash_encoding
let%expect_test "Initial encoding" =
let show_initial initial =
print_endline "-------";
Format.printf "Pretty: %a\n%!" pp initial;
let hex =
Data_encoding.make_lazy encoding initial
|> Data_encoding.force_bytes |> Hex.of_bytes |> Hex.show
in
Format.printf "Hex: %s\n%!" hex;
let json = Data_encoding.Json.construct encoding initial in
Format.printf "Json: %a\n%!" Data_encoding.Json.pp json
in
let nonce = Nonce.of_n N.zero in
let sender =
Address.of_b58 "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE" |> Option.get
in
let operation = Operation_noop { sender } in
let noop = make ~nonce ~level:Level.zero ~operation in
show_initial noop;
let operation =
let address =
Address.of_b58 "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE" |> Option.get
in
let contract_address =
Deku_tezos.Contract_hash.of_b58 "KT1LiabSxPyVUmVZCqHneCFLJrqQcLHkmX9d"
|> Option.get
in
let ticketer = Ticket_id.Tezos contract_address in
let ticket_id = Ticket_id.make ticketer (Bytes.of_string "hello") in
let open Ocaml_wasm_vm in
let argument = Value.(Union (Left (Union (Right (Int (Z.of_int 5)))))) in
let operation = Operation.Call { address; argument } in
let payload =
Operation_payload.{ operation; tickets = [ (ticket_id, Amount.zero) ] }
in
Operation_vm_transaction { sender = address; operation = payload }
in
(* TODO: triple-nested `operation` tags is pretty ugly. We should make it prettier. *)
let vm_operation = make ~nonce ~level:Level.zero ~operation in
show_initial vm_operation;
[%expect
{|
-------
Pretty: Operation.Initial.Initial_operation {
hash = Do2XVsHk8txd6V4YTt6io1nyJMHujD6APbhWWW64DwM3y8D5XxhF;
nonce = 0; level = 0;
operation =
Operation.Operation_noop {
sender = (Address.Implicit tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE)}}
Hex: 000000010000000001000300005d9ac49706a3566b65f1ad56dd1433e4569a0367
Json: { "nonce": "0", "level": 0,
"operation":
{ "type": "noop",
"sender": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE" } }
-------
Pretty: Operation.Initial.Initial_operation {
hash = Do2PvNgvfLPoj7WJoAMECmtPB5chhKuSbj2cmo9XF31bXRxoxheu;
nonce = 0; level = 0;
operation =
Operation.Operation_vm_transaction {
sender = (Address.Implicit tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE);
operation =
{ Operation_payload.operation =
Operation.Call {
address =
(Address.Implicit tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE);
argument =
(Value.V.Union
(Value.V.Left (Value.V.Union (Value.V.Right 5))))};
tickets = <opaque> }}}
Hex: 00000001000000000100010000001600005d9ac49706a3566b65f1ad56dd1433e4569a036700000029010000001600005d9ac49706a3566b65f1ad56dd1433e4569a036709000000090f09000000031000050000002300851badd1d782c28269474322b2662d7774545bf50000000568656c6c6f0000000100
Json: { "nonce": "0", "level": 0,
"operation":
{ "type": "vm_transaction",
"sender": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"operation":
{ "operation":
{ "address": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"argument":
[ "Union",
[ "Left", [ "Union", [ "Right", [ "Int", "5" ] ] ] ] ] },
"tickets":
[ [ [ "KT1LiabSxPyVUmVZCqHneCFLJrqQcLHkmX9d",
"68656c6c6f" ], "0" ] ] } } } |}]
let includable_operation_window = Deku_constants.includable_operation_window
let last_includable_level operation =
let (Initial_operation { level = operation_level; _ }) = operation in
let operation_level = Level.to_n operation_level in
Level.of_n N.(operation_level + includable_operation_window)
(* TODO: This seems like a weird place to put this function *)
let is_in_includable_window ~current_level ~operation_level =
let last_includable_block =
let operation_level = Level.to_n operation_level in
Level.of_n N.(operation_level + includable_operation_window)
in
(* limits for how many blocks we need to hold the operations *)
Level.(last_includable_block > current_level)
end
module Signed = struct
type signed_operation =
| Signed_operation of {
key : Key.t;
signature : Signature.t;
initial : Initial.t;
}
and t = signed_operation [@@deriving show]
let make ~identity ~initial =
let key = Identity.key identity in
let signature =
let open Initial in
let (Initial_operation { hash; _ }) = initial in
let hash = Operation_hash.to_blake2b hash in
Identity.sign ~hash identity
in
Signed_operation { key; signature; initial }
let encoding =
let open Data_encoding in
conv_with_guard
(fun (Signed_operation { key; signature; initial }) ->
((key, signature), initial))
(fun ((key, signature), initial) ->
let (Initial_operation { hash; nonce = _; level = _; operation }) =
initial
in
let sender =
match operation with
| Operation_ticket_transfer { sender; _ } -> sender
| Operation_vm_transaction { sender; _ } -> sender
| Operation_withdraw { sender; _ } -> sender
| Operation_noop { sender } -> sender
in
let sender = Address.to_key_hash sender in
let hash = Operation_hash.to_blake2b hash in
match
Option.equal Key_hash.equal (Some (Key_hash.of_key key)) sender
&& Signature.verify key signature hash
with
| true -> Ok (Signed_operation { key; signature; initial })
| false -> Error "Invalid operation signature")
(tup2 Signature.key_encoding Initial.encoding)
let make_with_signature ~key ~signature ~initial =
let (Initial.Initial_operation { hash; _ }) = initial in
match Signature.verify key signature (Operation_hash.to_blake2b hash) with
| false -> None
| true -> Some (Signed_operation { key; signature; initial })
let ticket_transfer ~identity ~nonce ~level ~receiver ~ticket_id ~amount =
let sender = Address.of_key_hash (Identity.key_hash identity) in
let operation =
Operation_ticket_transfer { sender; receiver; ticket_id; amount }
in
let initial = Initial.make ~nonce ~level ~operation in
make ~identity ~initial
let noop ~identity ~nonce ~level =
let sender = Address.of_key_hash (Identity.key_hash identity) in
let operation = Operation_noop { sender } in
let initial = Initial.make ~nonce ~level ~operation in
make ~identity ~initial
let withdraw ~identity ~nonce ~level ~tezos_owner ~ticket_id ~amount =
let sender = Address.of_key_hash (Identity.key_hash identity) in
let operation =
Operation_withdraw { sender; owner = tezos_owner; ticket_id; amount }
in
let initial = Initial.make ~nonce ~level ~operation in
make ~identity ~initial
let vm_transaction ~nonce ~level ~content ~identity =
let sender = Address.of_key_hash (Identity.key_hash identity) in
let operation = Operation_vm_transaction { sender; operation = content } in
let initial = Initial.make ~nonce ~level ~operation in
make ~identity ~initial
end
| null | https://raw.githubusercontent.com/marigold-dev/deku/58fb5377816401fcd6457519ebde6cae9332fed9/deku-p/src/core/protocol/operation.ml | ocaml | TODO: this one is a big ugly with nested "operation" keys. We should fix it.
TODO: triple-nested `operation` tags is pretty ugly. We should make it prettier.
TODO: This seems like a weird place to put this function
limits for how many blocks we need to hold the operations | open Deku_stdlib
open Deku_crypto
open Deku_concepts
open Deku_ledger
exception Invalid_signature
exception Invalid_source
type operation =
| Operation_ticket_transfer of {
sender : Address.t;
receiver : Address.t;
ticket_id : Ticket_id.t;
amount : Amount.t;
}
| Operation_vm_transaction of {
sender : Address.t;
operation : Ocaml_wasm_vm.Operation_payload.t;
}
| Operation_withdraw of {
sender : Address.t;
owner : Deku_tezos.Address.t;
ticket_id : Ticket_id.t;
amount : Amount.t;
}
| Operation_noop of { sender : Address.t }
and t = operation [@@deriving show]
let encoding =
TODO : bench Data_encoding.union vs Data_encoding.matching
let open Data_encoding in
union ~tag_size:`Uint8
[
case ~title:"ticket_transfer" (Tag 0)
(Data_encoding.dynamic_size
(obj5
(req "type" (constant "ticket_transfer"))
(req "sender" (Data_encoding.dynamic_size Address.encoding))
(req "receiver" (Data_encoding.dynamic_size Address.encoding))
(req "ticket_id" Ticket_id.encoding)
(req "amount" Amount.encoding)))
(fun operation ->
match operation with
| Operation_ticket_transfer { sender; receiver; ticket_id; amount } ->
Some ((), sender, receiver, ticket_id, amount)
| _ -> None)
(fun ((), sender, receiver, ticket_id, amount) ->
Operation_ticket_transfer { sender; receiver; ticket_id; amount });
case ~title:"vm_transaction" (Tag 1)
(obj3
(req "type" (constant "vm_transaction"))
(req "sender" (Data_encoding.dynamic_size Address.encoding))
(req "operation" Ocaml_wasm_vm.Operation_payload.encoding))
(fun operation ->
match operation with
| Operation_vm_transaction { sender; operation } ->
Some ((), sender, operation)
| _ -> None)
(fun ((), sender, operation) ->
Operation_vm_transaction { sender; operation });
case ~title:"withdraw" (Tag 2)
(obj5
(req "type" (constant "withdraw"))
(req "sender" (Data_encoding.dynamic_size Address.encoding))
(req "ticket_id" Ticket_id.encoding)
(req "amount" Amount.encoding)
(req "owner" Deku_tezos.Address.encoding))
(fun operation ->
match operation with
| Operation_withdraw { sender; owner; ticket_id; amount } ->
Some ((), sender, ticket_id, amount, owner)
| _ -> None)
(fun ((), sender, ticket_id, amount, owner) ->
Operation_withdraw { sender; owner; ticket_id; amount });
case ~title:"noop" (Tag 3)
(obj2 (req "type" (constant "noop")) (req "sender" Address.encoding))
(fun operation ->
match operation with
| Operation_noop { sender } -> Some ((), sender)
| _ -> None)
(fun ((), sender) -> Operation_noop { sender });
]
let%expect_test "Operation encoding" =
let address =
Address.of_b58 "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE" |> Option.get
in
let tezos_address =
Deku_tezos.Address.of_string "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE"
|> Option.get
in
let contract_address =
Deku_tezos.Contract_hash.of_b58 "KT1LiabSxPyVUmVZCqHneCFLJrqQcLHkmX9d"
|> Option.get
in
let ticketer = Ticket_id.Tezos contract_address in
let ticket_id = Ticket_id.make ticketer (Bytes.of_string "hello") in
let show_op op =
let json = Data_encoding.Json.construct encoding op in
Format.printf "%a\n---------\n%!" Data_encoding.Json.pp json
in
show_op
@@ Operation_ticket_transfer
{ sender = address; receiver = address; ticket_id; amount = Amount.zero };
let operation =
let open Ocaml_wasm_vm in
let argument = Value.(Union (Left (Union (Right (Int (Z.of_int 5)))))) in
let operation = Operation.Call { address; argument } in
Operation_payload.{ operation; tickets = [ (ticket_id, Amount.zero) ] }
in
show_op @@ Operation_vm_transaction { sender = address; operation };
show_op
@@ Operation_withdraw
{
sender = address;
owner = tezos_address;
ticket_id;
amount = Amount.zero;
};
show_op @@ Operation_noop { sender = address };
[%expect
{|
{ "type": "ticket_transfer",
"sender": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"receiver": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"ticket_id": [ "KT1LiabSxPyVUmVZCqHneCFLJrqQcLHkmX9d", "68656c6c6f" ],
"amount": "0" }
---------
{ "type": "vm_transaction", "sender": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"operation":
{ "operation":
{ "address": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"argument":
[ "Union", [ "Left", [ "Union", [ "Right", [ "Int", "5" ] ] ] ] ] },
"tickets":
[ [ [ "KT1LiabSxPyVUmVZCqHneCFLJrqQcLHkmX9d", "68656c6c6f" ], "0" ] ] } }
---------
{ "type": "withdraw", "sender": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"ticket_id": [ "KT1LiabSxPyVUmVZCqHneCFLJrqQcLHkmX9d", "68656c6c6f" ],
"amount": "0", "owner": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE" }
---------
{ "type": "noop", "sender": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE" }
--------- |}]
module Initial = struct
type initial_operation =
| Initial_operation of {
hash : Operation_hash.t;
nonce : Nonce.t;
level : Level.t;
operation : operation;
}
and t = initial_operation [@@deriving show]
type hash_repr = Nonce.t * Level.t * operation
let hash_encoding : hash_repr Data_encoding.t =
let open Data_encoding in
obj3
(req "nonce" Nonce.encoding)
(req "level" Level.encoding)
(req "operation" encoding)
let hash ~nonce ~level ~operation =
let binary =
Data_encoding.Binary.to_string_exn hash_encoding (nonce, level, operation)
in
let binary = "\x80" ^ binary in
Operation_hash.hash binary
let make ~nonce ~level ~operation =
let hash = hash ~nonce ~level ~operation in
Initial_operation { hash; nonce; level; operation }
let encoding =
let open Data_encoding in
conv
(fun (Initial_operation { hash = _; nonce; level; operation }) ->
(nonce, level, operation))
(fun (nonce, level, operation) ->
let hash = hash ~nonce ~level ~operation in
Initial_operation { hash; nonce; level; operation })
hash_encoding
let%expect_test "Initial encoding" =
let show_initial initial =
print_endline "-------";
Format.printf "Pretty: %a\n%!" pp initial;
let hex =
Data_encoding.make_lazy encoding initial
|> Data_encoding.force_bytes |> Hex.of_bytes |> Hex.show
in
Format.printf "Hex: %s\n%!" hex;
let json = Data_encoding.Json.construct encoding initial in
Format.printf "Json: %a\n%!" Data_encoding.Json.pp json
in
let nonce = Nonce.of_n N.zero in
let sender =
Address.of_b58 "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE" |> Option.get
in
let operation = Operation_noop { sender } in
let noop = make ~nonce ~level:Level.zero ~operation in
show_initial noop;
let operation =
let address =
Address.of_b58 "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE" |> Option.get
in
let contract_address =
Deku_tezos.Contract_hash.of_b58 "KT1LiabSxPyVUmVZCqHneCFLJrqQcLHkmX9d"
|> Option.get
in
let ticketer = Ticket_id.Tezos contract_address in
let ticket_id = Ticket_id.make ticketer (Bytes.of_string "hello") in
let open Ocaml_wasm_vm in
let argument = Value.(Union (Left (Union (Right (Int (Z.of_int 5)))))) in
let operation = Operation.Call { address; argument } in
let payload =
Operation_payload.{ operation; tickets = [ (ticket_id, Amount.zero) ] }
in
Operation_vm_transaction { sender = address; operation = payload }
in
let vm_operation = make ~nonce ~level:Level.zero ~operation in
show_initial vm_operation;
[%expect
{|
-------
Pretty: Operation.Initial.Initial_operation {
hash = Do2XVsHk8txd6V4YTt6io1nyJMHujD6APbhWWW64DwM3y8D5XxhF;
nonce = 0; level = 0;
operation =
Operation.Operation_noop {
sender = (Address.Implicit tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE)}}
Hex: 000000010000000001000300005d9ac49706a3566b65f1ad56dd1433e4569a0367
Json: { "nonce": "0", "level": 0,
"operation":
{ "type": "noop",
"sender": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE" } }
-------
Pretty: Operation.Initial.Initial_operation {
hash = Do2PvNgvfLPoj7WJoAMECmtPB5chhKuSbj2cmo9XF31bXRxoxheu;
nonce = 0; level = 0;
operation =
Operation.Operation_vm_transaction {
sender = (Address.Implicit tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE);
operation =
{ Operation_payload.operation =
Operation.Call {
address =
(Address.Implicit tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE);
argument =
(Value.V.Union
(Value.V.Left (Value.V.Union (Value.V.Right 5))))};
tickets = <opaque> }}}
Hex: 00000001000000000100010000001600005d9ac49706a3566b65f1ad56dd1433e4569a036700000029010000001600005d9ac49706a3566b65f1ad56dd1433e4569a036709000000090f09000000031000050000002300851badd1d782c28269474322b2662d7774545bf50000000568656c6c6f0000000100
Json: { "nonce": "0", "level": 0,
"operation":
{ "type": "vm_transaction",
"sender": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"operation":
{ "operation":
{ "address": "tz1UAxwRXXDvpZ5sAanbbP8tjKBoa2dxKUHE",
"argument":
[ "Union",
[ "Left", [ "Union", [ "Right", [ "Int", "5" ] ] ] ] ] },
"tickets":
[ [ [ "KT1LiabSxPyVUmVZCqHneCFLJrqQcLHkmX9d",
"68656c6c6f" ], "0" ] ] } } } |}]
let includable_operation_window = Deku_constants.includable_operation_window
let last_includable_level operation =
let (Initial_operation { level = operation_level; _ }) = operation in
let operation_level = Level.to_n operation_level in
Level.of_n N.(operation_level + includable_operation_window)
let is_in_includable_window ~current_level ~operation_level =
let last_includable_block =
let operation_level = Level.to_n operation_level in
Level.of_n N.(operation_level + includable_operation_window)
in
Level.(last_includable_block > current_level)
end
module Signed = struct
type signed_operation =
| Signed_operation of {
key : Key.t;
signature : Signature.t;
initial : Initial.t;
}
and t = signed_operation [@@deriving show]
let make ~identity ~initial =
let key = Identity.key identity in
let signature =
let open Initial in
let (Initial_operation { hash; _ }) = initial in
let hash = Operation_hash.to_blake2b hash in
Identity.sign ~hash identity
in
Signed_operation { key; signature; initial }
let encoding =
let open Data_encoding in
conv_with_guard
(fun (Signed_operation { key; signature; initial }) ->
((key, signature), initial))
(fun ((key, signature), initial) ->
let (Initial_operation { hash; nonce = _; level = _; operation }) =
initial
in
let sender =
match operation with
| Operation_ticket_transfer { sender; _ } -> sender
| Operation_vm_transaction { sender; _ } -> sender
| Operation_withdraw { sender; _ } -> sender
| Operation_noop { sender } -> sender
in
let sender = Address.to_key_hash sender in
let hash = Operation_hash.to_blake2b hash in
match
Option.equal Key_hash.equal (Some (Key_hash.of_key key)) sender
&& Signature.verify key signature hash
with
| true -> Ok (Signed_operation { key; signature; initial })
| false -> Error "Invalid operation signature")
(tup2 Signature.key_encoding Initial.encoding)
let make_with_signature ~key ~signature ~initial =
let (Initial.Initial_operation { hash; _ }) = initial in
match Signature.verify key signature (Operation_hash.to_blake2b hash) with
| false -> None
| true -> Some (Signed_operation { key; signature; initial })
let ticket_transfer ~identity ~nonce ~level ~receiver ~ticket_id ~amount =
let sender = Address.of_key_hash (Identity.key_hash identity) in
let operation =
Operation_ticket_transfer { sender; receiver; ticket_id; amount }
in
let initial = Initial.make ~nonce ~level ~operation in
make ~identity ~initial
let noop ~identity ~nonce ~level =
let sender = Address.of_key_hash (Identity.key_hash identity) in
let operation = Operation_noop { sender } in
let initial = Initial.make ~nonce ~level ~operation in
make ~identity ~initial
let withdraw ~identity ~nonce ~level ~tezos_owner ~ticket_id ~amount =
let sender = Address.of_key_hash (Identity.key_hash identity) in
let operation =
Operation_withdraw { sender; owner = tezos_owner; ticket_id; amount }
in
let initial = Initial.make ~nonce ~level ~operation in
make ~identity ~initial
let vm_transaction ~nonce ~level ~content ~identity =
let sender = Address.of_key_hash (Identity.key_hash identity) in
let operation = Operation_vm_transaction { sender; operation = content } in
let initial = Initial.make ~nonce ~level ~operation in
make ~identity ~initial
end
|
2691cf9e8685bed37b04b7267014bc0a7cf552fa63b2a9d6ed142bd45a134289 | fossas/fossa-cli | VSI.hs | module Control.Carrier.FossaApiClient.Internal.VSI (
addFilesToVsiScan,
assertRevisionBinaries,
assertUserDefinedBinaries,
completeVsiScan,
createVsiScan,
getVsiInferences,
getVsiScanAnalysisStatus,
resolveProjectDependencies,
resolveUserDefinedBinary,
) where
import App.Fossa.VSI.Fingerprint (Fingerprint, Raw)
import App.Fossa.VSI.Fingerprint qualified as Fingerprint
import App.Fossa.VSI.IAT.Types qualified as IAT
import App.Fossa.VSI.Types qualified as VSI
import App.Types (ProjectRevision)
import Control.Algebra (Has)
import Control.Carrier.FossaApiClient.Internal.FossaAPIV1 qualified as API
import Control.Effect.Diagnostics (Diagnostics)
import Control.Effect.Lift (Lift)
import Control.Effect.Reader (Reader, ask)
import Data.Map (Map)
import Fossa.API.Types (ApiOpts)
import Path (File, Path, Rel)
import Srclib.Types (Locator)
assertRevisionBinaries ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
Locator ->
[Fingerprint Raw] ->
m ()
assertRevisionBinaries meta fingerprints = do
apiOpts <- ask
API.assertRevisionBinaries apiOpts meta fingerprints
assertUserDefinedBinaries ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
IAT.UserDefinedAssertionMeta ->
[Fingerprint Raw] ->
m ()
assertUserDefinedBinaries meta fingerprints = do
apiOpts <- ask
API.assertUserDefinedBinaries apiOpts meta fingerprints
resolveUserDefinedBinary ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
IAT.UserDep ->
m IAT.UserDefinedAssertionMeta
resolveUserDefinedBinary dep = do
apiOpts <- ask
API.resolveUserDefinedBinary apiOpts dep
resolveProjectDependencies ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
VSI.Locator ->
m [VSI.Locator]
resolveProjectDependencies locator = do
apiOpts <- ask
API.resolveProjectDependencies apiOpts locator
createVsiScan ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
ProjectRevision ->
m VSI.ScanID
createVsiScan revision = do
apiOpts <- ask
API.vsiCreateScan apiOpts revision
addFilesToVsiScan ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
VSI.ScanID ->
Map (Path Rel File) Fingerprint.Combined ->
m ()
addFilesToVsiScan scanId files = do
apiOpts <- ask
API.vsiAddFilesToScan apiOpts scanId files
completeVsiScan ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
VSI.ScanID ->
m ()
completeVsiScan scanId = do
apiOpts <- ask
API.vsiCompleteScan apiOpts scanId
getVsiScanAnalysisStatus ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
VSI.ScanID ->
m VSI.AnalysisStatus
getVsiScanAnalysisStatus scanId = do
apiOpts <- ask
API.vsiScanAnalysisStatus apiOpts scanId
getVsiInferences ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
VSI.ScanID ->
m [Locator]
getVsiInferences scanId = do
apiOpts <- ask
API.vsiDownloadInferences apiOpts scanId
| null | https://raw.githubusercontent.com/fossas/fossa-cli/c8367f402a6d403fb55a3925cdb27354b5c5b190/src/Control/Carrier/FossaApiClient/Internal/VSI.hs | haskell | module Control.Carrier.FossaApiClient.Internal.VSI (
addFilesToVsiScan,
assertRevisionBinaries,
assertUserDefinedBinaries,
completeVsiScan,
createVsiScan,
getVsiInferences,
getVsiScanAnalysisStatus,
resolveProjectDependencies,
resolveUserDefinedBinary,
) where
import App.Fossa.VSI.Fingerprint (Fingerprint, Raw)
import App.Fossa.VSI.Fingerprint qualified as Fingerprint
import App.Fossa.VSI.IAT.Types qualified as IAT
import App.Fossa.VSI.Types qualified as VSI
import App.Types (ProjectRevision)
import Control.Algebra (Has)
import Control.Carrier.FossaApiClient.Internal.FossaAPIV1 qualified as API
import Control.Effect.Diagnostics (Diagnostics)
import Control.Effect.Lift (Lift)
import Control.Effect.Reader (Reader, ask)
import Data.Map (Map)
import Fossa.API.Types (ApiOpts)
import Path (File, Path, Rel)
import Srclib.Types (Locator)
assertRevisionBinaries ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
Locator ->
[Fingerprint Raw] ->
m ()
assertRevisionBinaries meta fingerprints = do
apiOpts <- ask
API.assertRevisionBinaries apiOpts meta fingerprints
assertUserDefinedBinaries ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
IAT.UserDefinedAssertionMeta ->
[Fingerprint Raw] ->
m ()
assertUserDefinedBinaries meta fingerprints = do
apiOpts <- ask
API.assertUserDefinedBinaries apiOpts meta fingerprints
resolveUserDefinedBinary ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
IAT.UserDep ->
m IAT.UserDefinedAssertionMeta
resolveUserDefinedBinary dep = do
apiOpts <- ask
API.resolveUserDefinedBinary apiOpts dep
resolveProjectDependencies ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
VSI.Locator ->
m [VSI.Locator]
resolveProjectDependencies locator = do
apiOpts <- ask
API.resolveProjectDependencies apiOpts locator
createVsiScan ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
ProjectRevision ->
m VSI.ScanID
createVsiScan revision = do
apiOpts <- ask
API.vsiCreateScan apiOpts revision
addFilesToVsiScan ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
VSI.ScanID ->
Map (Path Rel File) Fingerprint.Combined ->
m ()
addFilesToVsiScan scanId files = do
apiOpts <- ask
API.vsiAddFilesToScan apiOpts scanId files
completeVsiScan ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
VSI.ScanID ->
m ()
completeVsiScan scanId = do
apiOpts <- ask
API.vsiCompleteScan apiOpts scanId
getVsiScanAnalysisStatus ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
VSI.ScanID ->
m VSI.AnalysisStatus
getVsiScanAnalysisStatus scanId = do
apiOpts <- ask
API.vsiScanAnalysisStatus apiOpts scanId
getVsiInferences ::
( Has (Lift IO) sig m
, Has Diagnostics sig m
, Has (Reader ApiOpts) sig m
) =>
VSI.ScanID ->
m [Locator]
getVsiInferences scanId = do
apiOpts <- ask
API.vsiDownloadInferences apiOpts scanId
| |
5491039bf37563f72592f884b492402e30b71b1dc60ac2c7f7a32433d26331cc | mbutterick/aoc-racket | test.rkt | #lang reader "lang.rkt"
eedadn
drvtee
eandsr
raavrd
atevrs
tsrnev
sdttsa
rasrtv
nssdts
ntnada
svetve
tesnvt
vntsnd
vrdear
dvrsen
enarar | null | https://raw.githubusercontent.com/mbutterick/aoc-racket/2c6cb2f3ad876a91a82f33ce12844f7758b969d6/2016/day06/test.rkt | racket | #lang reader "lang.rkt"
eedadn
drvtee
eandsr
raavrd
atevrs
tsrnev
sdttsa
rasrtv
nssdts
ntnada
svetve
tesnvt
vntsnd
vrdear
dvrsen
enarar | |
309713f0654c3ec3792d92edabc09c5643e0236ea01f78648a20ac293b3be6af | csm/s4 | core.clj | (ns s4.core
(:require [cemerick.uri :as uri]
[clojure.core.async :as async]
[clojure.data.xml :as xml]
[clojure.set :as set]
[clojure.string :as string]
[clojure.tools.logging :as log]
[clojure.walk :refer [keywordize-keys]]
[konserve.core :as k]
[konserve.protocols :as kp]
[konserve.serializers :as ser]
[s4.$$$$ :as $]
[s4.auth :as auth]
[s4.sqs.queues :as queues]
[superv.async :as sv]
[s4.util :as util :refer [xml-content-type s3-xmlns]]
[clojure.spec.alpha :as s]
[clojure.data.json :as json]
[clojure.core.async.impl.protocols :as impl])
(:import [java.time ZonedDateTime ZoneId Instant]
[java.time.format DateTimeFormatter DateTimeParseException]
[java.nio ByteBuffer]
[java.security SecureRandom MessageDigest]
[java.util Base64 List UUID]
[com.google.common.io ByteStreams]
[java.io ByteArrayInputStream InputStream]
[org.fressian.handlers ReadHandler WriteHandler]
[clojure.lang PersistentTreeMap]))
(def write-handlers
"Write handlers for fressian, for durable konserve stores."
(atom {PersistentTreeMap
{"sorted-map"
(reify WriteHandler
(write [_ wtr m]
(.writeTag wtr "sorted-map" 1)
(.writeObject wtr (mapcat identity m))))}
ZonedDateTime
{"zoned-inst"
(reify WriteHandler
(write [_ wtr t]
(.writeTag wtr "zoned-inst" 2)
(.writeInt wtr (-> ^ZonedDateTime t ^Instant (.toInstant) (.toEpochMilli)))
(.writeString wtr (.getId (.getZone ^ZonedDateTime t)))))}}))
(def read-handlers
"Read handlers for fressian, for durable konserve stores."
(atom {"sorted-map"
(reify ReadHandler
(read [_ rdr tag component-count]
(let [kvs ^List (.readObject rdr)]
(PersistentTreeMap/create (seq kvs)))))
"zoned-inst"
(reify ReadHandler
(read [_ rdr tag component-count]
(let [milli (.readInt rdr)
zone-id ^String (.readObject rdr)]
(ZonedDateTime/ofInstant (Instant/ofEpochMilli milli)
(ZoneId/of zone-id)))))}))
(defn- drop-leading-slashes
[path]
(.substring path (loop [i 0]
(if (and (< i (count path))
(= \/ (.charAt path i)))
(recur (inc i))
i))))
(defn- read-bucket-object
[request hostname]
(let [host-header (get-in request [:headers "host"])]
(if (and (string/ends-with? host-header hostname)
(not= host-header hostname))
[(uri/uri-decode (.substring (get-in request [:headers "host"]) 0 (- (count host-header) (count hostname) 1)))
(uri/uri-decode (drop-leading-slashes (:uri request)))]
(vec (map uri/uri-decode (.split (drop-leading-slashes (:uri request)) "/" 2))))))
(s/def ::S3EventType #{"s3:ReducedRedundancyLostObject"
"s3:ObjectCreated:*"
"s3:ObjectCreated:Put"
"s3:ObjectCreated:Post"
"s3:ObjectCreated:Copy"
"s3:ObjectCreated:CompleteMultipartUpload"
"s3:ObjectRemoved:*"
"s3:ObjectRemoved:Delete"
"s3:ObjectRemoved:DeleteMarkerCreated"
"s3:ObjectRestore:Post"
"s3:ObjectRestore:Completed"})
(s/def :QueueConfiguration/Event (s/coll-of ::S3EventType))
(s/def ::FilterRuleName (fn [[k v]]
(and (= :Name k)
(#{"prefix" "suffix"} v))))
(s/def ::FilterRuleValue (fn [[k v]]
(and (= :Value k)
(string? v))))
(s/def ::FilterRule (fn [rule]
(when-let [[k & args] rule]
(and (= :FilterRule k)
(= 2 (count args))
(some #(s/valid? ::FilterRuleName %) args)
(some #(s/valid? ::FilterRuleValue %) args)))))
(s/def ::Filter (fn [f]
(when-let [[k & rules] f]
(and (= :S3Key k)
(every? #(s/valid? ::FilterRule %) rules)))))
(s/def :QueueConfiguration/Id string?)
(s/def :QueueConfiguration/Queue string?)
(s/def ::QueueConfiguration (s/coll-of (s/keys :req-un [:QueueConfiguration/Event
:QueueConfiguration/Queue]
:opt-un [::Filter
:QueueConfiguration/Id])))
(s/def :TopicConfiguration/Event (s/coll-of ::S3EventType))
(s/def :TopicConfiguration/Id string?)
(s/def :TopicConfiguration/Topic string?)
(s/def ::TopicConfiguration (s/coll-of (s/keys :req-un [:TopicConfiguration/Event
:TopicConfiguration/Topic]
:opt-un [::Filter
:TopicConfiguration/Id])))
(s/def :LambdaFunctionConfiguration/Event (s/coll-of ::S3EventType))
(s/def :LambdaFunctionConfiguration/Id string?)
(s/def :LambdaFunctionConfiguration/CloudFunction string?)
(s/def ::LambdaFunctionConfiguration (s/coll-of (s/keys :req-un [:LambdaFunctionConfiguration/Event
:LambdaFunctionConfiguration/CloudFunction]
:opt-un [::Filter
:LambdaFunctionConfiguration/Id])))
(s/def ::NotificationConfiguration (s/keys :opt-un [::QueueConfiguration
::TopicConfiguration
::LambdaFunctionConfiguration]))
(defn ^:no-doc element->map
([element] (element->map element
(fn [content]
(if-let [children (not-empty (filter xml/element? content))]
(map element->map children)
content))))
([element value-fn]
(when (some? element)
{(:tag element) (value-fn (:content element))})))
(defn ^:no-doc assoc-some
[m k v & kvs]
(let [m (if (some? v) (assoc m k v) m)]
(if-let [[k v & kvs] kvs]
(apply assoc-some m k v kvs)
m)))
(defn ^:no-doc element-as-sexp
[element]
(vec (concat [(:tag element)]
(some-> (:attrs element) not-empty vector)
(if (some xml/element? (:content element))
(map element-as-sexp (filter xml/element? (:content element)))
(:content element)))))
(defn ^:no-doc parse-notification-configuration
[xml]
(log/debug "parse-notification-configuration" (pr-str xml))
(if (= :NotificationConfiguration (:tag xml))
(let [config (->> (:content xml)
(filter xml/element?)
(reduce (fn [config element]
(if-let [key (#{:QueueConfiguration :TopicConfiguration :CloudFunctionConfiguration} (:tag element))]
(merge-with concat config {key [(as-> {} conf
(assoc-some conf
:Event
(->> (:content element)
(filter #(and (xml/element? %) (= :Event (:tag %))))
(mapcat :content)
not-empty))
(assoc-some conf
:Filter
(some->> (:content element)
(filter #(and (xml/element? %) (= :Filter (:tag %))))
(first)
(:content)
(filter xml/element?)
(first)
(element-as-sexp)))
(->> (:content element)
(filter #(and (xml/element? %) (#{:Id :Queue :Topic :CloudFunction} (:tag %))))
(mapcat #(vector (:tag %) (->> (:content %) (first))))
(apply assoc conf)))]})
(throw (IllegalArgumentException. "invalid notification configuration"))))
{}))
_ (log/debug "config before conform:" (pr-str config))
config (s/conform ::NotificationConfiguration config)]
(if (= ::s/invalid config)
(throw (IllegalArgumentException. "invalid notification configuration"))
config))
(throw (IllegalArgumentException. "invalid notification configuration"))))
(defn ^:no-doc bucket-put-ops
[bucket request {:keys [konserve clock sqs-server]} request-id]
(sv/go-try sv/S
(let [params (keywordize-keys (uri/query->map (:query-string request)))]
(if (empty? params)
(if-let [existing-bucket (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))]
{:status 409
:headers xml-content-type
:body [:Error
[:Code "BucketAlreadyExists"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]}
(do
(sv/<? sv/S (k/assoc-in konserve [:bucket-meta bucket] {:created (ZonedDateTime/now clock)
:object-count 0}))
(sv/<? sv/S (k/assoc-in konserve [:version-meta bucket] (sorted-map)))
{:status 200
:headers {"location" (str \/ bucket)}}))
(if-let [existing-bucket (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket]))]
(cond (some? (:versioning params))
(if-let [config (some-> (:body request) (xml/parse :namespace-aware false))]
(if (= "VersioningConfiguration" (name (:tag config)))
(if-let [new-state (#{"Enabled" "Suspended"} (some->> config
:content
(filter #(= :Status (:tag %)))
(first)
:content
(first)))]
(let [current-state (:versioning existing-bucket)]
(when (not= current-state new-state)
(sv/<? sv/S (k/assoc-in konserve [:bucket-meta bucket :versioning] new-state)))
{:status 200})
{:status 400
:headers xml-content-type
:body [:Error
[:Code "IllegalVersioningConfigurationException"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
{:status 400
:headers xml-content-type
:body [:Error
[:Code "IllegalVersioningConfigurationException"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
{:status 400
:headers xml-content-type
:body [:Error
[:Code "MissingRequestBodyError"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
(some? (:tagging params))
(if-let [config (some-> (:body request) (xml/parse :namespace-aware false))]
(if (= :Tagging (:tag config))
(let [tags (->> (:content config)
(filter #(= :TagSet (:tag %)))
first
:content
(filter #(= :Tag (:tag %)))
(map :content)
(map (fn [tags] (filter #(#{:Key :Value} (:tag %)) tags)))
(map (fn [tags] [(->> tags (filter #(= :Key (:tag %))) first :content first)
(->> tags (filter #(= :Value (:tag %))) first :content first)])))]
(sv/<? sv/S (k/assoc-in konserve [:bucket-meta bucket :tags] tags))
{:status 204}))
{:status 400
:headers xml-content-type
:body [:Error
[:Code "MissingRequestBodyError"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
(some? (:notification params))
(try
(if-let [config (some-> (:body request) (xml/parse :namespace-aware false) (parse-notification-configuration))]
(cond (or (not-empty (:TopicConfiguration config))
(not-empty (:CloudFunctionConfiguration config)))
(throw (IllegalArgumentException.))
(not-empty (:QueueConfiguration config))
(if-let [queue-metas (when (some? sqs-server)
(->> (:QueueConfiguration config)
(map #(k/get-in (-> sqs-server deref :konserve) [:queue-meta (:QueueArn %)]))
(sv/<?* sv/S)))]
(do
(sv/<? sv/S (k/assoc-in konserve [:bucket-meta bucket :notifications] (:QueueConfiguration config)))
{:status 200})
(throw (IllegalArgumentException.))))
{:status 400
:headers xml-content-type
:body [:Error
[:Code "MissingRequestBodyError"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
(catch IllegalArgumentException _
{:status 400
:headers xml-content-type
:body [:Error [:Code "InvalidArgument"] [:Resource (str \/ bucket)] [:RequestId request-id]]}))
; todo cors - too lazy to parse out the damn xml right now
:else
{:status 200
:headers xml-content-type
:body [:Error [:Code "NotImplemented"] [:Resource (str \/ bucket)] [:RequestId request-id]]})
{:status 404
:headers xml-content-type
:body [:Error [:Code "NoSuchBucket"] [:Resource (str \/ bucket)] [:RequestId request-id]]})))))
(defn ^:no-doc list-objects-v2
[bucket bucket-meta request {:keys [konserve]} request-id]
(sv/go-try sv/S
(let [{:keys [delimiter encoding-type max-keys prefix continuation-token fetch-owner start-after]
:or {max-keys "1000"}}
(keywordize-keys (uri/query->map (:query-string request)))
max-keys (Integer/parseInt max-keys)
encode-key (fn [k] (if (= "url" encoding-type) (uri/uri-encode k) k))
objects (remove nil? (map (fn [[k v]] (when-not (:deleted? (first v))
(assoc (first v) :key k)))
(sv/<? sv/S (k/get-in konserve [:version-meta bucket]))))
objects (drop-while (fn [{:keys [key]}]
(neg? (compare key (or continuation-token start-after))))
objects)
objects (if (and (some? delimiter) (some? prefix))
(filter #(string/starts-with? (:key %) prefix) objects)
objects)
common-prefixes (when (some? delimiter)
(->> objects
(map :key)
(dedupe)
(filter #(or (nil? prefix) (string/starts-with? % prefix)))
(filter #(string/includes? (subs % (some-> (or prefix "") count)) delimiter))
(map #(str prefix (subs % (some-> (or prefix "") count) (string/index-of % delimiter (some-> (or prefix "") count)))))))
truncated? (> (count objects) max-keys)
objects (take max-keys objects)
objects (if (some? delimiter)
(if (some? prefix)
(filter #(not (string/includes? (subs (:key %) (count prefix)) delimiter)) objects)
(filter #(not (string/includes? (:key %) delimiter)) objects))
objects)
response [:ListBucketResult {:xmlns s3-xmlns}
[:Name bucket]
[:Prefix prefix]
[:KeyCount (count objects)]
[:IsTruncated truncated?]
[:Delimiter delimiter]
[:MaxKeys max-keys]]
response (if truncated?
(conj response [:NextContinuationToken (:key (last objects))])
response)
response (reduce conj response
(map (fn [object]
(let [obj [:Contents
[:Key (encode-key (:key object))]
[:LastModified (.format (:created object) DateTimeFormatter/ISO_OFFSET_DATE_TIME)]
[:ETag (:etag object)]
[:Size (:content-length object)]
[:StorageClass "STANDARD"]]]
(if (= "true" fetch-owner)
(conj obj [:Owner [:ID "S4"] [:DisplayName "You Know, for Data"]])
obj)))
objects))
response (reduce conj response
(map (fn [prefix]
[:CommonPrefixes [:Prefix prefix]])
common-prefixes))]
{:status 200
:headers xml-content-type
:body response})))
(defn ^:no-doc list-versions
[bucket bucket-meta request {:keys [konserve]} request-id]
(sv/go-try sv/S
(let [{:keys [delimiter encoding-type key-marker max-keys prefix version-id-marker]
:or {max-keys "1000" key-marker "" version-id-marker ""}}
(keywordize-keys (uri/query->map (:query-string request)))
encode-key (fn [k] (if (= "uri" encoding-type)
(uri/uri-encode k)
k))
max-keys (Integer/parseInt max-keys)
versions (sv/<? sv/S (k/get-in konserve [:version-meta bucket]))
versions (mapcat (fn [[key versions]]
(let [[current & others] versions]
(cons (assoc current :key key :current? true)
(map #(assoc % :key key) others))))
versions)
versions (drop-while (fn [{:keys [key]}]
(neg? (compare key key-marker)))
versions)
versions (if (empty? version-id-marker)
versions
(let [seen? (atom false)]
(drop-while (fn [{:keys [version-id]}]
(if @seen?
false
(do
(when (= (or version-id "null") version-id-marker)
(reset! seen? true))
true)))
versions)))
versions (if (and (some? delimiter) (some? prefix))
(filter #(string/starts-with? (:key %) prefix) versions)
versions)
common-prefixes (when (some? delimiter)
(->> versions
(map :key)
(dedupe)
(filter #(or (nil? prefix) (string/starts-with? % prefix)))
(filter #(string/includes? (subs % (some-> (or prefix "") count)) delimiter))
(map #(str prefix (subs % (some-> (or prefix "") count) (string/index-of % delimiter (some-> (or prefix "") count)))))))
versions (if (some? delimiter)
(if (some? prefix)
(filter #(not (string/includes? (subs (:key %) (count prefix)) delimiter)) versions)
(filter #(not (string/includes? (:key %) delimiter)) versions))
versions)
truncated? (> (count versions) max-keys)
versions (take max-keys versions)
last-version (when truncated? (last versions))
{:keys [delete-markers versions]} (group-by (fn [{:keys [deleted?]}]
(if deleted? :delete-markers :versions))
versions)
result [:ListVersionsResult {:xmlns s3-xmlns}
[:Name bucket]
[:Prefix prefix]
[:KeyMarker key-marker]
[:VersionIdMarker version-id-marker]
[:MaxKeys max-keys]
[:IsTruncated truncated?]]
result (if truncated?
(conj result [:NextKeyMarker (:key last-version)]
[:NextVersionIdMarker (or (:version-id last-version) "null")])
result)
result (reduce conj result (map (fn [marker]
[:DeleteMarker
[:Key (encode-key (:key marker))]
[:VersionId (or (:version-id marker) "null")]
[:IsLatest (boolean (:current? marker))]
[:LastModified (.format (:created marker) DateTimeFormatter/ISO_OFFSET_DATE_TIME)]
[:Owner [:ID "S4"]]])
delete-markers))
result (reduce conj result (map (fn [version]
[:Version
[:Key (encode-key (:key version))]
[:VersionId (or (:version-id version) "null")]
[:IsLatest (boolean (:current? version))]
[:LastModified (.format (:created version) DateTimeFormatter/ISO_OFFSET_DATE_TIME)]
[:ETag (:etag version)]
[:Size (:content-length version)]
[:Owner [:ID "S4"]]
[:StorageClass "STANDARD"]])
versions))
result (reduce conj result (map (fn [prefix]
[:CommonPrefixes [:Prefix prefix]])
common-prefixes))]
{:status 200
:headers xml-content-type
:body result})))
(defn ^:no-doc list-objects
[bucket bucket-meta request system request-id]
(sv/go-try sv/S
(let [request (update request :query-string
(fn [query-string]
(let [query (uri/query->map query-string)]
(-> query
(assoc "continuation-token" (get query "marker"))
(dissoc "marker")
(assoc "fetch-owner" "true")
(uri/map->query)))))
response (:body (sv/<? sv/S (list-objects-v2 bucket bucket-meta request system request-id)))
response (vec (map (fn [element]
(cond (keyword? element) element
(map? element) element
:else (condp = (first element)
:ContinuationToken (into [:Marker] (rest element))
:NextContinuationToken (into [:NextMarker] (rest element))
element)))
response))]
{:status 200
:headers xml-content-type
:body response})))
(defn bucket-get-ops
[bucket request {:keys [konserve cost-tracker] :as system} request-id]
(sv/go-try sv/S
(let [params (keywordize-keys (uri/query->map (:query-string request)))]
(log/debug :task ::s3-handler :phase :get-bucket-request :bucket bucket :params params)
(if-let [existing-bucket (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))]
(cond
(= "2" (:list-type params))
(do
($/-track-put-request! cost-tracker)
(sv/<? sv/S (list-objects-v2 bucket existing-bucket request system request-id)))
(some? (:versions params))
(do
($/-track-put-request! cost-tracker)
(sv/<? sv/S (list-versions bucket existing-bucket request system request-id)))
(some? (:accelerate params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:AccelerateConfiguration {:xmlns s3-xmlns}
[:Status {} "Suspended"]]})
(some? (:cors params))
(let [cors (:cors existing-bucket)]
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:CORSConfiguration {}
(map (fn [{:keys [header origin method max-age expose-header]}]
[:CORSRule {}
(concat
(map (fn [header] [:AllowedHeader {} header]) header)
(map (fn [origin] [:AllowedOrigin {} origin]) origin)
(map (fn [method] [:AllowedMethod {} method]) method)
(map (fn [max-age] [:MaxAgeSeconds {} max-age]) max-age)
(map (fn [header] [:ExposeHeader {} header]) expose-header))])
cors)]})
(some? (:encryption params)) ; todo maybe support this?
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "ServerSideEncryptionConfigurationNotFoundError"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
(some? (:acl params)) ; todo maybe support this?
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:AccessControlPolicy {}
[:Owner {}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:AccessControlList {}
[:Grant
[:Grantee {"xmlns:xsi" "-instance"
"xsi:type" "CanonicalUser"}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:Permission {} "FULL_CONTROL"]]]]})
(some? (:inventory params))
(if (some? (:id params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:InventoryConfiguration {}]})
(do
($/-track-put-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:ListInventoryConfigurationsResult {:xmlns s3-xmlns}
[:IsTruncated {} "false"]]}))
(some? (:lifecycle params))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchLifecycleConfiguration"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:location params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:LocationConstraint {}]})
(some? (:publicAccessBlock params))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchPublicAccessBlockConfiguration"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:logging params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:BucketLoggingStatus {:xmlns "-03-01"}]})
(some? (:metrics params))
(if (some? (:id params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:MetricsConfiguration {:xmlns s3-xmlns}]})
(do
($/-track-put-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:ListMetricsConfigurationsResult {:xmlns s3-xmlns}
[:IsTruncated {} "false"]]}))
(some? (:notification params))
(do
($/-track-get-request! cost-tracker)
(let [configs (:notifications existing-bucket)]
(log/debug "returning configs:" (pr-str configs))
{:status 200
:headers xml-content-type
:body (into [:NotificationConfiguration {:xmlns s3-xmlns}]
(map (fn [conf]
(vec (concat [:QueueConfiguration]
(map (fn [event] [:Event event]) (:Event conf))
(some->> (:Filter conf) (vector :Filter) vector)
(some->> (:Id conf) (vector :Id) vector)
(some->> (:Queue conf) (vector :Queue) vector))))
configs))}))
(or (some? (:policyStatus params)) (some? (:policy params)))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchBucketPolicy"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
(some? (:versions params))
(do
($/-track-put-request! cost-tracker)
{:status 501
:headers xml-content-type
:body [:Error {}
[:Code {} "NotImplemented"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:replication params))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "ReplicationConfigurationNotFoundError"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:requestPayment params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:RequestPaymentConfiguration {:xmlns s3-xmlns}
[:Payer {} "BucketOwner"]]})
(some? (:tagging params))
(do
($/-track-get-request! cost-tracker)
(if-let [tags (not-empty (get existing-bucket :tags))]
{:status 200
:headers xml-content-type
:body [:Tagging {}
[:TagSet {}
(map (fn [[key value]]
[:Tag {}
[:Key {} (str key)]
[:Value {} (str value)]])
tags)]]}
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchTagSet"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]}))
(some? (:versioning params))
(do
($/-track-get-request! cost-tracker)
(let [config (get existing-bucket :versioning)]
(cond (nil? config)
{:status 200
:headers xml-content-type
:body [:VersioningConfiguration {:xmlns s3-xmlns}]}
:else
{:status 200
:headers xml-content-type
:body [:VersioningConfiguration {:xmlns s3-xmlns}
[:Status {} config]]})))
(some? (:website params))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchWebsiteConfiguration"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:analytics params))
(do
($/-track-put-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:ListBucketAnalyticsConfigurationResult {:xmlns s3-xmlns}
[:IsTruncated {} "false"]]})
(some? (:uploads params))
(do
($/-track-put-request! cost-tracker)
(let [{:keys [delimiter encoding-type max-uploads key-marker prefix upload-id-marker]
:or {max-uploads "1000" key-marker "" upload-id-marker ""}}
params
max-uploads (Integer/parseInt max-uploads)
uploads (sv/<? sv/S (k/get-in konserve [:uploads bucket]))
uploads (doall (drop-while (fn [[[key upload-id]]]
(and (not (pos? (compare key key-marker)))
(not (pos? (compare upload-id upload-id-marker)))))
uploads))
uploads (doall (if (and (some? delimiter) (some? prefix))
(filter #(string/starts-with? (first (key %)) prefix) uploads)
uploads))
common-prefixes (doall (when (some? delimiter)
(->> uploads
(map (comp first key))
(filter #(or (nil? prefix) (string/starts-with? % prefix)))
(filter #(string/includes? (subs % (some-> (or prefix "") count)) delimiter))
(map #(str prefix (subs % (some-> (or prefix "") count) (string/index-of % delimiter (some-> (or prefix "") count)))))
(set))))
uploads (doall (if (some? delimiter)
(if (some? prefix)
(filter #(not (string/includes? (subs (first (key %)) (count prefix)) delimiter)) uploads)
(filter #(not (string/includes? (first (key %)) delimiter)) uploads))
uploads))
truncated? (> (count uploads) max-uploads)
uploads (take max-uploads uploads)
result [:ListMultipartUploadsResult {:xmlns s3-xmlns}
[:Bucket {} bucket]
[:KeyMarker {} key-marker]
[:UploadIdMarker {} upload-id-marker]
[:NextKeyMarker {} (if truncated? (first (key (last uploads))) "")]
[:NextUploadIdMarker {} (if truncated? (second (key (last uploads))) "")]
[:MaxUploads {} (str max-uploads)]
[:IsTruncated {} truncated?]]
result (if encoding-type
(conj result [:EncodingType {} encoding-type])
result)
result (reduce conj result
(map (fn [[[key upload-id] {:keys [created]}]]
[:Upload {}
[:Key {} key]
[:UploadId {} upload-id]
[:Initiator {}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:Owner {}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:StorageClass {} "STANDARD"]
[:Initiated {} (.format DateTimeFormatter/ISO_OFFSET_DATE_TIME created)]])
uploads))
result (reduce conj result
(map (fn [prefix]
[:CommonPrefixes {}
[:Prefix {} prefix]])
common-prefixes))]
{:status 200
:headers xml-content-type
:body result}))
:else
(do
($/-track-put-request! cost-tracker)
(sv/<? sv/S (list-objects bucket existing-bucket request system request-id))))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchBucket"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})))))
(def ^:no-doc random (SecureRandom.))
(defn ^:no-doc generate-blob-id
[bucket object]
(let [uuid (UUID/nameUUIDFromBytes (.getBytes (pr-str [bucket object])))
b (byte-array 32)
buf (ByteBuffer/wrap b)]
(.putLong buf (.getMostSignificantBits uuid))
(.putLong buf (.getLeastSignificantBits uuid))
(.putLong buf (System/currentTimeMillis))
(.putLong buf (.nextLong random))
(.encodeToString (Base64/getEncoder) b)))
(defn ^:no-doc trigger-bucket-notification
[sqs-server notification-config notification]
(sv/go-try
sv/S
(when (some? sqs-server)
(doseq [config notification-config]
(when (or (and (= "ObjectCreated:Put" (get notification :eventName))
(some #{"s3:ObjectCreated:Put" "s3:ObjectCreated:*"} (:Event config)))
(and (= "ObjectRemoved:Delete" (get notification :eventName))
(some #{"s3:ObjectRemoved:Delete" "s3:ObjectRemoved:*"} (:Event config)))
(and (= "ObjectRemoved:DeleteMarkerCreated" (get notification :eventName))
(some #{"s3:ObjectRemoved:DeleteMarkerCreated" "s3:ObjectRemoved:*"} (:Event config)))
(every? (fn [rule]
(let [name (second (first (filter #(= :Name (first %)) (rest rule))))
value (second (first (filter #(= :Value (first %)) (rest rule))))]
(if (= "prefix" name)
(string/starts-with? (get-in notification [:s3 :key]) value)
(string/ends-with? (get-in notification [:s3 :key]) value))))
(rest (:Filter config))))
(when-let [queue-meta (sv/<? sv/S (k/get-in (-> sqs-server deref :konserve) [:queue-meta (:Queue config)]))]
(let [queues (queues/get-queue (-> sqs-server deref :queues) (:Queue config))
message-id (str (UUID/randomUUID))
body (json/write-str {:Records [(if-let [id (:Id config)]
(assoc-in notification [:s3 :configurationId] id)
notification)]})
body-md5 (util/hex (util/md5 body))]
(queues/offer! queues (queues/->Message message-id message-id body body-md5 {})
(Integer/parseInt (get-in queue-meta [:attributes :DelaySeconds]))
(Integer/parseInt (get-in queue-meta [:attributes :MessageRetentionPeriod]))))))))))
(defn ^:no-doc put-object
[bucket object request {:keys [konserve cost-tracker clock sqs-server]} request-id]
(sv/go-try sv/S
(if-let [existing-bucket (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))]
(let [blob-id (generate-blob-id bucket object)
version-id (when (= "Enabled" (:versioning existing-bucket))
blob-id)
content (some-> (:body request) (ByteStreams/toByteArray))
etag (let [md (MessageDigest/getInstance "MD5")]
(some->> content (.update md))
(->> (.digest md)
(map #(format "%02x" %))
(string/join)))
content-type (get-in request [:headers "content-type"] "binary/octet-stream")
created (ZonedDateTime/now clock)]
(when (some? content)
($/-track-data-in! cost-tracker (count content))
(if (satisfies? kp/PBinaryAsyncKeyValueStore konserve)
(sv/<? sv/S (k/bassoc konserve blob-id content))
(sv/<? sv/S (k/assoc-in konserve blob-id content))))
(sv/<? sv/S (k/update-in konserve [:version-meta bucket object]
(fn [versions]
(cons
{:blob-id blob-id
:version-id version-id
:created (ZonedDateTime/now clock)
:etag (str \" etag \")
:content-type content-type
:content-length (count content)}
(if (= "Enabled" (:versioning existing-bucket))
versions
(vec (filter #(= version-id (:version-id %)) versions)))))))
(sv/<? sv/S (trigger-bucket-notification sqs-server (:notifications existing-bucket)
{:eventVersion "2.1"
:eventSource "aws:s3"
:awsRegion "s4"
:eventTime (.format created DateTimeFormatter/ISO_OFFSET_DATE_TIME)
:eventName "ObjectCreated:Put"
:userIdentity {:principalId "S4"}
:requestParameters {:sourceIPAddress (:remote-addr request)}
:responseElements {:x-amz-request-id request-id}
:s3 {:s3SchemaVersion "1.0"
:bucket {:name bucket
:ownerIdentity {:principalId "S4"}
:arn bucket}
:object {:key object
:size (count content)
:eTag etag
:versionId (or version-id "null")
:sequencer "00"}}}))
{:status 200
:headers (as-> {"ETag" etag} h
(if (some? version-id)
(assoc h "x-amz-version-id" version-id)
h))})
{:status 404
:headers xml-content-type
:body [:Error
[:Code "NoSuchBucket"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})))
(defn ^:no-doc parse-date-header
[d]
(try
(ZonedDateTime/parse d DateTimeFormatter/RFC_1123_DATE_TIME)
(catch DateTimeParseException _
(try
(ZonedDateTime/parse d auth/RFC-1036-FORMATTER)
(catch DateTimeParseException _
(ZonedDateTime/parse d auth/ASCTIME-FORMATTER))))))
(defn ^:no-doc parse-range
[r]
(let [[begin end] (rest (re-matches #"bytes=([0-9]+)-([0-9]*)" r))]
(when (some? begin)
[(Long/parseLong begin)
(some-> (not-empty end) (Long/parseLong))])))
(defn ^:no-doc unwrap-input-stream
[value]
(log/debug :task ::unwrap-input-stream :value value)
(cond (instance? InputStream value) value
(map? value) (recur (:input-stream value))
(bytes? value) (ByteArrayInputStream. value)))
(defn ^:no-doc get-object
[bucket object request {:keys [konserve cost-tracker]} request-id with-body?]
(sv/go-try sv/S
($/-track-get-request! cost-tracker)
(if-let [existing-bucket (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))]
(if-let [versions (sv/<? sv/S (k/get-in konserve [:version-meta bucket object]))]
(let [params (keywordize-keys (uri/query->map (:query-string request)))]
(cond (some? (:acl params))
(as-> {:status 200
:headers xml-content-type} r
(if with-body?
(assoc r :body [:AccessControlPolicy
[:Owner
[:ID "S4"]
[:DisplayName "You Know, for Data"]]
[:AccessControlList
[:Grant
[:Grantee {"xmlns:xsi" "-instance"
"xsi:type" "CanonicalUser"}
[:ID "S4"]
[:DisplayName "You Know, for Data"]]
[:Permission "FULL_CONTROL"]]]])
r))
(or (some? (:legal-hold params))
(some? (:retention params))
(some? (:torrent params))
(some? (:tagging params)))
(as-> {:status 501
:headers xml-content-type} r
(if with-body?
(assoc r :body [:Error
[:Code "NotImplemented"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r))
:else
(if-let [version (let [v (if-let [version-id (:versionId params)]
(first (filter #(= version-id (:version-id %)) versions))
(first versions))]
(log/debug :task ::get-object :phase :got-version :version v)
v)]
(if (:deleted? version)
(as-> {:status 404
:headers (as-> xml-content-type h
(if (some? (:versioning existing-bucket))
(assoc h "x-amz-version-id" (or (:version-id version) "null")
"x-amz-delete-marker" "true")
h))} r
(if with-body?
(assoc r :body [:Error
[:Code "NoSuchKey"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r))
(let [if-modified-since (some-> (get-in request [:headers "if-modified-since"]) parse-date-header)
if-unmodified-since (some-> (get-in request [:headers "if-unmodified-since"]) parse-date-header)
if-match (get-in request [:headers "if-match"])
if-none-match (get-in request [:headers "if-none-match"])
content-type (or (:response-content-type params)
(:content-type version))
headers (as-> {"content-type" content-type
"last-modified" (.format DateTimeFormatter/ISO_OFFSET_DATE_TIME (:created version))
"accept-ranges" "bytes"
"content-length" (str (:content-length version))} h
(if-let [etag (:etag version)]
(assoc h "etag" etag)
h)
(if-let [v (:response-content-language params)]
(assoc h "content-language" v)
h)
(if-let [v (:response-expires params)]
(assoc h "expires" v)
h)
(if-let [v (:response-cache-control params)]
(assoc h "cache-control" v)
h)
(if-let [v (:response-content-disposition params)]
(assoc h "content-disposition" v)
h)
(if-let [v (:response-content-encoding params)]
(assoc h "content-encoding" v)
h)
(if (= "Enabled" (:versioning existing-bucket))
(assoc h "x-amz-version-id" (or (:version-id version) "null"))
h))
range (some-> (get-in request [:headers "range"]) parse-range)]
(log/debug :task ::get-object :phase :checking-object :version version
:if-modified-since if-modified-since
:if-unmodified-since if-unmodified-since
:if-match if-match
:if-none-match if-none-match)
(cond (and (some? if-modified-since)
(pos? (compare if-modified-since (:created version))))
{:status 304
:headers headers}
(and (some? if-unmodified-since)
(pos? (compare (:created version) if-unmodified-since)))
{:status 412
:headers headers}
(and (some? if-match)
(not= if-match (:etag version)))
{:status 412
:headers headers}
(and (some? if-none-match)
(= if-none-match (:etag version)))
{:status 304
:headers headers}
(and (some? range)
(or (and (some? (second range)) (> (first range) (second range)))
(> (first range) (:content-length version))
(and (some? (second range)) (> (second range) (:content-length version)))))
{:status 416
:headers headers}
(and (some? range)
(or (pos? (first range))
(and (some? (second range))
(not= (second range) (:content-length version)))))
(let [range [(first range) (or (second range) (:content-length version))]
response {:status 206
:headers (assoc headers
"content-range" (str "bytes " (first range) \- (second range) \/ (:content-length version)))}]
(if with-body?
(if (satisfies? kp/PBinaryAsyncKeyValueStore konserve)
there seems to be no consistency in what -bget returns
; memory store returns the callback's value
filestore expects a channel from the callback , takes from
; that channel, and returns that value on a new channel
; leveldb returns what the callback returns, but *within*
; a go block (so it's a channel in a channel).
(let [content (k/bget konserve (:blob-id version)
(fn [in]
(async/thread
(some-> (unwrap-input-stream in)
(ByteStreams/limit (second range))
(ByteStreams/skipFully (first range))
(ByteStreams/toByteArray)))))
content (loop [content content]
(if (satisfies? impl/ReadPort content)
(recur (sv/<? sv/S content))
content))]
($/-track-data-out! cost-tracker (- (second range) (first range)))
(assoc response :body content))
(let [content (or (sv/<? sv/S (k/get-in konserve (:blob-id version))) (byte-array 0))]
($/-track-data-out! cost-tracker (- (second range) (first range)))
(assoc response :body (ByteArrayInputStream. content (first range) (- (second range) (first range))))))
response))
:else
(let [response {:status 200
:headers headers}]
(if with-body?
(if (satisfies? kp/PBinaryAsyncKeyValueStore konserve)
(let [content (k/bget konserve (:blob-id version)
(fn [in]
(async/thread
(some-> (unwrap-input-stream in)
(ByteStreams/toByteArray)))))
content (loop [content content]
(if (satisfies? impl/ReadPort content)
(recur (sv/<? sv/S content))
content))]
($/-track-data-out! cost-tracker (:content-length version))
(assoc response :body content))
(let [content (or (sv/<? sv/S (k/get-in konserve (:blob-id version))) (byte-array 0))]
($/-track-data-out! cost-tracker (:content-length version))
(assoc response :body (ByteArrayInputStream. content))))
response)))))
(as-> {:status 404
:headers xml-content-type} r
(if with-body?
(assoc r :body [:Error
[:Code "NoSuchVersion"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r)))))
(as-> {:status 404
:headers xml-content-type} r
(if with-body?
(assoc r :body [:Error
[:Code "NoSuchKey"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r)))
(as-> {:status 404
:headers xml-content-type} r
(if with-body?
(assoc r :body [:Error
[:Code "NoSuchBucket"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r)))))
(defn ^:no-doc delete-object
[{:keys [konserve clock sqs-server]} request bucket object bucket-meta request-id]
(sv/go-try sv/S
;(log/debug :task ::delete-object :phase :begin :bucket bucket :object object)
(let [{:keys [versionId tagging]} (keywordize-keys (uri/query->map (:query-string request)))]
(if (some? tagging)
{:status 501
:headers xml-content-type
:body [:Error [:Code "NotImplemented"] [:Resource (str \/ bucket \/ object)]]}
(let [last-mod (ZonedDateTime/now clock)
[old new] (sv/<?
sv/S
(k/update-in konserve [:version-meta bucket]
(fn [objects]
(let [res (update objects object
(fn [versions]
;(log/debug :task ::delete-object :phase :updating-version :versions versions)
(if (nil? versions)
versions
(cond (some? versionId)
(remove #(= versionId (:version-id %)) versions)
(= "Enabled" (:versioning bucket-meta))
(let [version-id (generate-blob-id bucket object)]
(cons {:version-id version-id
:deleted? true
:last-modified last-mod}
versions))
(:deleted? (first versions))
versions
(and (<= (count versions) 1)
(not= "Enabled" (:versioning bucket-meta)))
nil
:else
(cons {:version-id nil
:deleted? true
:last-modified last-mod}
(remove #(nil? (:version-id %)) versions))))))]
(if (nil? (get res object))
(dissoc res object)
res)))))]
;(log/debug :task ::delete-object :phase :updated-versions :result [old new])
(if (and (nil? old) (nil? new))
{:status 204}
(do
(when-let [deleted-version (first (set/difference (set old) (set new)))]
(when-let [blob-id (:blob-id deleted-version)]
(sv/<? sv/S (k/dissoc konserve blob-id))))
(sv/<? sv/S (trigger-bucket-notification sqs-server (:notifications bucket-meta)
{:eventVersion "2.1"
:eventSource "aws:s3"
:awsRegion "s4"
:eventTime (.format last-mod DateTimeFormatter/ISO_OFFSET_DATE_TIME)
:eventName (if (some? versionId)
"ObjectRemoved:DeleteMarkerCreated"
"ObjectRemoved:Delete")
:userIdentity {:principalId "S4"}
:requestParameters {:sourceIPAddress (:remote-addr request)}
:responseElements {:x-amz-request-id request-id}
:s3 {:s3SchemaVersion "1.0"
:bucket {:name bucket
:ownerIdentity {:principalId "S4"}
:arn bucket}
:object (assoc-some {:key object
:sequencer "00"}
:versionId versionId)}}))
(cond (some? versionId)
{:status 204
:headers (as-> {"x-amz-version-id" versionId}
h
(if (some #(= versionId (:version-id %)) old)
(assoc h "x-amz-delete-marker" "true")
h))}
(not-empty (get new object))
{:status 204
:headers {"x-amz-version-id" (or (:version-id (first new)) "null")
"x-amz-delete-marker" "true"}}
:else
{:status 204
:headers (if (or (empty? old) (nil? (:versioning bucket-meta)))
{}
{"x-amz-version-id" "null"})}))))))))
(defn s3-handler
"Create an asynchronous Ring handler for the S3 API.
Keys in the argument map:
* `konserve` The konserve instance.
* `hostname` Your hostname, e.g. \"localhost\". This should match what your client sends.
* `request-id-prefix` A string to prepend to request IDs.
* `request-counter` An atom containing an int, used to generate request IDs.
* `cost-tracker` A [[s4.$$$$/ICostTracker]], for estimating costs.
* `clock` A `java.time.Clock` to use for generating timestamps."
[{:keys [konserve hostname request-id-prefix request-counter cost-tracker clock sqs-server] :as system}]
(fn [request respond error]
(async/go
(let [request-id (str request-id-prefix (format "%016x" (swap! request-counter inc)))]
(try
(log/debug :task ::s3-handler :phase :begin :request (pr-str request))
(let [respond (fn respond-wrapper
[response]
(log/debug :task ::s3-handler :phase :end :response (pr-str response))
(let [body (:body response)
body (if (and (= "application/xml" (get-in response [:headers "content-type"]))
(sequential? body))
(xml/emit-str (xml/sexp-as-element body) :encoding "UTF-8")
body)]
(respond (assoc
(assoc-in response [:headers "x-amz-request-id"] request-id)
:body body))))
[bucket object] (read-bucket-object request hostname)]
(log/debug :task ::s3-handler :bucket bucket :object object)
(case (:request-method request)
:head (cond (and (not-empty bucket)
(empty? object))
(do
($/-track-get-request! cost-tracker)
(if (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))
(respond {:status 200})
(respond {:status 404})))
(and (not-empty bucket)
(not-empty object))
(do
($/-track-get-request! cost-tracker)
(respond (sv/<? sv/S (get-object bucket object request system request-id false))))
:else
(do
($/-track-get-request! cost-tracker)
(respond {:status 200})))
:get (cond (empty? bucket)
(let [buckets (sv/<? sv/S (k/get-in konserve [:bucket-meta]))
buckets-response [:ListAllMyBucketsResult {:xmlns "-03-01"}
[:Owner {}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:Buckets {}
(map (fn [[bucket-name {:keys [created]}]]
[:Bucket {}
[:Name {} bucket-name]
[:CreationDate {} (.format DateTimeFormatter/ISO_OFFSET_DATE_TIME created)]])
buckets)]]]
($/-track-put-request! cost-tracker)
(respond {:status 200
:headers xml-content-type
:body buckets-response}))
(empty? object)
(respond (sv/<? sv/S (bucket-get-ops bucket request system request-id)))
:else
(respond (sv/<? sv/S (get-object bucket object request system request-id true))))
:put (do
($/-track-put-request! cost-tracker)
(cond (and (not-empty bucket) (empty? object))
(respond (sv/<? sv/S (bucket-put-ops bucket request system request-id)))
(and (not-empty bucket) (not-empty object))
(respond (sv/<? sv/S (put-object bucket object request system request-id)))
:else (respond {:status 501
:headers xml-content-type
:body [:Error {}
[:Code {} "NotImplemented"]
[:Resource {} (:uri request)]
[:RequestId {} request-id]]})))
:post (let [params (keywordize-keys (uri/query->map (:query-string request)))]
($/-track-put-request! cost-tracker)
(cond
(and (some? (:delete params))
(nil? object))
(if-let [bucket-meta (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket]))]
(let [objects (element-as-sexp (xml/parse (:body request) :namespace-aware false))]
(if (not= :Delete (first objects))
(respond {:status 400
:headers xml-content-type
:body [:Error
[:Code "MalformedXML"]
[:Resource (:uri request)]
[:RequestId request-id]]})
(let [quiet (= "true" (->> (rest objects)
(filter #(= :Quiet (first %)))
(first)
(second)))
results (->> (rest objects)
(filter #(= :Object (first %)))
(map #(let [object (into {} (rest %))
query {}
query (if-let [v (:VersionId object)]
(assoc query :versionId v))
request {:query-string (uri/map->query query)}]
(async/go
[object (async/<! (delete-object system request bucket (:Key object) bucket-meta request-id))])))
(sv/<?* sv/S)
(doall))]
(respond {:status 200
:headers xml-content-type
:body (into [:DeleteObjectOutput]
(->> results
(remove #(and quiet (= 200 (:status (second %)))))
(map (fn [[object result]]
(if (= 200 (:status result))
(vec (concat [:Deleted
[:Key (:Key object)]]
(some->> (:VersionId object) (vector :VersionId) (vector))
(when-let [v (get-in result [:headers "x-amz-version-id"])]
[[:DeleteMarkerVersionId v]])
(when (= "true" (get-in result [:headers "x-amz-delete-marker"]))
[[:DeleteMarker "true"]])))
(vec (concat [:Error
[:Key (:Key object)]]
(some->> (:VersionId object) (vector :VersionId) (vector))
(->> (:body result)
(rest)
(filter #(= :Code (first %)))))))))))}))))
(respond {:status 404
:headers xml-content-type
:body [:Error [:Code "NoSuchBucket"] [:Resource (:uri request)] [:RequestId request-id]]}))
:else
(respond {:status 501
:headers xml-content-type
:body [:Error {}
[:Code {} "NotImplemented"]
[:Resource {} (:uri request)]
[:RequestId {} request-id]]})))
:delete (do
($/-track-get-request! cost-tracker)
(cond (and (not-empty bucket) (empty? object))
(if-let [bucket-meta (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))]
(if (pos? (:object-count bucket-meta 0))
(respond {:status 409
:headers xml-content-type
:body [:Error {}
[:Code {} "BucketNotEmpty"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(do
(sv/<? sv/S (k/update-in konserve [:bucket-meta] #(dissoc % bucket)))
(sv/<? sv/S (k/update-in konserve [:version-meta] #(dissoc % bucket)))
(respond {:status 204})))
(respond {:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchBucket"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]}))
(and (not-empty bucket) (not-empty object))
(if-let [bucket-meta (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))]
(respond (sv/<? sv/S (delete-object system request bucket object bucket-meta request-id)))
(respond {:status 404}
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchBucket"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]))
:else (respond {:status 501
:headers xml-content-type
:body [:Error {}
[:Code {} "NotImplemented"]
[:Resource {} (:uri request)]
[:RequestId {} request-id]]})))
(do
($/-track-get-request! cost-tracker)
(respond {:status 405
:headers xml-content-type
:body [:Error {}
[:Code {} "MethodNotAllowed"]
[:Message {} (string/upper-case (name (:request-method request)))]
[:Resource {} (:uri request)]
[:RequestId {} request-id]]}))))
(catch Exception x
(log/warn x "exception in S3 handler")
(respond {:status 500
:headers xml-content-type
:body [:Error {}
[:Code {} "InternalError"]
[:Resource {} (:uri request)]
[:RequestId {} request-id]]})))))))
(defn make-handler
"Make an asynchronous, authenticated S3 ring handler.
See [[s3-handler]] and [[s4.auth/authenticating-handler]]
for what keys should be in `system`."
[system]
(auth/authenticating-handler (s3-handler system) system))
(defn make-reloadable-handler
"Create an S3 handler that will rebuild the handler functions on
every request; this way you can reload the namespace in between
calls via a REPL. System is an atom containing a system map."
[system]
(fn [request respond error]
(let [handler (s3-handler @system)
auth-handler (auth/authenticating-handler handler @system)]
(auth-handler request respond error))))
(comment
"If you want a konserve file store, do this:"
(def file-store (async/<!! (konserve.filestore/new-fs-store "foo" {:serializer (ser/fressian-serializer @read-handlers @write-handlers)})))
"You need to use the custom read/write handlers for fressian, since by default
fressian doesn't support sorted-map. This likely goes for any other
konserve implementation, but I haven't looked.") | null | https://raw.githubusercontent.com/csm/s4/a09662bbd1696ee2159545523d5def34802fcc16/src/s4/core.clj | clojure | todo cors - too lazy to parse out the damn xml right now
todo maybe support this?
todo maybe support this?
memory store returns the callback's value
that channel, and returns that value on a new channel
leveldb returns what the callback returns, but *within*
a go block (so it's a channel in a channel).
(log/debug :task ::delete-object :phase :begin :bucket bucket :object object)
(log/debug :task ::delete-object :phase :updating-version :versions versions)
(log/debug :task ::delete-object :phase :updated-versions :result [old new])
this way you can reload the namespace in between | (ns s4.core
(:require [cemerick.uri :as uri]
[clojure.core.async :as async]
[clojure.data.xml :as xml]
[clojure.set :as set]
[clojure.string :as string]
[clojure.tools.logging :as log]
[clojure.walk :refer [keywordize-keys]]
[konserve.core :as k]
[konserve.protocols :as kp]
[konserve.serializers :as ser]
[s4.$$$$ :as $]
[s4.auth :as auth]
[s4.sqs.queues :as queues]
[superv.async :as sv]
[s4.util :as util :refer [xml-content-type s3-xmlns]]
[clojure.spec.alpha :as s]
[clojure.data.json :as json]
[clojure.core.async.impl.protocols :as impl])
(:import [java.time ZonedDateTime ZoneId Instant]
[java.time.format DateTimeFormatter DateTimeParseException]
[java.nio ByteBuffer]
[java.security SecureRandom MessageDigest]
[java.util Base64 List UUID]
[com.google.common.io ByteStreams]
[java.io ByteArrayInputStream InputStream]
[org.fressian.handlers ReadHandler WriteHandler]
[clojure.lang PersistentTreeMap]))
(def write-handlers
"Write handlers for fressian, for durable konserve stores."
(atom {PersistentTreeMap
{"sorted-map"
(reify WriteHandler
(write [_ wtr m]
(.writeTag wtr "sorted-map" 1)
(.writeObject wtr (mapcat identity m))))}
ZonedDateTime
{"zoned-inst"
(reify WriteHandler
(write [_ wtr t]
(.writeTag wtr "zoned-inst" 2)
(.writeInt wtr (-> ^ZonedDateTime t ^Instant (.toInstant) (.toEpochMilli)))
(.writeString wtr (.getId (.getZone ^ZonedDateTime t)))))}}))
(def read-handlers
"Read handlers for fressian, for durable konserve stores."
(atom {"sorted-map"
(reify ReadHandler
(read [_ rdr tag component-count]
(let [kvs ^List (.readObject rdr)]
(PersistentTreeMap/create (seq kvs)))))
"zoned-inst"
(reify ReadHandler
(read [_ rdr tag component-count]
(let [milli (.readInt rdr)
zone-id ^String (.readObject rdr)]
(ZonedDateTime/ofInstant (Instant/ofEpochMilli milli)
(ZoneId/of zone-id)))))}))
(defn- drop-leading-slashes
[path]
(.substring path (loop [i 0]
(if (and (< i (count path))
(= \/ (.charAt path i)))
(recur (inc i))
i))))
(defn- read-bucket-object
[request hostname]
(let [host-header (get-in request [:headers "host"])]
(if (and (string/ends-with? host-header hostname)
(not= host-header hostname))
[(uri/uri-decode (.substring (get-in request [:headers "host"]) 0 (- (count host-header) (count hostname) 1)))
(uri/uri-decode (drop-leading-slashes (:uri request)))]
(vec (map uri/uri-decode (.split (drop-leading-slashes (:uri request)) "/" 2))))))
(s/def ::S3EventType #{"s3:ReducedRedundancyLostObject"
"s3:ObjectCreated:*"
"s3:ObjectCreated:Put"
"s3:ObjectCreated:Post"
"s3:ObjectCreated:Copy"
"s3:ObjectCreated:CompleteMultipartUpload"
"s3:ObjectRemoved:*"
"s3:ObjectRemoved:Delete"
"s3:ObjectRemoved:DeleteMarkerCreated"
"s3:ObjectRestore:Post"
"s3:ObjectRestore:Completed"})
(s/def :QueueConfiguration/Event (s/coll-of ::S3EventType))
(s/def ::FilterRuleName (fn [[k v]]
(and (= :Name k)
(#{"prefix" "suffix"} v))))
(s/def ::FilterRuleValue (fn [[k v]]
(and (= :Value k)
(string? v))))
(s/def ::FilterRule (fn [rule]
(when-let [[k & args] rule]
(and (= :FilterRule k)
(= 2 (count args))
(some #(s/valid? ::FilterRuleName %) args)
(some #(s/valid? ::FilterRuleValue %) args)))))
(s/def ::Filter (fn [f]
(when-let [[k & rules] f]
(and (= :S3Key k)
(every? #(s/valid? ::FilterRule %) rules)))))
(s/def :QueueConfiguration/Id string?)
(s/def :QueueConfiguration/Queue string?)
(s/def ::QueueConfiguration (s/coll-of (s/keys :req-un [:QueueConfiguration/Event
:QueueConfiguration/Queue]
:opt-un [::Filter
:QueueConfiguration/Id])))
(s/def :TopicConfiguration/Event (s/coll-of ::S3EventType))
(s/def :TopicConfiguration/Id string?)
(s/def :TopicConfiguration/Topic string?)
(s/def ::TopicConfiguration (s/coll-of (s/keys :req-un [:TopicConfiguration/Event
:TopicConfiguration/Topic]
:opt-un [::Filter
:TopicConfiguration/Id])))
(s/def :LambdaFunctionConfiguration/Event (s/coll-of ::S3EventType))
(s/def :LambdaFunctionConfiguration/Id string?)
(s/def :LambdaFunctionConfiguration/CloudFunction string?)
(s/def ::LambdaFunctionConfiguration (s/coll-of (s/keys :req-un [:LambdaFunctionConfiguration/Event
:LambdaFunctionConfiguration/CloudFunction]
:opt-un [::Filter
:LambdaFunctionConfiguration/Id])))
(s/def ::NotificationConfiguration (s/keys :opt-un [::QueueConfiguration
::TopicConfiguration
::LambdaFunctionConfiguration]))
(defn ^:no-doc element->map
([element] (element->map element
(fn [content]
(if-let [children (not-empty (filter xml/element? content))]
(map element->map children)
content))))
([element value-fn]
(when (some? element)
{(:tag element) (value-fn (:content element))})))
(defn ^:no-doc assoc-some
[m k v & kvs]
(let [m (if (some? v) (assoc m k v) m)]
(if-let [[k v & kvs] kvs]
(apply assoc-some m k v kvs)
m)))
(defn ^:no-doc element-as-sexp
[element]
(vec (concat [(:tag element)]
(some-> (:attrs element) not-empty vector)
(if (some xml/element? (:content element))
(map element-as-sexp (filter xml/element? (:content element)))
(:content element)))))
(defn ^:no-doc parse-notification-configuration
[xml]
(log/debug "parse-notification-configuration" (pr-str xml))
(if (= :NotificationConfiguration (:tag xml))
(let [config (->> (:content xml)
(filter xml/element?)
(reduce (fn [config element]
(if-let [key (#{:QueueConfiguration :TopicConfiguration :CloudFunctionConfiguration} (:tag element))]
(merge-with concat config {key [(as-> {} conf
(assoc-some conf
:Event
(->> (:content element)
(filter #(and (xml/element? %) (= :Event (:tag %))))
(mapcat :content)
not-empty))
(assoc-some conf
:Filter
(some->> (:content element)
(filter #(and (xml/element? %) (= :Filter (:tag %))))
(first)
(:content)
(filter xml/element?)
(first)
(element-as-sexp)))
(->> (:content element)
(filter #(and (xml/element? %) (#{:Id :Queue :Topic :CloudFunction} (:tag %))))
(mapcat #(vector (:tag %) (->> (:content %) (first))))
(apply assoc conf)))]})
(throw (IllegalArgumentException. "invalid notification configuration"))))
{}))
_ (log/debug "config before conform:" (pr-str config))
config (s/conform ::NotificationConfiguration config)]
(if (= ::s/invalid config)
(throw (IllegalArgumentException. "invalid notification configuration"))
config))
(throw (IllegalArgumentException. "invalid notification configuration"))))
(defn ^:no-doc bucket-put-ops
[bucket request {:keys [konserve clock sqs-server]} request-id]
(sv/go-try sv/S
(let [params (keywordize-keys (uri/query->map (:query-string request)))]
(if (empty? params)
(if-let [existing-bucket (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))]
{:status 409
:headers xml-content-type
:body [:Error
[:Code "BucketAlreadyExists"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]}
(do
(sv/<? sv/S (k/assoc-in konserve [:bucket-meta bucket] {:created (ZonedDateTime/now clock)
:object-count 0}))
(sv/<? sv/S (k/assoc-in konserve [:version-meta bucket] (sorted-map)))
{:status 200
:headers {"location" (str \/ bucket)}}))
(if-let [existing-bucket (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket]))]
(cond (some? (:versioning params))
(if-let [config (some-> (:body request) (xml/parse :namespace-aware false))]
(if (= "VersioningConfiguration" (name (:tag config)))
(if-let [new-state (#{"Enabled" "Suspended"} (some->> config
:content
(filter #(= :Status (:tag %)))
(first)
:content
(first)))]
(let [current-state (:versioning existing-bucket)]
(when (not= current-state new-state)
(sv/<? sv/S (k/assoc-in konserve [:bucket-meta bucket :versioning] new-state)))
{:status 200})
{:status 400
:headers xml-content-type
:body [:Error
[:Code "IllegalVersioningConfigurationException"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
{:status 400
:headers xml-content-type
:body [:Error
[:Code "IllegalVersioningConfigurationException"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
{:status 400
:headers xml-content-type
:body [:Error
[:Code "MissingRequestBodyError"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
(some? (:tagging params))
(if-let [config (some-> (:body request) (xml/parse :namespace-aware false))]
(if (= :Tagging (:tag config))
(let [tags (->> (:content config)
(filter #(= :TagSet (:tag %)))
first
:content
(filter #(= :Tag (:tag %)))
(map :content)
(map (fn [tags] (filter #(#{:Key :Value} (:tag %)) tags)))
(map (fn [tags] [(->> tags (filter #(= :Key (:tag %))) first :content first)
(->> tags (filter #(= :Value (:tag %))) first :content first)])))]
(sv/<? sv/S (k/assoc-in konserve [:bucket-meta bucket :tags] tags))
{:status 204}))
{:status 400
:headers xml-content-type
:body [:Error
[:Code "MissingRequestBodyError"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
(some? (:notification params))
(try
(if-let [config (some-> (:body request) (xml/parse :namespace-aware false) (parse-notification-configuration))]
(cond (or (not-empty (:TopicConfiguration config))
(not-empty (:CloudFunctionConfiguration config)))
(throw (IllegalArgumentException.))
(not-empty (:QueueConfiguration config))
(if-let [queue-metas (when (some? sqs-server)
(->> (:QueueConfiguration config)
(map #(k/get-in (-> sqs-server deref :konserve) [:queue-meta (:QueueArn %)]))
(sv/<?* sv/S)))]
(do
(sv/<? sv/S (k/assoc-in konserve [:bucket-meta bucket :notifications] (:QueueConfiguration config)))
{:status 200})
(throw (IllegalArgumentException.))))
{:status 400
:headers xml-content-type
:body [:Error
[:Code "MissingRequestBodyError"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
(catch IllegalArgumentException _
{:status 400
:headers xml-content-type
:body [:Error [:Code "InvalidArgument"] [:Resource (str \/ bucket)] [:RequestId request-id]]}))
:else
{:status 200
:headers xml-content-type
:body [:Error [:Code "NotImplemented"] [:Resource (str \/ bucket)] [:RequestId request-id]]})
{:status 404
:headers xml-content-type
:body [:Error [:Code "NoSuchBucket"] [:Resource (str \/ bucket)] [:RequestId request-id]]})))))
(defn ^:no-doc list-objects-v2
[bucket bucket-meta request {:keys [konserve]} request-id]
(sv/go-try sv/S
(let [{:keys [delimiter encoding-type max-keys prefix continuation-token fetch-owner start-after]
:or {max-keys "1000"}}
(keywordize-keys (uri/query->map (:query-string request)))
max-keys (Integer/parseInt max-keys)
encode-key (fn [k] (if (= "url" encoding-type) (uri/uri-encode k) k))
objects (remove nil? (map (fn [[k v]] (when-not (:deleted? (first v))
(assoc (first v) :key k)))
(sv/<? sv/S (k/get-in konserve [:version-meta bucket]))))
objects (drop-while (fn [{:keys [key]}]
(neg? (compare key (or continuation-token start-after))))
objects)
objects (if (and (some? delimiter) (some? prefix))
(filter #(string/starts-with? (:key %) prefix) objects)
objects)
common-prefixes (when (some? delimiter)
(->> objects
(map :key)
(dedupe)
(filter #(or (nil? prefix) (string/starts-with? % prefix)))
(filter #(string/includes? (subs % (some-> (or prefix "") count)) delimiter))
(map #(str prefix (subs % (some-> (or prefix "") count) (string/index-of % delimiter (some-> (or prefix "") count)))))))
truncated? (> (count objects) max-keys)
objects (take max-keys objects)
objects (if (some? delimiter)
(if (some? prefix)
(filter #(not (string/includes? (subs (:key %) (count prefix)) delimiter)) objects)
(filter #(not (string/includes? (:key %) delimiter)) objects))
objects)
response [:ListBucketResult {:xmlns s3-xmlns}
[:Name bucket]
[:Prefix prefix]
[:KeyCount (count objects)]
[:IsTruncated truncated?]
[:Delimiter delimiter]
[:MaxKeys max-keys]]
response (if truncated?
(conj response [:NextContinuationToken (:key (last objects))])
response)
response (reduce conj response
(map (fn [object]
(let [obj [:Contents
[:Key (encode-key (:key object))]
[:LastModified (.format (:created object) DateTimeFormatter/ISO_OFFSET_DATE_TIME)]
[:ETag (:etag object)]
[:Size (:content-length object)]
[:StorageClass "STANDARD"]]]
(if (= "true" fetch-owner)
(conj obj [:Owner [:ID "S4"] [:DisplayName "You Know, for Data"]])
obj)))
objects))
response (reduce conj response
(map (fn [prefix]
[:CommonPrefixes [:Prefix prefix]])
common-prefixes))]
{:status 200
:headers xml-content-type
:body response})))
(defn ^:no-doc list-versions
[bucket bucket-meta request {:keys [konserve]} request-id]
(sv/go-try sv/S
(let [{:keys [delimiter encoding-type key-marker max-keys prefix version-id-marker]
:or {max-keys "1000" key-marker "" version-id-marker ""}}
(keywordize-keys (uri/query->map (:query-string request)))
encode-key (fn [k] (if (= "uri" encoding-type)
(uri/uri-encode k)
k))
max-keys (Integer/parseInt max-keys)
versions (sv/<? sv/S (k/get-in konserve [:version-meta bucket]))
versions (mapcat (fn [[key versions]]
(let [[current & others] versions]
(cons (assoc current :key key :current? true)
(map #(assoc % :key key) others))))
versions)
versions (drop-while (fn [{:keys [key]}]
(neg? (compare key key-marker)))
versions)
versions (if (empty? version-id-marker)
versions
(let [seen? (atom false)]
(drop-while (fn [{:keys [version-id]}]
(if @seen?
false
(do
(when (= (or version-id "null") version-id-marker)
(reset! seen? true))
true)))
versions)))
versions (if (and (some? delimiter) (some? prefix))
(filter #(string/starts-with? (:key %) prefix) versions)
versions)
common-prefixes (when (some? delimiter)
(->> versions
(map :key)
(dedupe)
(filter #(or (nil? prefix) (string/starts-with? % prefix)))
(filter #(string/includes? (subs % (some-> (or prefix "") count)) delimiter))
(map #(str prefix (subs % (some-> (or prefix "") count) (string/index-of % delimiter (some-> (or prefix "") count)))))))
versions (if (some? delimiter)
(if (some? prefix)
(filter #(not (string/includes? (subs (:key %) (count prefix)) delimiter)) versions)
(filter #(not (string/includes? (:key %) delimiter)) versions))
versions)
truncated? (> (count versions) max-keys)
versions (take max-keys versions)
last-version (when truncated? (last versions))
{:keys [delete-markers versions]} (group-by (fn [{:keys [deleted?]}]
(if deleted? :delete-markers :versions))
versions)
result [:ListVersionsResult {:xmlns s3-xmlns}
[:Name bucket]
[:Prefix prefix]
[:KeyMarker key-marker]
[:VersionIdMarker version-id-marker]
[:MaxKeys max-keys]
[:IsTruncated truncated?]]
result (if truncated?
(conj result [:NextKeyMarker (:key last-version)]
[:NextVersionIdMarker (or (:version-id last-version) "null")])
result)
result (reduce conj result (map (fn [marker]
[:DeleteMarker
[:Key (encode-key (:key marker))]
[:VersionId (or (:version-id marker) "null")]
[:IsLatest (boolean (:current? marker))]
[:LastModified (.format (:created marker) DateTimeFormatter/ISO_OFFSET_DATE_TIME)]
[:Owner [:ID "S4"]]])
delete-markers))
result (reduce conj result (map (fn [version]
[:Version
[:Key (encode-key (:key version))]
[:VersionId (or (:version-id version) "null")]
[:IsLatest (boolean (:current? version))]
[:LastModified (.format (:created version) DateTimeFormatter/ISO_OFFSET_DATE_TIME)]
[:ETag (:etag version)]
[:Size (:content-length version)]
[:Owner [:ID "S4"]]
[:StorageClass "STANDARD"]])
versions))
result (reduce conj result (map (fn [prefix]
[:CommonPrefixes [:Prefix prefix]])
common-prefixes))]
{:status 200
:headers xml-content-type
:body result})))
(defn ^:no-doc list-objects
[bucket bucket-meta request system request-id]
(sv/go-try sv/S
(let [request (update request :query-string
(fn [query-string]
(let [query (uri/query->map query-string)]
(-> query
(assoc "continuation-token" (get query "marker"))
(dissoc "marker")
(assoc "fetch-owner" "true")
(uri/map->query)))))
response (:body (sv/<? sv/S (list-objects-v2 bucket bucket-meta request system request-id)))
response (vec (map (fn [element]
(cond (keyword? element) element
(map? element) element
:else (condp = (first element)
:ContinuationToken (into [:Marker] (rest element))
:NextContinuationToken (into [:NextMarker] (rest element))
element)))
response))]
{:status 200
:headers xml-content-type
:body response})))
(defn bucket-get-ops
[bucket request {:keys [konserve cost-tracker] :as system} request-id]
(sv/go-try sv/S
(let [params (keywordize-keys (uri/query->map (:query-string request)))]
(log/debug :task ::s3-handler :phase :get-bucket-request :bucket bucket :params params)
(if-let [existing-bucket (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))]
(cond
(= "2" (:list-type params))
(do
($/-track-put-request! cost-tracker)
(sv/<? sv/S (list-objects-v2 bucket existing-bucket request system request-id)))
(some? (:versions params))
(do
($/-track-put-request! cost-tracker)
(sv/<? sv/S (list-versions bucket existing-bucket request system request-id)))
(some? (:accelerate params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:AccelerateConfiguration {:xmlns s3-xmlns}
[:Status {} "Suspended"]]})
(some? (:cors params))
(let [cors (:cors existing-bucket)]
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:CORSConfiguration {}
(map (fn [{:keys [header origin method max-age expose-header]}]
[:CORSRule {}
(concat
(map (fn [header] [:AllowedHeader {} header]) header)
(map (fn [origin] [:AllowedOrigin {} origin]) origin)
(map (fn [method] [:AllowedMethod {} method]) method)
(map (fn [max-age] [:MaxAgeSeconds {} max-age]) max-age)
(map (fn [header] [:ExposeHeader {} header]) expose-header))])
cors)]})
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "ServerSideEncryptionConfigurationNotFoundError"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:AccessControlPolicy {}
[:Owner {}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:AccessControlList {}
[:Grant
[:Grantee {"xmlns:xsi" "-instance"
"xsi:type" "CanonicalUser"}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:Permission {} "FULL_CONTROL"]]]]})
(some? (:inventory params))
(if (some? (:id params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:InventoryConfiguration {}]})
(do
($/-track-put-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:ListInventoryConfigurationsResult {:xmlns s3-xmlns}
[:IsTruncated {} "false"]]}))
(some? (:lifecycle params))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchLifecycleConfiguration"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:location params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:LocationConstraint {}]})
(some? (:publicAccessBlock params))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchPublicAccessBlockConfiguration"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:logging params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:BucketLoggingStatus {:xmlns "-03-01"}]})
(some? (:metrics params))
(if (some? (:id params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:MetricsConfiguration {:xmlns s3-xmlns}]})
(do
($/-track-put-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:ListMetricsConfigurationsResult {:xmlns s3-xmlns}
[:IsTruncated {} "false"]]}))
(some? (:notification params))
(do
($/-track-get-request! cost-tracker)
(let [configs (:notifications existing-bucket)]
(log/debug "returning configs:" (pr-str configs))
{:status 200
:headers xml-content-type
:body (into [:NotificationConfiguration {:xmlns s3-xmlns}]
(map (fn [conf]
(vec (concat [:QueueConfiguration]
(map (fn [event] [:Event event]) (:Event conf))
(some->> (:Filter conf) (vector :Filter) vector)
(some->> (:Id conf) (vector :Id) vector)
(some->> (:Queue conf) (vector :Queue) vector))))
configs))}))
(or (some? (:policyStatus params)) (some? (:policy params)))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchBucketPolicy"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})
(some? (:versions params))
(do
($/-track-put-request! cost-tracker)
{:status 501
:headers xml-content-type
:body [:Error {}
[:Code {} "NotImplemented"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:replication params))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "ReplicationConfigurationNotFoundError"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:requestPayment params))
(do
($/-track-get-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:RequestPaymentConfiguration {:xmlns s3-xmlns}
[:Payer {} "BucketOwner"]]})
(some? (:tagging params))
(do
($/-track-get-request! cost-tracker)
(if-let [tags (not-empty (get existing-bucket :tags))]
{:status 200
:headers xml-content-type
:body [:Tagging {}
[:TagSet {}
(map (fn [[key value]]
[:Tag {}
[:Key {} (str key)]
[:Value {} (str value)]])
tags)]]}
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchTagSet"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]}))
(some? (:versioning params))
(do
($/-track-get-request! cost-tracker)
(let [config (get existing-bucket :versioning)]
(cond (nil? config)
{:status 200
:headers xml-content-type
:body [:VersioningConfiguration {:xmlns s3-xmlns}]}
:else
{:status 200
:headers xml-content-type
:body [:VersioningConfiguration {:xmlns s3-xmlns}
[:Status {} config]]})))
(some? (:website params))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchWebsiteConfiguration"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(some? (:analytics params))
(do
($/-track-put-request! cost-tracker)
{:status 200
:headers xml-content-type
:body [:ListBucketAnalyticsConfigurationResult {:xmlns s3-xmlns}
[:IsTruncated {} "false"]]})
(some? (:uploads params))
(do
($/-track-put-request! cost-tracker)
(let [{:keys [delimiter encoding-type max-uploads key-marker prefix upload-id-marker]
:or {max-uploads "1000" key-marker "" upload-id-marker ""}}
params
max-uploads (Integer/parseInt max-uploads)
uploads (sv/<? sv/S (k/get-in konserve [:uploads bucket]))
uploads (doall (drop-while (fn [[[key upload-id]]]
(and (not (pos? (compare key key-marker)))
(not (pos? (compare upload-id upload-id-marker)))))
uploads))
uploads (doall (if (and (some? delimiter) (some? prefix))
(filter #(string/starts-with? (first (key %)) prefix) uploads)
uploads))
common-prefixes (doall (when (some? delimiter)
(->> uploads
(map (comp first key))
(filter #(or (nil? prefix) (string/starts-with? % prefix)))
(filter #(string/includes? (subs % (some-> (or prefix "") count)) delimiter))
(map #(str prefix (subs % (some-> (or prefix "") count) (string/index-of % delimiter (some-> (or prefix "") count)))))
(set))))
uploads (doall (if (some? delimiter)
(if (some? prefix)
(filter #(not (string/includes? (subs (first (key %)) (count prefix)) delimiter)) uploads)
(filter #(not (string/includes? (first (key %)) delimiter)) uploads))
uploads))
truncated? (> (count uploads) max-uploads)
uploads (take max-uploads uploads)
result [:ListMultipartUploadsResult {:xmlns s3-xmlns}
[:Bucket {} bucket]
[:KeyMarker {} key-marker]
[:UploadIdMarker {} upload-id-marker]
[:NextKeyMarker {} (if truncated? (first (key (last uploads))) "")]
[:NextUploadIdMarker {} (if truncated? (second (key (last uploads))) "")]
[:MaxUploads {} (str max-uploads)]
[:IsTruncated {} truncated?]]
result (if encoding-type
(conj result [:EncodingType {} encoding-type])
result)
result (reduce conj result
(map (fn [[[key upload-id] {:keys [created]}]]
[:Upload {}
[:Key {} key]
[:UploadId {} upload-id]
[:Initiator {}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:Owner {}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:StorageClass {} "STANDARD"]
[:Initiated {} (.format DateTimeFormatter/ISO_OFFSET_DATE_TIME created)]])
uploads))
result (reduce conj result
(map (fn [prefix]
[:CommonPrefixes {}
[:Prefix {} prefix]])
common-prefixes))]
{:status 200
:headers xml-content-type
:body result}))
:else
(do
($/-track-put-request! cost-tracker)
(sv/<? sv/S (list-objects bucket existing-bucket request system request-id))))
(do
($/-track-get-request! cost-tracker)
{:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchBucket"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})))))
(def ^:no-doc random (SecureRandom.))
(defn ^:no-doc generate-blob-id
[bucket object]
(let [uuid (UUID/nameUUIDFromBytes (.getBytes (pr-str [bucket object])))
b (byte-array 32)
buf (ByteBuffer/wrap b)]
(.putLong buf (.getMostSignificantBits uuid))
(.putLong buf (.getLeastSignificantBits uuid))
(.putLong buf (System/currentTimeMillis))
(.putLong buf (.nextLong random))
(.encodeToString (Base64/getEncoder) b)))
(defn ^:no-doc trigger-bucket-notification
[sqs-server notification-config notification]
(sv/go-try
sv/S
(when (some? sqs-server)
(doseq [config notification-config]
(when (or (and (= "ObjectCreated:Put" (get notification :eventName))
(some #{"s3:ObjectCreated:Put" "s3:ObjectCreated:*"} (:Event config)))
(and (= "ObjectRemoved:Delete" (get notification :eventName))
(some #{"s3:ObjectRemoved:Delete" "s3:ObjectRemoved:*"} (:Event config)))
(and (= "ObjectRemoved:DeleteMarkerCreated" (get notification :eventName))
(some #{"s3:ObjectRemoved:DeleteMarkerCreated" "s3:ObjectRemoved:*"} (:Event config)))
(every? (fn [rule]
(let [name (second (first (filter #(= :Name (first %)) (rest rule))))
value (second (first (filter #(= :Value (first %)) (rest rule))))]
(if (= "prefix" name)
(string/starts-with? (get-in notification [:s3 :key]) value)
(string/ends-with? (get-in notification [:s3 :key]) value))))
(rest (:Filter config))))
(when-let [queue-meta (sv/<? sv/S (k/get-in (-> sqs-server deref :konserve) [:queue-meta (:Queue config)]))]
(let [queues (queues/get-queue (-> sqs-server deref :queues) (:Queue config))
message-id (str (UUID/randomUUID))
body (json/write-str {:Records [(if-let [id (:Id config)]
(assoc-in notification [:s3 :configurationId] id)
notification)]})
body-md5 (util/hex (util/md5 body))]
(queues/offer! queues (queues/->Message message-id message-id body body-md5 {})
(Integer/parseInt (get-in queue-meta [:attributes :DelaySeconds]))
(Integer/parseInt (get-in queue-meta [:attributes :MessageRetentionPeriod]))))))))))
(defn ^:no-doc put-object
[bucket object request {:keys [konserve cost-tracker clock sqs-server]} request-id]
(sv/go-try sv/S
(if-let [existing-bucket (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))]
(let [blob-id (generate-blob-id bucket object)
version-id (when (= "Enabled" (:versioning existing-bucket))
blob-id)
content (some-> (:body request) (ByteStreams/toByteArray))
etag (let [md (MessageDigest/getInstance "MD5")]
(some->> content (.update md))
(->> (.digest md)
(map #(format "%02x" %))
(string/join)))
content-type (get-in request [:headers "content-type"] "binary/octet-stream")
created (ZonedDateTime/now clock)]
(when (some? content)
($/-track-data-in! cost-tracker (count content))
(if (satisfies? kp/PBinaryAsyncKeyValueStore konserve)
(sv/<? sv/S (k/bassoc konserve blob-id content))
(sv/<? sv/S (k/assoc-in konserve blob-id content))))
(sv/<? sv/S (k/update-in konserve [:version-meta bucket object]
(fn [versions]
(cons
{:blob-id blob-id
:version-id version-id
:created (ZonedDateTime/now clock)
:etag (str \" etag \")
:content-type content-type
:content-length (count content)}
(if (= "Enabled" (:versioning existing-bucket))
versions
(vec (filter #(= version-id (:version-id %)) versions)))))))
(sv/<? sv/S (trigger-bucket-notification sqs-server (:notifications existing-bucket)
{:eventVersion "2.1"
:eventSource "aws:s3"
:awsRegion "s4"
:eventTime (.format created DateTimeFormatter/ISO_OFFSET_DATE_TIME)
:eventName "ObjectCreated:Put"
:userIdentity {:principalId "S4"}
:requestParameters {:sourceIPAddress (:remote-addr request)}
:responseElements {:x-amz-request-id request-id}
:s3 {:s3SchemaVersion "1.0"
:bucket {:name bucket
:ownerIdentity {:principalId "S4"}
:arn bucket}
:object {:key object
:size (count content)
:eTag etag
:versionId (or version-id "null")
:sequencer "00"}}}))
{:status 200
:headers (as-> {"ETag" etag} h
(if (some? version-id)
(assoc h "x-amz-version-id" version-id)
h))})
{:status 404
:headers xml-content-type
:body [:Error
[:Code "NoSuchBucket"]
[:Resource (str \/ bucket)]
[:RequestId request-id]]})))
(defn ^:no-doc parse-date-header
[d]
(try
(ZonedDateTime/parse d DateTimeFormatter/RFC_1123_DATE_TIME)
(catch DateTimeParseException _
(try
(ZonedDateTime/parse d auth/RFC-1036-FORMATTER)
(catch DateTimeParseException _
(ZonedDateTime/parse d auth/ASCTIME-FORMATTER))))))
(defn ^:no-doc parse-range
[r]
(let [[begin end] (rest (re-matches #"bytes=([0-9]+)-([0-9]*)" r))]
(when (some? begin)
[(Long/parseLong begin)
(some-> (not-empty end) (Long/parseLong))])))
(defn ^:no-doc unwrap-input-stream
[value]
(log/debug :task ::unwrap-input-stream :value value)
(cond (instance? InputStream value) value
(map? value) (recur (:input-stream value))
(bytes? value) (ByteArrayInputStream. value)))
(defn ^:no-doc get-object
[bucket object request {:keys [konserve cost-tracker]} request-id with-body?]
(sv/go-try sv/S
($/-track-get-request! cost-tracker)
(if-let [existing-bucket (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))]
(if-let [versions (sv/<? sv/S (k/get-in konserve [:version-meta bucket object]))]
(let [params (keywordize-keys (uri/query->map (:query-string request)))]
(cond (some? (:acl params))
(as-> {:status 200
:headers xml-content-type} r
(if with-body?
(assoc r :body [:AccessControlPolicy
[:Owner
[:ID "S4"]
[:DisplayName "You Know, for Data"]]
[:AccessControlList
[:Grant
[:Grantee {"xmlns:xsi" "-instance"
"xsi:type" "CanonicalUser"}
[:ID "S4"]
[:DisplayName "You Know, for Data"]]
[:Permission "FULL_CONTROL"]]]])
r))
(or (some? (:legal-hold params))
(some? (:retention params))
(some? (:torrent params))
(some? (:tagging params)))
(as-> {:status 501
:headers xml-content-type} r
(if with-body?
(assoc r :body [:Error
[:Code "NotImplemented"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r))
:else
(if-let [version (let [v (if-let [version-id (:versionId params)]
(first (filter #(= version-id (:version-id %)) versions))
(first versions))]
(log/debug :task ::get-object :phase :got-version :version v)
v)]
(if (:deleted? version)
(as-> {:status 404
:headers (as-> xml-content-type h
(if (some? (:versioning existing-bucket))
(assoc h "x-amz-version-id" (or (:version-id version) "null")
"x-amz-delete-marker" "true")
h))} r
(if with-body?
(assoc r :body [:Error
[:Code "NoSuchKey"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r))
(let [if-modified-since (some-> (get-in request [:headers "if-modified-since"]) parse-date-header)
if-unmodified-since (some-> (get-in request [:headers "if-unmodified-since"]) parse-date-header)
if-match (get-in request [:headers "if-match"])
if-none-match (get-in request [:headers "if-none-match"])
content-type (or (:response-content-type params)
(:content-type version))
headers (as-> {"content-type" content-type
"last-modified" (.format DateTimeFormatter/ISO_OFFSET_DATE_TIME (:created version))
"accept-ranges" "bytes"
"content-length" (str (:content-length version))} h
(if-let [etag (:etag version)]
(assoc h "etag" etag)
h)
(if-let [v (:response-content-language params)]
(assoc h "content-language" v)
h)
(if-let [v (:response-expires params)]
(assoc h "expires" v)
h)
(if-let [v (:response-cache-control params)]
(assoc h "cache-control" v)
h)
(if-let [v (:response-content-disposition params)]
(assoc h "content-disposition" v)
h)
(if-let [v (:response-content-encoding params)]
(assoc h "content-encoding" v)
h)
(if (= "Enabled" (:versioning existing-bucket))
(assoc h "x-amz-version-id" (or (:version-id version) "null"))
h))
range (some-> (get-in request [:headers "range"]) parse-range)]
(log/debug :task ::get-object :phase :checking-object :version version
:if-modified-since if-modified-since
:if-unmodified-since if-unmodified-since
:if-match if-match
:if-none-match if-none-match)
(cond (and (some? if-modified-since)
(pos? (compare if-modified-since (:created version))))
{:status 304
:headers headers}
(and (some? if-unmodified-since)
(pos? (compare (:created version) if-unmodified-since)))
{:status 412
:headers headers}
(and (some? if-match)
(not= if-match (:etag version)))
{:status 412
:headers headers}
(and (some? if-none-match)
(= if-none-match (:etag version)))
{:status 304
:headers headers}
(and (some? range)
(or (and (some? (second range)) (> (first range) (second range)))
(> (first range) (:content-length version))
(and (some? (second range)) (> (second range) (:content-length version)))))
{:status 416
:headers headers}
(and (some? range)
(or (pos? (first range))
(and (some? (second range))
(not= (second range) (:content-length version)))))
(let [range [(first range) (or (second range) (:content-length version))]
response {:status 206
:headers (assoc headers
"content-range" (str "bytes " (first range) \- (second range) \/ (:content-length version)))}]
(if with-body?
(if (satisfies? kp/PBinaryAsyncKeyValueStore konserve)
there seems to be no consistency in what -bget returns
filestore expects a channel from the callback , takes from
(let [content (k/bget konserve (:blob-id version)
(fn [in]
(async/thread
(some-> (unwrap-input-stream in)
(ByteStreams/limit (second range))
(ByteStreams/skipFully (first range))
(ByteStreams/toByteArray)))))
content (loop [content content]
(if (satisfies? impl/ReadPort content)
(recur (sv/<? sv/S content))
content))]
($/-track-data-out! cost-tracker (- (second range) (first range)))
(assoc response :body content))
(let [content (or (sv/<? sv/S (k/get-in konserve (:blob-id version))) (byte-array 0))]
($/-track-data-out! cost-tracker (- (second range) (first range)))
(assoc response :body (ByteArrayInputStream. content (first range) (- (second range) (first range))))))
response))
:else
(let [response {:status 200
:headers headers}]
(if with-body?
(if (satisfies? kp/PBinaryAsyncKeyValueStore konserve)
(let [content (k/bget konserve (:blob-id version)
(fn [in]
(async/thread
(some-> (unwrap-input-stream in)
(ByteStreams/toByteArray)))))
content (loop [content content]
(if (satisfies? impl/ReadPort content)
(recur (sv/<? sv/S content))
content))]
($/-track-data-out! cost-tracker (:content-length version))
(assoc response :body content))
(let [content (or (sv/<? sv/S (k/get-in konserve (:blob-id version))) (byte-array 0))]
($/-track-data-out! cost-tracker (:content-length version))
(assoc response :body (ByteArrayInputStream. content))))
response)))))
(as-> {:status 404
:headers xml-content-type} r
(if with-body?
(assoc r :body [:Error
[:Code "NoSuchVersion"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r)))))
(as-> {:status 404
:headers xml-content-type} r
(if with-body?
(assoc r :body [:Error
[:Code "NoSuchKey"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r)))
(as-> {:status 404
:headers xml-content-type} r
(if with-body?
(assoc r :body [:Error
[:Code "NoSuchBucket"]
[:Resource (str \/ bucket \/ object)]
[:RequestId request-id]])
r)))))
(defn ^:no-doc delete-object
[{:keys [konserve clock sqs-server]} request bucket object bucket-meta request-id]
(sv/go-try sv/S
(let [{:keys [versionId tagging]} (keywordize-keys (uri/query->map (:query-string request)))]
(if (some? tagging)
{:status 501
:headers xml-content-type
:body [:Error [:Code "NotImplemented"] [:Resource (str \/ bucket \/ object)]]}
(let [last-mod (ZonedDateTime/now clock)
[old new] (sv/<?
sv/S
(k/update-in konserve [:version-meta bucket]
(fn [objects]
(let [res (update objects object
(fn [versions]
(if (nil? versions)
versions
(cond (some? versionId)
(remove #(= versionId (:version-id %)) versions)
(= "Enabled" (:versioning bucket-meta))
(let [version-id (generate-blob-id bucket object)]
(cons {:version-id version-id
:deleted? true
:last-modified last-mod}
versions))
(:deleted? (first versions))
versions
(and (<= (count versions) 1)
(not= "Enabled" (:versioning bucket-meta)))
nil
:else
(cons {:version-id nil
:deleted? true
:last-modified last-mod}
(remove #(nil? (:version-id %)) versions))))))]
(if (nil? (get res object))
(dissoc res object)
res)))))]
(if (and (nil? old) (nil? new))
{:status 204}
(do
(when-let [deleted-version (first (set/difference (set old) (set new)))]
(when-let [blob-id (:blob-id deleted-version)]
(sv/<? sv/S (k/dissoc konserve blob-id))))
(sv/<? sv/S (trigger-bucket-notification sqs-server (:notifications bucket-meta)
{:eventVersion "2.1"
:eventSource "aws:s3"
:awsRegion "s4"
:eventTime (.format last-mod DateTimeFormatter/ISO_OFFSET_DATE_TIME)
:eventName (if (some? versionId)
"ObjectRemoved:DeleteMarkerCreated"
"ObjectRemoved:Delete")
:userIdentity {:principalId "S4"}
:requestParameters {:sourceIPAddress (:remote-addr request)}
:responseElements {:x-amz-request-id request-id}
:s3 {:s3SchemaVersion "1.0"
:bucket {:name bucket
:ownerIdentity {:principalId "S4"}
:arn bucket}
:object (assoc-some {:key object
:sequencer "00"}
:versionId versionId)}}))
(cond (some? versionId)
{:status 204
:headers (as-> {"x-amz-version-id" versionId}
h
(if (some #(= versionId (:version-id %)) old)
(assoc h "x-amz-delete-marker" "true")
h))}
(not-empty (get new object))
{:status 204
:headers {"x-amz-version-id" (or (:version-id (first new)) "null")
"x-amz-delete-marker" "true"}}
:else
{:status 204
:headers (if (or (empty? old) (nil? (:versioning bucket-meta)))
{}
{"x-amz-version-id" "null"})}))))))))
(defn s3-handler
"Create an asynchronous Ring handler for the S3 API.
Keys in the argument map:
* `konserve` The konserve instance.
* `hostname` Your hostname, e.g. \"localhost\". This should match what your client sends.
* `request-id-prefix` A string to prepend to request IDs.
* `request-counter` An atom containing an int, used to generate request IDs.
* `cost-tracker` A [[s4.$$$$/ICostTracker]], for estimating costs.
* `clock` A `java.time.Clock` to use for generating timestamps."
[{:keys [konserve hostname request-id-prefix request-counter cost-tracker clock sqs-server] :as system}]
(fn [request respond error]
(async/go
(let [request-id (str request-id-prefix (format "%016x" (swap! request-counter inc)))]
(try
(log/debug :task ::s3-handler :phase :begin :request (pr-str request))
(let [respond (fn respond-wrapper
[response]
(log/debug :task ::s3-handler :phase :end :response (pr-str response))
(let [body (:body response)
body (if (and (= "application/xml" (get-in response [:headers "content-type"]))
(sequential? body))
(xml/emit-str (xml/sexp-as-element body) :encoding "UTF-8")
body)]
(respond (assoc
(assoc-in response [:headers "x-amz-request-id"] request-id)
:body body))))
[bucket object] (read-bucket-object request hostname)]
(log/debug :task ::s3-handler :bucket bucket :object object)
(case (:request-method request)
:head (cond (and (not-empty bucket)
(empty? object))
(do
($/-track-get-request! cost-tracker)
(if (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))
(respond {:status 200})
(respond {:status 404})))
(and (not-empty bucket)
(not-empty object))
(do
($/-track-get-request! cost-tracker)
(respond (sv/<? sv/S (get-object bucket object request system request-id false))))
:else
(do
($/-track-get-request! cost-tracker)
(respond {:status 200})))
:get (cond (empty? bucket)
(let [buckets (sv/<? sv/S (k/get-in konserve [:bucket-meta]))
buckets-response [:ListAllMyBucketsResult {:xmlns "-03-01"}
[:Owner {}
[:ID {} "S4"]
[:DisplayName {} "You Know, for Data"]]
[:Buckets {}
(map (fn [[bucket-name {:keys [created]}]]
[:Bucket {}
[:Name {} bucket-name]
[:CreationDate {} (.format DateTimeFormatter/ISO_OFFSET_DATE_TIME created)]])
buckets)]]]
($/-track-put-request! cost-tracker)
(respond {:status 200
:headers xml-content-type
:body buckets-response}))
(empty? object)
(respond (sv/<? sv/S (bucket-get-ops bucket request system request-id)))
:else
(respond (sv/<? sv/S (get-object bucket object request system request-id true))))
:put (do
($/-track-put-request! cost-tracker)
(cond (and (not-empty bucket) (empty? object))
(respond (sv/<? sv/S (bucket-put-ops bucket request system request-id)))
(and (not-empty bucket) (not-empty object))
(respond (sv/<? sv/S (put-object bucket object request system request-id)))
:else (respond {:status 501
:headers xml-content-type
:body [:Error {}
[:Code {} "NotImplemented"]
[:Resource {} (:uri request)]
[:RequestId {} request-id]]})))
:post (let [params (keywordize-keys (uri/query->map (:query-string request)))]
($/-track-put-request! cost-tracker)
(cond
(and (some? (:delete params))
(nil? object))
(if-let [bucket-meta (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket]))]
(let [objects (element-as-sexp (xml/parse (:body request) :namespace-aware false))]
(if (not= :Delete (first objects))
(respond {:status 400
:headers xml-content-type
:body [:Error
[:Code "MalformedXML"]
[:Resource (:uri request)]
[:RequestId request-id]]})
(let [quiet (= "true" (->> (rest objects)
(filter #(= :Quiet (first %)))
(first)
(second)))
results (->> (rest objects)
(filter #(= :Object (first %)))
(map #(let [object (into {} (rest %))
query {}
query (if-let [v (:VersionId object)]
(assoc query :versionId v))
request {:query-string (uri/map->query query)}]
(async/go
[object (async/<! (delete-object system request bucket (:Key object) bucket-meta request-id))])))
(sv/<?* sv/S)
(doall))]
(respond {:status 200
:headers xml-content-type
:body (into [:DeleteObjectOutput]
(->> results
(remove #(and quiet (= 200 (:status (second %)))))
(map (fn [[object result]]
(if (= 200 (:status result))
(vec (concat [:Deleted
[:Key (:Key object)]]
(some->> (:VersionId object) (vector :VersionId) (vector))
(when-let [v (get-in result [:headers "x-amz-version-id"])]
[[:DeleteMarkerVersionId v]])
(when (= "true" (get-in result [:headers "x-amz-delete-marker"]))
[[:DeleteMarker "true"]])))
(vec (concat [:Error
[:Key (:Key object)]]
(some->> (:VersionId object) (vector :VersionId) (vector))
(->> (:body result)
(rest)
(filter #(= :Code (first %)))))))))))}))))
(respond {:status 404
:headers xml-content-type
:body [:Error [:Code "NoSuchBucket"] [:Resource (:uri request)] [:RequestId request-id]]}))
:else
(respond {:status 501
:headers xml-content-type
:body [:Error {}
[:Code {} "NotImplemented"]
[:Resource {} (:uri request)]
[:RequestId {} request-id]]})))
:delete (do
($/-track-get-request! cost-tracker)
(cond (and (not-empty bucket) (empty? object))
(if-let [bucket-meta (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))]
(if (pos? (:object-count bucket-meta 0))
(respond {:status 409
:headers xml-content-type
:body [:Error {}
[:Code {} "BucketNotEmpty"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]})
(do
(sv/<? sv/S (k/update-in konserve [:bucket-meta] #(dissoc % bucket)))
(sv/<? sv/S (k/update-in konserve [:version-meta] #(dissoc % bucket)))
(respond {:status 204})))
(respond {:status 404
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchBucket"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]}))
(and (not-empty bucket) (not-empty object))
(if-let [bucket-meta (not-empty (sv/<? sv/S (k/get-in konserve [:bucket-meta bucket])))]
(respond (sv/<? sv/S (delete-object system request bucket object bucket-meta request-id)))
(respond {:status 404}
:headers xml-content-type
:body [:Error {}
[:Code {} "NoSuchBucket"]
[:Resource {} (str \/ bucket)]
[:RequestId {} request-id]]))
:else (respond {:status 501
:headers xml-content-type
:body [:Error {}
[:Code {} "NotImplemented"]
[:Resource {} (:uri request)]
[:RequestId {} request-id]]})))
(do
($/-track-get-request! cost-tracker)
(respond {:status 405
:headers xml-content-type
:body [:Error {}
[:Code {} "MethodNotAllowed"]
[:Message {} (string/upper-case (name (:request-method request)))]
[:Resource {} (:uri request)]
[:RequestId {} request-id]]}))))
(catch Exception x
(log/warn x "exception in S3 handler")
(respond {:status 500
:headers xml-content-type
:body [:Error {}
[:Code {} "InternalError"]
[:Resource {} (:uri request)]
[:RequestId {} request-id]]})))))))
(defn make-handler
"Make an asynchronous, authenticated S3 ring handler.
See [[s3-handler]] and [[s4.auth/authenticating-handler]]
for what keys should be in `system`."
[system]
(auth/authenticating-handler (s3-handler system) system))
(defn make-reloadable-handler
"Create an S3 handler that will rebuild the handler functions on
calls via a REPL. System is an atom containing a system map."
[system]
(fn [request respond error]
(let [handler (s3-handler @system)
auth-handler (auth/authenticating-handler handler @system)]
(auth-handler request respond error))))
(comment
"If you want a konserve file store, do this:"
(def file-store (async/<!! (konserve.filestore/new-fs-store "foo" {:serializer (ser/fressian-serializer @read-handlers @write-handlers)})))
"You need to use the custom read/write handlers for fressian, since by default
fressian doesn't support sorted-map. This likely goes for any other
konserve implementation, but I haven't looked.") |
9cc869a3a712f7095a594d01f56d10bba3b3a83b9e7ad95c16528bec21fe83c5 | cunger/pythia | Effects.clj | (ns core.definitions.Effects
(:require [core.nlu.context.short_term_memory :as stm]
[core.nlu.reasoning.oracle :as oracle]
[core.data.LambdaRDF :refer :all])
(:import [core.data.LambdaRDF Term Triple Path Not And Or Quant Ask Select]))
;; Functions without effects
(defn bind [v e] (Select. v e))
(defn check [e] (Ask. e))
(defn lnot [e] (Not. e))
(defn land [e1 e2] (And. e1 e2))
(defn lor [e1 e2] (Or. e1 e2))
(defn quant [q v es1 es2] (Quant. q v es1 es2))
;; Functions with effects
(defn sel [& conditions]
(let [i (stm/get-fresh!)]
; oracle/... context/...
add candidates for x to / candidates
; return x
i))
(defn bridge [e1 e2 & conditions]
(let [candidates (oracle/rank (oracle/find-paths e1 e2 conditions))
instantiations (if-not (empty? candidates) candidates [(oracle/eq-path e1 e2) (Path. e1 e2 conditions)])
i (stm/get-fresh!)]
(do (swap! stm/candidates assoc i instantiations)
(Term. :index i))))
| null | https://raw.githubusercontent.com/cunger/pythia/f58e35395968d4c46aef495fd363c26b1102003c/src/core/definitions/Effects.clj | clojure | Functions without effects
Functions with effects
oracle/... context/...
return x | (ns core.definitions.Effects
(:require [core.nlu.context.short_term_memory :as stm]
[core.nlu.reasoning.oracle :as oracle]
[core.data.LambdaRDF :refer :all])
(:import [core.data.LambdaRDF Term Triple Path Not And Or Quant Ask Select]))
(defn bind [v e] (Select. v e))
(defn check [e] (Ask. e))
(defn lnot [e] (Not. e))
(defn land [e1 e2] (And. e1 e2))
(defn lor [e1 e2] (Or. e1 e2))
(defn quant [q v es1 es2] (Quant. q v es1 es2))
(defn sel [& conditions]
(let [i (stm/get-fresh!)]
add candidates for x to / candidates
i))
(defn bridge [e1 e2 & conditions]
(let [candidates (oracle/rank (oracle/find-paths e1 e2 conditions))
instantiations (if-not (empty? candidates) candidates [(oracle/eq-path e1 e2) (Path. e1 e2 conditions)])
i (stm/get-fresh!)]
(do (swap! stm/candidates assoc i instantiations)
(Term. :index i))))
|
68f080cec3d303235dfea9396cdced83bb117aa5d05de6ab6952b57658bce46d | RolfRolles/PandemicML | BinaryFileUtil.ml | (* Belongs in a BinaryFileUtil module *)
let transformed_int_array_of_filename f fname =
let fh = open_in_bin fname in
let rl_i32 = ref [] in
let add i32 = rl_i32 := i32::(!rl_i32) in
let rec aux () =
let _ = add (f (input_byte fh)) in
aux ()
in
try
aux ()
with End_of_file ->
let _ = close_in fh in
Array.of_list (List.rev !rl_i32)
let int32_array_of_filename = transformed_int_array_of_filename Int32.of_int
let int_array_of_filename = transformed_int_array_of_filename (fun x -> x) | null | https://raw.githubusercontent.com/RolfRolles/PandemicML/9c31ecaf9c782dbbeb6cf502bc2a6730316d681e/Util/BinaryFileUtil.ml | ocaml | Belongs in a BinaryFileUtil module | let transformed_int_array_of_filename f fname =
let fh = open_in_bin fname in
let rl_i32 = ref [] in
let add i32 = rl_i32 := i32::(!rl_i32) in
let rec aux () =
let _ = add (f (input_byte fh)) in
aux ()
in
try
aux ()
with End_of_file ->
let _ = close_in fh in
Array.of_list (List.rev !rl_i32)
let int32_array_of_filename = transformed_int_array_of_filename Int32.of_int
let int_array_of_filename = transformed_int_array_of_filename (fun x -> x) |
d06877d4184ae477901a6d76f869c9f55b7dcbb4f8aa6949b5aaa98d4e31ced7 | esl/tracerl | tracerl.erl | %%%-------------------------------------------------------------------
@author
( C ) 2013 , Erlang Solutions Ltd.
%%% @doc Main tracerl API
%%%
%%% @end
Created : 21 Aug 2013 by
%%%-------------------------------------------------------------------
-module(tracerl).
-export([start_trace/3, start_trace/4, stop_trace/1]).
start_trace(ScriptSrc, Node, PidOrHandler) ->
start_trace(ScriptSrc, Node, PidOrHandler, []).
start_trace(ScriptSrc, Node, PidOrHandler, Options) ->
tracerl_sup:start_child(ScriptSrc, Node, PidOrHandler, Options).
stop_trace(Pid) ->
tracerl_process:stop(Pid).
| null | https://raw.githubusercontent.com/esl/tracerl/8ebc649ccd7a3013aa310e4f71d35ef65fb3286b/src/tracerl.erl | erlang | -------------------------------------------------------------------
@doc Main tracerl API
@end
------------------------------------------------------------------- | @author
( C ) 2013 , Erlang Solutions Ltd.
Created : 21 Aug 2013 by
-module(tracerl).
-export([start_trace/3, start_trace/4, stop_trace/1]).
start_trace(ScriptSrc, Node, PidOrHandler) ->
start_trace(ScriptSrc, Node, PidOrHandler, []).
start_trace(ScriptSrc, Node, PidOrHandler, Options) ->
tracerl_sup:start_child(ScriptSrc, Node, PidOrHandler, Options).
stop_trace(Pid) ->
tracerl_process:stop(Pid).
|
75b1f4ec3ff84a1a6c93b5ef4f34fdc75804d153c22e02f27cc964b1c096b0fb | metosin/compojure-api | resource_test.clj | (ns compojure.api.resource-test
(:require [compojure.api.sweet :refer :all]
[compojure.api.test-utils :refer :all]
[plumbing.core :refer [fnk]]
[midje.sweet :refer :all]
[ring.util.http-response :refer :all]
[clojure.core.async :as a]
[schema.core :as s]
[compojure.api.test-utils :refer [call]])
(:import (clojure.lang ExceptionInfo)))
(defn has-body [expected]
(fn [{:keys [body]}]
(= body expected)))
(def request-validation-failed?
(throws ExceptionInfo #"Request validation failed"))
(def response-validation-failed?
(throws ExceptionInfo #"Response validation failed"))
(facts "resource definitions"
(fact "only top-level handler"
(let [handler (resource
{:handler (constantly (ok {:total 10}))})]
(fact "paths and methods don't matter"
(call handler {:request-method :get, :uri "/"}) => (has-body {:total 10})
(call handler {:request-method :head, :uri "/kikka"}) => (has-body {:total 10}))))
(fact "top-level parameter coercions"
(let [handler (resource
{:parameters {:query-params {:x Long}}
:handler (fnk [[:query-params x]]
(ok {:total x}))})]
(call handler {:request-method :get}) => request-validation-failed?
(call handler {:request-method :get, :query-params {:x "1"}}) => (has-body {:total 1})
(call handler {:request-method :get, :query-params {:x "1", :y "2"}}) => (has-body {:total 1})))
(fact "top-level and operation-level parameter coercions"
(let [handler (resource
{:parameters {:query-params {:x Long}}
:get {:parameters {:query-params {(s/optional-key :y) Long}}}
:handler (fnk [[:query-params x {y 0}]]
(ok {:total (+ x y)}))})]
(call handler {:request-method :get}) => request-validation-failed?
(call handler {:request-method :get, :query-params {:x "1"}}) => (has-body {:total 1})
(call handler {:request-method :get, :query-params {:x "1", :y "a"}}) => request-validation-failed?
(call handler {:request-method :get, :query-params {:x "1", :y "2"}}) => (has-body {:total 3})
(fact "non-matching operation level parameters are not used"
(call handler {:request-method :post, :query-params {:x "1"}}) => (has-body {:total 1})
(call handler {:request-method :post, :query-params {:x "1", :y "2"}}) => (throws ClassCastException))))
(fact "middleware"
(let [mw (fn [handler k] (fn [req] (update-in (handler req) [:body :mw] (fnil conj '()) k)))
handler (resource
{:middleware [[mw :top1] [mw :top2]]
:get {:middleware [[mw :get1] [mw :get2]]}
:post {:middleware [[mw :post1] [mw :post2]]}
:handler (constantly (ok))})]
(fact "top + method-level mw are applied if they are set"
(call handler {:request-method :get}) => (has-body {:mw [:top1 :top2 :get1 :get2]})
(call handler {:request-method :post}) => (has-body {:mw [:top1 :top2 :post1 :post2]}))
(fact "top-level mw are applied if method doesn't have mw"
(call handler {:request-method :put}) => (has-body {:mw [:top1 :top2]}))))
(fact "operation-level handlers"
(let [handler (resource
{:parameters {:query-params {:x Long}}
:get {:parameters {:query-params {(s/optional-key :y) Long}}
:handler (fnk [[:query-params x {y 0}]]
(ok {:total (+ x y)}))}
:post {:parameters {:query-params {:z Long}}}})]
(call handler {:request-method :get}) => request-validation-failed?
(call handler {:request-method :get, :query-params {:x "1"}}) => (has-body {:total 1})
(call handler {:request-method :get, :query-params {:x "1", :y "a"}}) => request-validation-failed?
(call handler {:request-method :get, :query-params {:x "1", :y "2"}}) => (has-body {:total 3})
(fact "if no handler is found, nil is returned"
(call handler {:request-method :post, :query-params {:x "1"}}) => nil)))
(fact "handler preference"
(let [handler (resource
{:get {:handler (constantly (ok {:from "get"}))}
:handler (constantly (ok {:from "top"}))})]
(call handler {:request-method :get}) => (has-body {:from "get"})
(call handler {:request-method :post}) => (has-body {:from "top"})))
(fact "resource without coercion"
(let [handler (resource
{:coercion nil
:get {:parameters {:query-params {(s/optional-key :y) Long
(s/optional-key :x) Long}}
:handler (fn [{{:keys [x y]} :query-params}]
(ok {:x x
:y y}))}})]
(call handler {:request-method :get}) => (has-body {:x nil, :y nil})
(call handler {:request-method :get, :query-params {:x "1"}}) => (has-body {:x "1", :y nil})
(call handler {:request-method :get, :query-params {:x "1", :y "a"}}) => (has-body {:x "1", :y "a"})
(call handler {:request-method :get, :query-params {:x 1, :y 2}}) => (has-body {:x 1, :y 2})))
(fact "parameter mappings"
(let [handler (resource
{:get {:parameters {:query-params {:q s/Str}
:body-params {:b s/Str}
:form-params {:f s/Str}
:header-params {:h s/Str}
:path-params {:p s/Str}}
:handler (fn [request]
(ok (select-keys request [:query-params
:body-params
:form-params
:header-params
:path-params])))}})]
(call handler {:request-method :get
:query-params {:q "q"}
:body-params {:b "b"}
:form-params {:f "f"}
;; the ring headers
:headers {"h" "h"}
;; compojure routing
:route-params {:p "p"}}) => (has-body {:query-params {:q "q"}
:body-params {:b "b"}
:form-params {:f "f"}
:header-params {:h "h"}
:path-params {:p "p"}})))
(fact "response coercion"
(let [handler (resource
{:responses {200 {:schema {:total (s/constrained Long pos? 'pos)}}}
:parameters {:query-params {:x Long}}
:get {:responses {200 {:schema {:total (s/constrained Long #(>= % 10) 'gte10)}}}
:handler (fnk [[:query-params x]]
(ok {:total x}))}
:handler (fnk [[:query-params x]]
(ok {:total x}))})]
(call handler {:request-method :get}) => request-validation-failed?
(call handler {:request-method :get, :query-params {:x "-1"}}) => response-validation-failed?
(call handler {:request-method :get, :query-params {:x "1"}}) => response-validation-failed?
(call handler {:request-method :get, :query-params {:x "10"}}) => (has-body {:total 10})
(call handler {:request-method :post, :query-params {:x "1"}}) => (has-body {:total 1}))))
(fact "explicit async tests"
(let [handler (resource
{:parameters {:query-params {:x Long}}
:responses {200 {:schema {:total (s/constrained Long pos? 'pos)}}}
:summary "top-level async handler"
:async-handler (fn [{{x :x} :query-params} res _]
(future
(res (ok {:total x})))
nil)
:get {:summary "operation-level async handler"
:async-handler (fn [{{x :x} :query-params} respond _]
(future
(respond (ok {:total (inc x)})))
nil)}
:post {:summary "operation-level sync handler"
:handler (fn [{{x :x} :query-params}]
(ok {:total (* x 10)}))}
:put {:summary "operation-level async send"
:handler (fn [{{x :x} :query-params}]
(a/go
(a/<! (a/timeout 100))
(ok {:total (* x 100)})))}})]
(fact "top-level async handler"
(let [respond (promise), res-raise (promise), req-raise (promise)]
(handler {:query-params {:x 1}} respond (promise))
(handler {:query-params {:x -1}} (promise) res-raise)
(handler {:query-params {:x "x"}} (promise) req-raise)
(deref respond 1000 :timeout) => (has-body {:total 1})
(throw (deref res-raise 1000 :timeout)) => response-validation-failed?
(throw (deref req-raise 1000 :timeout)) => request-validation-failed?))
(fact "operation-level async handler"
(let [respond (promise)]
(handler {:request-method :get, :query-params {:x 1}} respond (promise))
(deref respond 1000 :timeout) => (has-body {:total 2})))
(fact "sync handler can be called from async"
(let [respond (promise)]
(handler {:request-method :post, :query-params {:x 1}} respond (promise))
(deref respond 1000 :timeout) => (has-body {:total 10}))
(fact "response coercion works"
(let [raise (promise)]
(handler {:request-method :post, :query-params {:x -1}} (promise) raise)
(throw (deref raise 1000 :timeout)) => response-validation-failed?)))
(fact "core.async ManyToManyChannel"
(fact "works with 3-arity"
(let [respond (promise)]
(handler {:request-method :put, :query-params {:x 1}} respond (promise))
(deref respond 2000 :timeout) => (has-body {:total 100}))
(fact "response coercion works"
(let [raise (promise)]
(handler {:request-method :put, :query-params {:x -1}} (promise) raise)
(throw (deref raise 2000 :timeout)) => response-validation-failed?)))
(fact "fails with 1-arity"
(handler {:request-method :put, :query-params {:x 1}}) => (throws) #_(has-body {:total 100})
(handler {:request-method :put, :query-params {:x -1}}) => (throws) #_response-validation-failed?))))
(fact "compojure-api routing integration"
(let [app (context "/rest" []
(GET "/no" request
(ok (select-keys request [:uri :path-info])))
;; works & api-docs
(context "/context" []
(resource
{:handler (constantly (ok "CONTEXT"))}))
;; works, but no api-docs
(ANY "/any" []
(resource
{:handler (constantly (ok "ANY"))}))
(context "/path/:id" []
(resource
{:parameters {:path-params {:id s/Int}}
:handler (fn [request]
(ok (select-keys request [:path-params :route-params])))}))
(resource
{:get {:handler (fn [request]
(ok (select-keys request [:uri :path-info])))}}))]
(fact "normal endpoint works"
(call app {:request-method :get, :uri "/rest/no"}) => (has-body {:uri "/rest/no", :path-info "/no"}))
(fact "wrapped in ANY works"
(call app {:request-method :get, :uri "/rest/any"}) => (has-body "ANY"))
(fact "wrapped in context works"
(call app {:request-method :get, :uri "/rest/context"}) => (has-body "CONTEXT"))
(fact "only exact path match works"
(call app {:request-method :get, :uri "/rest/context/2"}) => nil)
(fact "path-parameters work: route-params are left untoucehed, path-params are coerced"
(call app {:request-method :get, :uri "/rest/path/12"}) => (has-body {:path-params {:id 12}
:route-params {:id "12"}}))
(fact "top-level GET without extra path works"
(call app {:request-method :get, :uri "/rest"}) => (has-body {:uri "/rest"
:path-info "/"}))
(fact "top-level POST without extra path works"
(call app {:request-method :post, :uri "/rest"}) => nil)
(fact "top-level GET with extra path misses"
(call app {:request-method :get, :uri "/rest/in-peaces"}) => nil)))
(fact "swagger-integration"
(fact "explicitely defined methods produce api-docs"
(let [app (api
(swagger-routes)
(context "/rest" []
(resource
{:parameters {:query-params {:x Long}}
:responses {400 {:schema (s/schema-with-name {:code s/Str} "Error")}}
:get {:parameters {:query-params {:y Long}}
:responses {200 {:schema (s/schema-with-name {:total Long} "Total")}}}
:post {}
:handler (constantly (ok {:total 1}))})))
spec (get-spec app)]
spec => (contains
{:definitions (just
{:Error irrelevant
:Total irrelevant})
:paths (just
{"/rest" (just
{:get (just
{:parameters (two-of irrelevant)
:responses (just {:200 irrelevant, :400 irrelevant})})
:post (just
{:parameters (one-of irrelevant)
:responses (just {:400 irrelevant})})})})})))
(fact "top-level handler doesn't contribute to docs"
(let [app (api
(swagger-routes)
(context "/rest" []
(resource
{:handler (constantly (ok {:total 1}))})))
spec (get-spec app)]
spec => (contains
{:paths {}}))))
| null | https://raw.githubusercontent.com/metosin/compojure-api/5c88f32fe56cdb6fcdb3cc506bb956943fcd8c17/test/compojure/api/resource_test.clj | clojure | the ring headers
compojure routing
works & api-docs
works, but no api-docs | (ns compojure.api.resource-test
(:require [compojure.api.sweet :refer :all]
[compojure.api.test-utils :refer :all]
[plumbing.core :refer [fnk]]
[midje.sweet :refer :all]
[ring.util.http-response :refer :all]
[clojure.core.async :as a]
[schema.core :as s]
[compojure.api.test-utils :refer [call]])
(:import (clojure.lang ExceptionInfo)))
(defn has-body [expected]
(fn [{:keys [body]}]
(= body expected)))
(def request-validation-failed?
(throws ExceptionInfo #"Request validation failed"))
(def response-validation-failed?
(throws ExceptionInfo #"Response validation failed"))
(facts "resource definitions"
(fact "only top-level handler"
(let [handler (resource
{:handler (constantly (ok {:total 10}))})]
(fact "paths and methods don't matter"
(call handler {:request-method :get, :uri "/"}) => (has-body {:total 10})
(call handler {:request-method :head, :uri "/kikka"}) => (has-body {:total 10}))))
(fact "top-level parameter coercions"
(let [handler (resource
{:parameters {:query-params {:x Long}}
:handler (fnk [[:query-params x]]
(ok {:total x}))})]
(call handler {:request-method :get}) => request-validation-failed?
(call handler {:request-method :get, :query-params {:x "1"}}) => (has-body {:total 1})
(call handler {:request-method :get, :query-params {:x "1", :y "2"}}) => (has-body {:total 1})))
(fact "top-level and operation-level parameter coercions"
(let [handler (resource
{:parameters {:query-params {:x Long}}
:get {:parameters {:query-params {(s/optional-key :y) Long}}}
:handler (fnk [[:query-params x {y 0}]]
(ok {:total (+ x y)}))})]
(call handler {:request-method :get}) => request-validation-failed?
(call handler {:request-method :get, :query-params {:x "1"}}) => (has-body {:total 1})
(call handler {:request-method :get, :query-params {:x "1", :y "a"}}) => request-validation-failed?
(call handler {:request-method :get, :query-params {:x "1", :y "2"}}) => (has-body {:total 3})
(fact "non-matching operation level parameters are not used"
(call handler {:request-method :post, :query-params {:x "1"}}) => (has-body {:total 1})
(call handler {:request-method :post, :query-params {:x "1", :y "2"}}) => (throws ClassCastException))))
(fact "middleware"
(let [mw (fn [handler k] (fn [req] (update-in (handler req) [:body :mw] (fnil conj '()) k)))
handler (resource
{:middleware [[mw :top1] [mw :top2]]
:get {:middleware [[mw :get1] [mw :get2]]}
:post {:middleware [[mw :post1] [mw :post2]]}
:handler (constantly (ok))})]
(fact "top + method-level mw are applied if they are set"
(call handler {:request-method :get}) => (has-body {:mw [:top1 :top2 :get1 :get2]})
(call handler {:request-method :post}) => (has-body {:mw [:top1 :top2 :post1 :post2]}))
(fact "top-level mw are applied if method doesn't have mw"
(call handler {:request-method :put}) => (has-body {:mw [:top1 :top2]}))))
(fact "operation-level handlers"
(let [handler (resource
{:parameters {:query-params {:x Long}}
:get {:parameters {:query-params {(s/optional-key :y) Long}}
:handler (fnk [[:query-params x {y 0}]]
(ok {:total (+ x y)}))}
:post {:parameters {:query-params {:z Long}}}})]
(call handler {:request-method :get}) => request-validation-failed?
(call handler {:request-method :get, :query-params {:x "1"}}) => (has-body {:total 1})
(call handler {:request-method :get, :query-params {:x "1", :y "a"}}) => request-validation-failed?
(call handler {:request-method :get, :query-params {:x "1", :y "2"}}) => (has-body {:total 3})
(fact "if no handler is found, nil is returned"
(call handler {:request-method :post, :query-params {:x "1"}}) => nil)))
(fact "handler preference"
(let [handler (resource
{:get {:handler (constantly (ok {:from "get"}))}
:handler (constantly (ok {:from "top"}))})]
(call handler {:request-method :get}) => (has-body {:from "get"})
(call handler {:request-method :post}) => (has-body {:from "top"})))
(fact "resource without coercion"
(let [handler (resource
{:coercion nil
:get {:parameters {:query-params {(s/optional-key :y) Long
(s/optional-key :x) Long}}
:handler (fn [{{:keys [x y]} :query-params}]
(ok {:x x
:y y}))}})]
(call handler {:request-method :get}) => (has-body {:x nil, :y nil})
(call handler {:request-method :get, :query-params {:x "1"}}) => (has-body {:x "1", :y nil})
(call handler {:request-method :get, :query-params {:x "1", :y "a"}}) => (has-body {:x "1", :y "a"})
(call handler {:request-method :get, :query-params {:x 1, :y 2}}) => (has-body {:x 1, :y 2})))
(fact "parameter mappings"
(let [handler (resource
{:get {:parameters {:query-params {:q s/Str}
:body-params {:b s/Str}
:form-params {:f s/Str}
:header-params {:h s/Str}
:path-params {:p s/Str}}
:handler (fn [request]
(ok (select-keys request [:query-params
:body-params
:form-params
:header-params
:path-params])))}})]
(call handler {:request-method :get
:query-params {:q "q"}
:body-params {:b "b"}
:form-params {:f "f"}
:headers {"h" "h"}
:route-params {:p "p"}}) => (has-body {:query-params {:q "q"}
:body-params {:b "b"}
:form-params {:f "f"}
:header-params {:h "h"}
:path-params {:p "p"}})))
(fact "response coercion"
(let [handler (resource
{:responses {200 {:schema {:total (s/constrained Long pos? 'pos)}}}
:parameters {:query-params {:x Long}}
:get {:responses {200 {:schema {:total (s/constrained Long #(>= % 10) 'gte10)}}}
:handler (fnk [[:query-params x]]
(ok {:total x}))}
:handler (fnk [[:query-params x]]
(ok {:total x}))})]
(call handler {:request-method :get}) => request-validation-failed?
(call handler {:request-method :get, :query-params {:x "-1"}}) => response-validation-failed?
(call handler {:request-method :get, :query-params {:x "1"}}) => response-validation-failed?
(call handler {:request-method :get, :query-params {:x "10"}}) => (has-body {:total 10})
(call handler {:request-method :post, :query-params {:x "1"}}) => (has-body {:total 1}))))
(fact "explicit async tests"
(let [handler (resource
{:parameters {:query-params {:x Long}}
:responses {200 {:schema {:total (s/constrained Long pos? 'pos)}}}
:summary "top-level async handler"
:async-handler (fn [{{x :x} :query-params} res _]
(future
(res (ok {:total x})))
nil)
:get {:summary "operation-level async handler"
:async-handler (fn [{{x :x} :query-params} respond _]
(future
(respond (ok {:total (inc x)})))
nil)}
:post {:summary "operation-level sync handler"
:handler (fn [{{x :x} :query-params}]
(ok {:total (* x 10)}))}
:put {:summary "operation-level async send"
:handler (fn [{{x :x} :query-params}]
(a/go
(a/<! (a/timeout 100))
(ok {:total (* x 100)})))}})]
(fact "top-level async handler"
(let [respond (promise), res-raise (promise), req-raise (promise)]
(handler {:query-params {:x 1}} respond (promise))
(handler {:query-params {:x -1}} (promise) res-raise)
(handler {:query-params {:x "x"}} (promise) req-raise)
(deref respond 1000 :timeout) => (has-body {:total 1})
(throw (deref res-raise 1000 :timeout)) => response-validation-failed?
(throw (deref req-raise 1000 :timeout)) => request-validation-failed?))
(fact "operation-level async handler"
(let [respond (promise)]
(handler {:request-method :get, :query-params {:x 1}} respond (promise))
(deref respond 1000 :timeout) => (has-body {:total 2})))
(fact "sync handler can be called from async"
(let [respond (promise)]
(handler {:request-method :post, :query-params {:x 1}} respond (promise))
(deref respond 1000 :timeout) => (has-body {:total 10}))
(fact "response coercion works"
(let [raise (promise)]
(handler {:request-method :post, :query-params {:x -1}} (promise) raise)
(throw (deref raise 1000 :timeout)) => response-validation-failed?)))
(fact "core.async ManyToManyChannel"
(fact "works with 3-arity"
(let [respond (promise)]
(handler {:request-method :put, :query-params {:x 1}} respond (promise))
(deref respond 2000 :timeout) => (has-body {:total 100}))
(fact "response coercion works"
(let [raise (promise)]
(handler {:request-method :put, :query-params {:x -1}} (promise) raise)
(throw (deref raise 2000 :timeout)) => response-validation-failed?)))
(fact "fails with 1-arity"
(handler {:request-method :put, :query-params {:x 1}}) => (throws) #_(has-body {:total 100})
(handler {:request-method :put, :query-params {:x -1}}) => (throws) #_response-validation-failed?))))
(fact "compojure-api routing integration"
(let [app (context "/rest" []
(GET "/no" request
(ok (select-keys request [:uri :path-info])))
(context "/context" []
(resource
{:handler (constantly (ok "CONTEXT"))}))
(ANY "/any" []
(resource
{:handler (constantly (ok "ANY"))}))
(context "/path/:id" []
(resource
{:parameters {:path-params {:id s/Int}}
:handler (fn [request]
(ok (select-keys request [:path-params :route-params])))}))
(resource
{:get {:handler (fn [request]
(ok (select-keys request [:uri :path-info])))}}))]
(fact "normal endpoint works"
(call app {:request-method :get, :uri "/rest/no"}) => (has-body {:uri "/rest/no", :path-info "/no"}))
(fact "wrapped in ANY works"
(call app {:request-method :get, :uri "/rest/any"}) => (has-body "ANY"))
(fact "wrapped in context works"
(call app {:request-method :get, :uri "/rest/context"}) => (has-body "CONTEXT"))
(fact "only exact path match works"
(call app {:request-method :get, :uri "/rest/context/2"}) => nil)
(fact "path-parameters work: route-params are left untoucehed, path-params are coerced"
(call app {:request-method :get, :uri "/rest/path/12"}) => (has-body {:path-params {:id 12}
:route-params {:id "12"}}))
(fact "top-level GET without extra path works"
(call app {:request-method :get, :uri "/rest"}) => (has-body {:uri "/rest"
:path-info "/"}))
(fact "top-level POST without extra path works"
(call app {:request-method :post, :uri "/rest"}) => nil)
(fact "top-level GET with extra path misses"
(call app {:request-method :get, :uri "/rest/in-peaces"}) => nil)))
(fact "swagger-integration"
(fact "explicitely defined methods produce api-docs"
(let [app (api
(swagger-routes)
(context "/rest" []
(resource
{:parameters {:query-params {:x Long}}
:responses {400 {:schema (s/schema-with-name {:code s/Str} "Error")}}
:get {:parameters {:query-params {:y Long}}
:responses {200 {:schema (s/schema-with-name {:total Long} "Total")}}}
:post {}
:handler (constantly (ok {:total 1}))})))
spec (get-spec app)]
spec => (contains
{:definitions (just
{:Error irrelevant
:Total irrelevant})
:paths (just
{"/rest" (just
{:get (just
{:parameters (two-of irrelevant)
:responses (just {:200 irrelevant, :400 irrelevant})})
:post (just
{:parameters (one-of irrelevant)
:responses (just {:400 irrelevant})})})})})))
(fact "top-level handler doesn't contribute to docs"
(let [app (api
(swagger-routes)
(context "/rest" []
(resource
{:handler (constantly (ok {:total 1}))})))
spec (get-spec app)]
spec => (contains
{:paths {}}))))
|
8a603d754c429f4f4ff414874a9a909e5df2c78374e59ed4c8cfab02443757eb | sonyxperiadev/dataflow | Validation.hs | module DataFlow.Validation (
ValidationError(..),
validate
) where
import Data.Set (Set, member, insert, empty)
import Text.Printf
import DataFlow.Core
data ValidationError = UnknownID ID
| DuplicateDeclaration ID
deriving (Eq)
instance Show ValidationError where
show (UnknownID i) = printf "Unknown ID: %s" i
show (DuplicateDeclaration i) = printf "Duplicate declaration of ID: %s" i
getNodeIDs :: Diagram -> [ID]
getNodeIDs (Diagram _ nodes _) = concatMap getRootNodeId nodes
where getId (InputOutput i _) = [i]
getId (Function i _) = [i]
getId (Database i _) = [i]
getRootNodeId (Node node) = getId node
getRootNodeId (TrustBoundary _ _ nodes) = concatMap getId nodes
getBoundaryIDs :: Diagram -> [ID]
getBoundaryIDs (Diagram _ nodes _) = concatMap getRootNodeId nodes
where getRootNodeId (TrustBoundary id _ _) = [id]
getRootNodeId _ = []
validateDuplicateIDs :: [ID] -> Either [ValidationError] (Set ID)
validateDuplicateIDs ids =
case foldl iter (empty, []) ids of
(seen, []) -> Right seen
(_, errors) -> Left errors
where iter (seen, errors) i = if i `member` seen
then (seen, errors ++ [DuplicateDeclaration i])
else (insert i seen, errors)
validateFlowIDs :: Diagram -> Set ID -> Either [ValidationError] ()
validateFlowIDs (Diagram _ _ flows) ids =
case foldl iter [] flows of
[] -> Right ()
errors -> Left errors
where idError i = if i `member` ids then [] else [UnknownID i]
iter errors (Flow source target _) =
errors ++ idError source ++ idError target
validate :: Diagram -> Either [ValidationError] Diagram
validate diagram = do
nodeIDs <- validateDuplicateIDs (getNodeIDs diagram)
validateDuplicateIDs (getBoundaryIDs diagram)
validateFlowIDs diagram nodeIDs
return diagram
| null | https://raw.githubusercontent.com/sonyxperiadev/dataflow/8bef5bd6bf96a918197e66ad9d675ff8cd2a4e33/src/DataFlow/Validation.hs | haskell | module DataFlow.Validation (
ValidationError(..),
validate
) where
import Data.Set (Set, member, insert, empty)
import Text.Printf
import DataFlow.Core
data ValidationError = UnknownID ID
| DuplicateDeclaration ID
deriving (Eq)
instance Show ValidationError where
show (UnknownID i) = printf "Unknown ID: %s" i
show (DuplicateDeclaration i) = printf "Duplicate declaration of ID: %s" i
getNodeIDs :: Diagram -> [ID]
getNodeIDs (Diagram _ nodes _) = concatMap getRootNodeId nodes
where getId (InputOutput i _) = [i]
getId (Function i _) = [i]
getId (Database i _) = [i]
getRootNodeId (Node node) = getId node
getRootNodeId (TrustBoundary _ _ nodes) = concatMap getId nodes
getBoundaryIDs :: Diagram -> [ID]
getBoundaryIDs (Diagram _ nodes _) = concatMap getRootNodeId nodes
where getRootNodeId (TrustBoundary id _ _) = [id]
getRootNodeId _ = []
validateDuplicateIDs :: [ID] -> Either [ValidationError] (Set ID)
validateDuplicateIDs ids =
case foldl iter (empty, []) ids of
(seen, []) -> Right seen
(_, errors) -> Left errors
where iter (seen, errors) i = if i `member` seen
then (seen, errors ++ [DuplicateDeclaration i])
else (insert i seen, errors)
validateFlowIDs :: Diagram -> Set ID -> Either [ValidationError] ()
validateFlowIDs (Diagram _ _ flows) ids =
case foldl iter [] flows of
[] -> Right ()
errors -> Left errors
where idError i = if i `member` ids then [] else [UnknownID i]
iter errors (Flow source target _) =
errors ++ idError source ++ idError target
validate :: Diagram -> Either [ValidationError] Diagram
validate diagram = do
nodeIDs <- validateDuplicateIDs (getNodeIDs diagram)
validateDuplicateIDs (getBoundaryIDs diagram)
validateFlowIDs diagram nodeIDs
return diagram
| |
ed85c45c67a77aa09e87dc4621d7ab47ef60dda23a0b1051870c2f9bbe01dbc8 | BrunoBonacci/1config | project.clj | (defn ver [] (-> "../ver/1config.version" slurp .trim))
(defn java-version
"It returns the current Java major version as a number"
[]
(as-> (System/getProperty "java.version") $
(str/split $ #"\.")
(if (= "1" (first $)) (second $) (first $))
(Integer/parseInt $)))
(defproject com.brunobonacci/oneconfig-cli #=(ver)
:description "A command line utility for managing 1config configurations"
:url ""
:license {:name "Apache License 2.0"
:url "-2.0"}
:scm {:name "git" :url ""}
:main com.brunobonacci.oneconfig.main
:dependencies [[org.clojure/clojure "1.11.1"]
[com.brunobonacci/oneconfig #=(ver)]
[org.clojure/tools.cli "1.0.206"]
[ch.qos.logback/logback-classic "1.2.11"]
[com.brunobonacci/safely "0.5.0"]
[com.github.clj-easy/graal-build-time "0.1.4"]]
:global-vars {*warn-on-reflection* true}
:jvm-opts ~(if (>= (java-version) 9)
Illegal reflective access by com.fasterxml.jackson.databind.util . ClassUtil
to method java.lang . Throwable.setCause(java.lang . Throwable )
(vector "--add-opens" "java.base/java.lang=ALL-UNNAMED" "-server")
(vector "-server"))
:java-source-paths ["java/src"]
:javac-options ["-target" "1.8" "-source" "1.8" ]
:resource-paths ["resources" "../ver" ]
:bin {:name "1cfgx"
:jvm-opts ["-server" "$JVM_OPTS" "-Dfile.encoding=utf-8"]}
:profiles {:uberjar {:aot :all}
:dev {:dependencies [[midje "1.10.5"]
[org.clojure/test.check "1.1.1"]
[criterium "0.4.6"]]
:resource-paths ["dev-resources"]
:plugins [[lein-midje "3.2.2"]
[lein-shell "0.5.0"]
[lein-binplus "0.6.6"]]}}
:aliases
{
"test"
["midje"]
"native-config"
["shell"
;; run the application to infer the build configuration
"../test/bin/end-2-end-test.sh" "graalvm-config"]
"native"
["shell" "./bin/native-image-build.sh" "."]
assumes container on with /tmp shared with
"native-linux"
["do"
["shell" "mkdir" "-p" "/tmp/1cfg-build/target/"]
["shell" "cp" "./target/${:uberjar-name:-${:name}-${:version}-standalone.jar}" "/tmp/1cfg-build/target/"]
["shell" "cp" "-r" "./graalvm-config" "/tmp/1cfg-build/"]
["shell" "docker" "run" "--platform=linux/amd64" "-v" "/tmp/1cfg-build:/1config" "findepi/graalvm:22.1.0-java17-native"
"/bin/bash" "-c"
"find /1config ; /graalvm/bin/native-image -H:-CheckToolchain --report-unsupported-elements-at-runtime --no-server --no-fallback -H:ConfigurationFileDirectories=/1config/graalvm-config/ --allow-incomplete-classpath --enable-http --enable-https --enable-all-security-services -jar /1config/target/${:uberjar-name:-${:name}-${:version}-standalone.jar} -H:Name=/1config/target/1cfg-Linux"]
["shell" "cp" "/tmp/1cfg-build/target/1cfg-Linux" "./target/"]]
}
)
| null | https://raw.githubusercontent.com/BrunoBonacci/1config/571fadb65067ac2812183632ae1d3fd07ab511a8/1config-cli/project.clj | clojure | run the application to infer the build configuration | (defn ver [] (-> "../ver/1config.version" slurp .trim))
(defn java-version
"It returns the current Java major version as a number"
[]
(as-> (System/getProperty "java.version") $
(str/split $ #"\.")
(if (= "1" (first $)) (second $) (first $))
(Integer/parseInt $)))
(defproject com.brunobonacci/oneconfig-cli #=(ver)
:description "A command line utility for managing 1config configurations"
:url ""
:license {:name "Apache License 2.0"
:url "-2.0"}
:scm {:name "git" :url ""}
:main com.brunobonacci.oneconfig.main
:dependencies [[org.clojure/clojure "1.11.1"]
[com.brunobonacci/oneconfig #=(ver)]
[org.clojure/tools.cli "1.0.206"]
[ch.qos.logback/logback-classic "1.2.11"]
[com.brunobonacci/safely "0.5.0"]
[com.github.clj-easy/graal-build-time "0.1.4"]]
:global-vars {*warn-on-reflection* true}
:jvm-opts ~(if (>= (java-version) 9)
Illegal reflective access by com.fasterxml.jackson.databind.util . ClassUtil
to method java.lang . Throwable.setCause(java.lang . Throwable )
(vector "--add-opens" "java.base/java.lang=ALL-UNNAMED" "-server")
(vector "-server"))
:java-source-paths ["java/src"]
:javac-options ["-target" "1.8" "-source" "1.8" ]
:resource-paths ["resources" "../ver" ]
:bin {:name "1cfgx"
:jvm-opts ["-server" "$JVM_OPTS" "-Dfile.encoding=utf-8"]}
:profiles {:uberjar {:aot :all}
:dev {:dependencies [[midje "1.10.5"]
[org.clojure/test.check "1.1.1"]
[criterium "0.4.6"]]
:resource-paths ["dev-resources"]
:plugins [[lein-midje "3.2.2"]
[lein-shell "0.5.0"]
[lein-binplus "0.6.6"]]}}
:aliases
{
"test"
["midje"]
"native-config"
["shell"
"../test/bin/end-2-end-test.sh" "graalvm-config"]
"native"
["shell" "./bin/native-image-build.sh" "."]
assumes container on with /tmp shared with
"native-linux"
["do"
["shell" "mkdir" "-p" "/tmp/1cfg-build/target/"]
["shell" "cp" "./target/${:uberjar-name:-${:name}-${:version}-standalone.jar}" "/tmp/1cfg-build/target/"]
["shell" "cp" "-r" "./graalvm-config" "/tmp/1cfg-build/"]
["shell" "docker" "run" "--platform=linux/amd64" "-v" "/tmp/1cfg-build:/1config" "findepi/graalvm:22.1.0-java17-native"
"/bin/bash" "-c"
"find /1config ; /graalvm/bin/native-image -H:-CheckToolchain --report-unsupported-elements-at-runtime --no-server --no-fallback -H:ConfigurationFileDirectories=/1config/graalvm-config/ --allow-incomplete-classpath --enable-http --enable-https --enable-all-security-services -jar /1config/target/${:uberjar-name:-${:name}-${:version}-standalone.jar} -H:Name=/1config/target/1cfg-Linux"]
["shell" "cp" "/tmp/1cfg-build/target/1cfg-Linux" "./target/"]]
}
)
|
bb5ef96d03b2c82bba86ed263dce1814ad60ba3ab85c3094984fc66d38e87402 | jaspervdj/websockets | Types.hs | --------------------------------------------------------------------------------
-- | Primary types
{-# LANGUAGE DeriveDataTypeable #-}
module Network.WebSockets.Types
( Message (..)
, ControlMessage (..)
, DataMessage (..)
, WebSocketsData (..)
, HandshakeException (..)
, ConnectionException (..)
, ConnectionType (..)
, decodeUtf8Lenient
, decodeUtf8Strict
) where
--------------------------------------------------------------------------------
import Control.Exception (Exception (..))
import Control.Exception (throw, try)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Encoding.Error as TL
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import Data.Typeable (Typeable)
import Data.Word (Word16)
import System.IO.Unsafe (unsafePerformIO)
--------------------------------------------------------------------------------
import Network.WebSockets.Http
--------------------------------------------------------------------------------
-- | The kind of message a server application typically deals with
data Message
= ControlMessage ControlMessage
-- | Reserved bits, actual message
| DataMessage Bool Bool Bool DataMessage
deriving (Eq, Show)
--------------------------------------------------------------------------------
-- | Different control messages
data ControlMessage
= Close Word16 BL.ByteString
| Ping BL.ByteString
| Pong BL.ByteString
deriving (Eq, Show)
--------------------------------------------------------------------------------
-- | For an end-user of this library, dealing with 'Frame's would be a bit
-- low-level. This is why define another type on top of it, which represents
-- data for the application layer.
--
There are currently two kinds of data messages supported by the WebSockets
-- protocol:
--
* Textual UTF-8 encoded data . This corresponds roughly to sending a
in JavaScript .
--
-- * Binary data. This corresponds roughly to send an ArrayBuffer in
JavaScript .
data DataMessage
| A textual message . The second field /might/ contain the decoded UTF-8
-- text for caching reasons. This field is computed lazily so if it's not
-- accessed, it should have no performance impact.
= Text BL.ByteString (Maybe TL.Text)
-- | A binary message.
| Binary BL.ByteString
deriving (Eq, Show)
--------------------------------------------------------------------------------
-- | In order to have an even more high-level API, we define a typeclass for
-- values the user can receive from and send to the socket. A few warnings
-- apply:
--
-- * Natively, everything is represented as a 'BL.ByteString', so this is the
-- fastest instance
--
* You should only use the ' TL.Text ' or the ' T.Text ' instance when you are
sure that the data is UTF-8 encoded ( which is the case for ' Text '
-- messages).
--
-- * Messages can be very large. If this is the case, it might be inefficient to
-- use the strict 'B.ByteString' and 'T.Text' instances.
class WebSocketsData a where
fromDataMessage :: DataMessage -> a
fromLazyByteString :: BL.ByteString -> a
toLazyByteString :: a -> BL.ByteString
--------------------------------------------------------------------------------
instance WebSocketsData BL.ByteString where
fromDataMessage (Text bl _) = bl
fromDataMessage (Binary bl) = bl
fromLazyByteString = id
toLazyByteString = id
--------------------------------------------------------------------------------
instance WebSocketsData B.ByteString where
fromDataMessage (Text bl _) = fromLazyByteString bl
fromDataMessage (Binary bl) = fromLazyByteString bl
fromLazyByteString = B.concat . BL.toChunks
toLazyByteString = BL.fromChunks . return
--------------------------------------------------------------------------------
instance WebSocketsData TL.Text where
fromDataMessage (Text _ (Just tl)) = tl
fromDataMessage (Text bl Nothing) = fromLazyByteString bl
fromDataMessage (Binary bl) = fromLazyByteString bl
fromLazyByteString = TL.decodeUtf8
toLazyByteString = TL.encodeUtf8
--------------------------------------------------------------------------------
instance WebSocketsData T.Text where
fromDataMessage (Text _ (Just tl)) = T.concat (TL.toChunks tl)
fromDataMessage (Text bl Nothing) = fromLazyByteString bl
fromDataMessage (Binary bl) = fromLazyByteString bl
fromLazyByteString = T.concat . TL.toChunks . fromLazyByteString
toLazyByteString = toLazyByteString . TL.fromChunks . return
--------------------------------------------------------------------------------
-- | Various exceptions that can occur while receiving or transmitting messages
data ConnectionException
-- | The peer has requested that the connection be closed, and included
-- a close code and a reason for closing. When receiving this exception,
-- no more messages can be sent. Also, the server is responsible for
-- closing the TCP connection once this exception is received.
--
-- See <#section-7.4> for a list of close
-- codes.
= CloseRequest Word16 BL.ByteString
-- | The peer unexpectedly closed the connection while we were trying to
-- receive some data. This is a violation of the websocket RFC since the
-- TCP connection should only be closed after sending and receiving close
-- control messages.
| ConnectionClosed
| The client sent garbage , i.e. we could not parse the WebSockets stream .
| ParseException String
| The client sent invalid UTF-8 . Note that this exception will only be
-- thrown if strict decoding is set in the connection options.
| UnicodeException String
deriving (Eq, Show, Typeable)
--------------------------------------------------------------------------------
instance Exception ConnectionException
--------------------------------------------------------------------------------
data ConnectionType = ServerConnection | ClientConnection
deriving (Eq, Ord, Show)
--------------------------------------------------------------------------------
| Replace an invalid input byte with the Unicode replacement character
-- U+FFFD.
decodeUtf8Lenient :: BL.ByteString -> TL.Text
decodeUtf8Lenient = TL.decodeUtf8With TL.lenientDecode
--------------------------------------------------------------------------------
-- | Throw an error if there is an invalid input byte.
decodeUtf8Strict :: BL.ByteString -> Either ConnectionException TL.Text
decodeUtf8Strict bl = unsafePerformIO $ try $
let txt = TL.decodeUtf8With (\err _ -> throw (UnicodeException err)) bl in
TL.length txt `seq` return txt
| null | https://raw.githubusercontent.com/jaspervdj/websockets/95dc7159322c8a60cbbbf0911571aef83673ec88/src/Network/WebSockets/Types.hs | haskell | ------------------------------------------------------------------------------
| Primary types
# LANGUAGE DeriveDataTypeable #
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| The kind of message a server application typically deals with
| Reserved bits, actual message
------------------------------------------------------------------------------
| Different control messages
------------------------------------------------------------------------------
| For an end-user of this library, dealing with 'Frame's would be a bit
low-level. This is why define another type on top of it, which represents
data for the application layer.
protocol:
* Binary data. This corresponds roughly to send an ArrayBuffer in
text for caching reasons. This field is computed lazily so if it's not
accessed, it should have no performance impact.
| A binary message.
------------------------------------------------------------------------------
| In order to have an even more high-level API, we define a typeclass for
values the user can receive from and send to the socket. A few warnings
apply:
* Natively, everything is represented as a 'BL.ByteString', so this is the
fastest instance
messages).
* Messages can be very large. If this is the case, it might be inefficient to
use the strict 'B.ByteString' and 'T.Text' instances.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Various exceptions that can occur while receiving or transmitting messages
| The peer has requested that the connection be closed, and included
a close code and a reason for closing. When receiving this exception,
no more messages can be sent. Also, the server is responsible for
closing the TCP connection once this exception is received.
See <#section-7.4> for a list of close
codes.
| The peer unexpectedly closed the connection while we were trying to
receive some data. This is a violation of the websocket RFC since the
TCP connection should only be closed after sending and receiving close
control messages.
thrown if strict decoding is set in the connection options.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
U+FFFD.
------------------------------------------------------------------------------
| Throw an error if there is an invalid input byte. | module Network.WebSockets.Types
( Message (..)
, ControlMessage (..)
, DataMessage (..)
, WebSocketsData (..)
, HandshakeException (..)
, ConnectionException (..)
, ConnectionType (..)
, decodeUtf8Lenient
, decodeUtf8Strict
) where
import Control.Exception (Exception (..))
import Control.Exception (throw, try)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Encoding.Error as TL
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import Data.Typeable (Typeable)
import Data.Word (Word16)
import System.IO.Unsafe (unsafePerformIO)
import Network.WebSockets.Http
data Message
= ControlMessage ControlMessage
| DataMessage Bool Bool Bool DataMessage
deriving (Eq, Show)
data ControlMessage
= Close Word16 BL.ByteString
| Ping BL.ByteString
| Pong BL.ByteString
deriving (Eq, Show)
There are currently two kinds of data messages supported by the WebSockets
* Textual UTF-8 encoded data . This corresponds roughly to sending a
in JavaScript .
JavaScript .
data DataMessage
| A textual message . The second field /might/ contain the decoded UTF-8
= Text BL.ByteString (Maybe TL.Text)
| Binary BL.ByteString
deriving (Eq, Show)
* You should only use the ' TL.Text ' or the ' T.Text ' instance when you are
sure that the data is UTF-8 encoded ( which is the case for ' Text '
class WebSocketsData a where
fromDataMessage :: DataMessage -> a
fromLazyByteString :: BL.ByteString -> a
toLazyByteString :: a -> BL.ByteString
instance WebSocketsData BL.ByteString where
fromDataMessage (Text bl _) = bl
fromDataMessage (Binary bl) = bl
fromLazyByteString = id
toLazyByteString = id
instance WebSocketsData B.ByteString where
fromDataMessage (Text bl _) = fromLazyByteString bl
fromDataMessage (Binary bl) = fromLazyByteString bl
fromLazyByteString = B.concat . BL.toChunks
toLazyByteString = BL.fromChunks . return
instance WebSocketsData TL.Text where
fromDataMessage (Text _ (Just tl)) = tl
fromDataMessage (Text bl Nothing) = fromLazyByteString bl
fromDataMessage (Binary bl) = fromLazyByteString bl
fromLazyByteString = TL.decodeUtf8
toLazyByteString = TL.encodeUtf8
instance WebSocketsData T.Text where
fromDataMessage (Text _ (Just tl)) = T.concat (TL.toChunks tl)
fromDataMessage (Text bl Nothing) = fromLazyByteString bl
fromDataMessage (Binary bl) = fromLazyByteString bl
fromLazyByteString = T.concat . TL.toChunks . fromLazyByteString
toLazyByteString = toLazyByteString . TL.fromChunks . return
data ConnectionException
= CloseRequest Word16 BL.ByteString
| ConnectionClosed
| The client sent garbage , i.e. we could not parse the WebSockets stream .
| ParseException String
| The client sent invalid UTF-8 . Note that this exception will only be
| UnicodeException String
deriving (Eq, Show, Typeable)
instance Exception ConnectionException
data ConnectionType = ServerConnection | ClientConnection
deriving (Eq, Ord, Show)
| Replace an invalid input byte with the Unicode replacement character
decodeUtf8Lenient :: BL.ByteString -> TL.Text
decodeUtf8Lenient = TL.decodeUtf8With TL.lenientDecode
decodeUtf8Strict :: BL.ByteString -> Either ConnectionException TL.Text
decodeUtf8Strict bl = unsafePerformIO $ try $
let txt = TL.decodeUtf8With (\err _ -> throw (UnicodeException err)) bl in
TL.length txt `seq` return txt
|
dec1d6807b0e49f61b192b5f4a584b69cb88415105ae0b562a74c673beaee607 | cartazio/tlaps | module.mli |
* Copyright ( C ) 2011 INRIA and Microsoft Corporation
* Copyright (C) 2011 INRIA and Microsoft Corporation
*)
module T : sig
open Property;;
open Util;;
open Expr.T;;
open Proof.T;;
type mule = mule_ wrapped
and mule_ = {
name : hint ;
extendees : hint list ;
instancees : hint list ;
only external instancees
body : modunit list ;
defdepth : int ;
mutable stage : stage ;
mutable important : bool
}
and modunit = modunit_ wrapped
and modunit_ =
| Constants of (hint * shape) list
| Recursives of (hint * shape) list
| Variables of hint list
| Definition of defn * wheredef * visibility * export
| Axiom of hint option * expr
| Theorem of hint option * sequent * int * proof * proof * summary
| Submod of mule
| Mutate of [`Use of bool | `Hide] * usable
| Anoninst of instance * export
and named = Named | Anonymous
and summary = {
sum_total : int ;
sum_absent : int * Loc.locus list ;
sum_omitted : int * Loc.locus list ;
sum_suppressed : int * Loc.locus list ;
}
and stage =
| Special
| Parsed | Flat
| Final of final
and final = { final_named : modunit list
; final_obs : obligation array
; final_status : status * summary
}
and status =
| Unchecked | Proved | Certified | Incomplete
;;
type modctx = mule Coll.Sm.t;;
val empty_summary : summary;;
val cat_summary : summary -> summary -> summary;;
val hyps_of_modunit : modunit -> Expr.T.hyp_ Property.wrapped list;;
val hyp_size : modunit -> int;;
val salt_prop : unit Property.pfuncs;;
end;;
module Fmt : sig
open Ctx
open T
val pp_print_modunit :
?force:bool -> Expr.Fmt.ctx -> Format.formatter -> modunit -> Expr.Fmt.ctx
;;
val pp_print_module :
?force:bool -> Expr.Fmt.ctx -> Format.formatter -> mule -> unit
;;
val pp_print_modctx : Format.formatter -> modctx -> unit;;
val summary : mule -> unit;;
end;;
module Standard : sig
open T
val tlapm : mule
val naturals : mule
val integers : mule
val reals : mule
val sequences : mule
val tlc : mule
val initctx : modctx
end;;
module Gen : sig
open Proof.T
open T
val generate : Expr.T.hyp Deque.dq -> mule -> mule * obligation list * summary
end;;
module Flatten : sig
val flatten :
T.modctx -> T.mule -> Util.Coll.Ss.t ->
(T.mule_ Property.wrapped * Util.Coll.Ss.t)
;;
end;;
module Elab : sig
open Proof.T
open T
val normalize :
modctx -> Expr.T.hyp Deque.dq -> mule -> modctx * mule * summary
;;
end;;
module Dep : sig
val external_deps : T.mule_ Property.wrapped -> Util.Coll.Hs.t;;
val schedule : T.modctx -> T.modctx * T.mule list;;
end;;
module Save : sig
open T
val parse_file : ?clock:Timing.clock -> Util.hint -> mule
val store_module : ?clock:Timing.clock -> mule -> unit
val complete_load : ?clock:Timing.clock -> ?root:string -> modctx -> modctx
end;;
module Parser : sig
open Tla_parser
open T
val parse : mule lprs
end;;
module Globalness : sig
open T
val is_global : 'a Property.wrapped -> bool
val globalness : mule -> mule
end;;
| null | https://raw.githubusercontent.com/cartazio/tlaps/562a34c066b636da7b921ae30fc5eacf83608280/src/module.mli | ocaml |
* Copyright ( C ) 2011 INRIA and Microsoft Corporation
* Copyright (C) 2011 INRIA and Microsoft Corporation
*)
module T : sig
open Property;;
open Util;;
open Expr.T;;
open Proof.T;;
type mule = mule_ wrapped
and mule_ = {
name : hint ;
extendees : hint list ;
instancees : hint list ;
only external instancees
body : modunit list ;
defdepth : int ;
mutable stage : stage ;
mutable important : bool
}
and modunit = modunit_ wrapped
and modunit_ =
| Constants of (hint * shape) list
| Recursives of (hint * shape) list
| Variables of hint list
| Definition of defn * wheredef * visibility * export
| Axiom of hint option * expr
| Theorem of hint option * sequent * int * proof * proof * summary
| Submod of mule
| Mutate of [`Use of bool | `Hide] * usable
| Anoninst of instance * export
and named = Named | Anonymous
and summary = {
sum_total : int ;
sum_absent : int * Loc.locus list ;
sum_omitted : int * Loc.locus list ;
sum_suppressed : int * Loc.locus list ;
}
and stage =
| Special
| Parsed | Flat
| Final of final
and final = { final_named : modunit list
; final_obs : obligation array
; final_status : status * summary
}
and status =
| Unchecked | Proved | Certified | Incomplete
;;
type modctx = mule Coll.Sm.t;;
val empty_summary : summary;;
val cat_summary : summary -> summary -> summary;;
val hyps_of_modunit : modunit -> Expr.T.hyp_ Property.wrapped list;;
val hyp_size : modunit -> int;;
val salt_prop : unit Property.pfuncs;;
end;;
module Fmt : sig
open Ctx
open T
val pp_print_modunit :
?force:bool -> Expr.Fmt.ctx -> Format.formatter -> modunit -> Expr.Fmt.ctx
;;
val pp_print_module :
?force:bool -> Expr.Fmt.ctx -> Format.formatter -> mule -> unit
;;
val pp_print_modctx : Format.formatter -> modctx -> unit;;
val summary : mule -> unit;;
end;;
module Standard : sig
open T
val tlapm : mule
val naturals : mule
val integers : mule
val reals : mule
val sequences : mule
val tlc : mule
val initctx : modctx
end;;
module Gen : sig
open Proof.T
open T
val generate : Expr.T.hyp Deque.dq -> mule -> mule * obligation list * summary
end;;
module Flatten : sig
val flatten :
T.modctx -> T.mule -> Util.Coll.Ss.t ->
(T.mule_ Property.wrapped * Util.Coll.Ss.t)
;;
end;;
module Elab : sig
open Proof.T
open T
val normalize :
modctx -> Expr.T.hyp Deque.dq -> mule -> modctx * mule * summary
;;
end;;
module Dep : sig
val external_deps : T.mule_ Property.wrapped -> Util.Coll.Hs.t;;
val schedule : T.modctx -> T.modctx * T.mule list;;
end;;
module Save : sig
open T
val parse_file : ?clock:Timing.clock -> Util.hint -> mule
val store_module : ?clock:Timing.clock -> mule -> unit
val complete_load : ?clock:Timing.clock -> ?root:string -> modctx -> modctx
end;;
module Parser : sig
open Tla_parser
open T
val parse : mule lprs
end;;
module Globalness : sig
open T
val is_global : 'a Property.wrapped -> bool
val globalness : mule -> mule
end;;
| |
a9bd32dacea42878a5fe836b4d78912a6a874002bec0015ff0f9cdf3e2a54316 | yoshiquest/forge-clj | ui.clj | (ns forge-clj.client.ui
"Contains the client side ui macros."
(:require
[forge-clj.core :refer [defclass]])
(:import
[net.minecraft.client.gui.inventory GuiContainer]))
(defmacro defguicontainer
"DEFCLASS: Given a class name and classdata, creates a class extending GuiContainer.
Remember to create implementations of drawGuiContainerBackgroundLayer and
drawGuiContainerForegroundLayer or this will break!"
[class-name & args]
(let [classdata (apply hash-map args)]
`(defclass GuiContainer ~class-name ~classdata)))
| null | https://raw.githubusercontent.com/yoshiquest/forge-clj/9ead6fcf9efc30ec0f0685562526ff7400c5cd3a/src/main/clojure/forge_clj/client/ui.clj | clojure | (ns forge-clj.client.ui
"Contains the client side ui macros."
(:require
[forge-clj.core :refer [defclass]])
(:import
[net.minecraft.client.gui.inventory GuiContainer]))
(defmacro defguicontainer
"DEFCLASS: Given a class name and classdata, creates a class extending GuiContainer.
Remember to create implementations of drawGuiContainerBackgroundLayer and
drawGuiContainerForegroundLayer or this will break!"
[class-name & args]
(let [classdata (apply hash-map args)]
`(defclass GuiContainer ~class-name ~classdata)))
| |
80202b5f0bc44efe8bbcf5aca12207b34dd73251b1e577d7f0405a53839fa082 | expipiplus1/vulkan | VK_NV_ray_tracing_motion_blur.hs | {-# language CPP #-}
-- | = Name
--
-- VK_NV_ray_tracing_motion_blur - device extension
--
-- == VK_NV_ray_tracing_motion_blur
--
-- [__Name String__]
@VK_NV_ray_tracing_motion_blur@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
328
--
-- [__Revision__]
1
--
-- [__Extension and Version Dependencies__]
--
- Requires support for Vulkan 1.0
--
-- - Requires @VK_KHR_ray_tracing_pipeline@ to be enabled for any
-- device-level functionality
--
-- [__Contact__]
--
-
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
2021 - 06 - 16
--
-- [__Interactions and External Dependencies__]
--
-- - This extension requires
< >
--
-- - This extension provides API support for
-- < GL_NV_ray_tracing_motion_blur>
--
-- [__Contributors__]
--
- , NVIDIA
--
- , NVIDIA
--
-- == Description
--
tracing support in the API provides an efficient mechanism to
-- intersect rays against static geometry, but rendering algorithms often
-- want to support motion, which is more efficiently supported with
-- motion-specific algorithms. This extension adds a set of mechanisms to
-- support fast tracing of moving geometry:
--
-- - A ray pipeline trace call which takes a time parameter
--
-- - Flags to enable motion support in an acceleration structure
--
-- - Support for time-varying vertex positions in a geometry
--
-- - Motion instances to move existing instances over time
--
-- The motion represented here is parameterized across a normalized
timestep between 0.0 and 1.0 . A motion trace using @OpTraceRayMotionNV@
-- provides a time within that normalized range to be used when
-- intersecting that ray with geometry. The geometry can be provided with
motion by a combination of adding a second vertex position for time of
1.0 using ' AccelerationStructureGeometryMotionTrianglesDataNV ' and
-- providing multiple transforms in the instance using
-- 'AccelerationStructureMotionInstanceNV'.
--
-- == New Structures
--
-- - 'AccelerationStructureMatrixMotionInstanceNV'
--
-- - 'AccelerationStructureMotionInstanceNV'
--
- ' AccelerationStructureSRTMotionInstanceNV '
--
-- - 'SRTDataNV'
--
-- - Extending
' Vulkan . Extensions . VK_KHR_acceleration_structure . AccelerationStructureCreateInfoKHR ' :
--
-- - 'AccelerationStructureMotionInfoNV'
--
-- - Extending
' Vulkan . Extensions . VK_KHR_acceleration_structure . AccelerationStructureGeometryTrianglesDataKHR ' :
--
- ' AccelerationStructureGeometryMotionTrianglesDataNV '
--
-- - Extending
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 ' ,
' Vulkan . Core10.Device . DeviceCreateInfo ' :
--
-- - 'PhysicalDeviceRayTracingMotionBlurFeaturesNV'
--
-- == New Unions
--
-- - 'AccelerationStructureMotionInstanceDataNV'
--
-- == New Enums
--
-- - 'AccelerationStructureMotionInstanceTypeNV'
--
-- == New Bitmasks
--
- ' '
--
- ' AccelerationStructureMotionInstanceFlagsNV '
--
-- == New Enum Constants
--
-- - 'NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME'
--
-- - 'NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION'
--
-- - Extending
' Vulkan . Extensions . VK_KHR_acceleration_structure . AccelerationStructureCreateFlagBitsKHR ' :
--
- ' Vulkan . Extensions . VK_KHR_acceleration_structure . ACCELERATION_STRUCTURE_CREATE_MOTION_BIT_NV '
--
-- - Extending
' Vulkan . Extensions . VK_KHR_acceleration_structure . BuildAccelerationStructureFlagBitsKHR ' :
--
- ' Vulkan . Extensions . VK_KHR_acceleration_structure . '
--
-- - Extending
' Vulkan . Core10.Enums . PipelineCreateFlagBits . ' :
--
- ' Vulkan . Core10.Enums . PipelineCreateFlagBits . PIPELINE_CREATE_RAY_TRACING_ALLOW_MOTION_BIT_NV '
--
- Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' :
--
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_MOTION_TRIANGLES_DATA_NV '
--
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MOTION_INFO_NV '
--
- ' Vulkan . Core10.Enums . StructureType . '
--
-- == Issues
--
( 1 ) What size is VkAccelerationStructureMotionInstanceNV ?
--
-- - Added a note on the structure size and made the stride explicit in
-- the language.
--
( 2 ) Allow arrayOfPointers for motion ?
--
-- - Yes, with a packed encoding to minimize the amount of data sent for
-- metadata.
--
-- == Version History
--
- Revision 1 , 2020 - 06 - 16 ( , )
--
-- - Initial external release
--
-- == See Also
--
-- 'AccelerationStructureGeometryMotionTrianglesDataNV',
-- 'AccelerationStructureMatrixMotionInstanceNV',
' ' ,
-- 'AccelerationStructureMotionInfoNV',
-- 'AccelerationStructureMotionInstanceDataNV',
-- 'AccelerationStructureMotionInstanceFlagsNV',
-- 'AccelerationStructureMotionInstanceNV',
-- 'AccelerationStructureMotionInstanceTypeNV',
' AccelerationStructureSRTMotionInstanceNV ' ,
-- 'PhysicalDeviceRayTracingMotionBlurFeaturesNV', 'SRTDataNV'
--
-- == Document Notes
--
-- For more information, see the
< -extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur Vulkan Specification >
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_NV_ray_tracing_motion_blur ( PhysicalDeviceRayTracingMotionBlurFeaturesNV(..)
, AccelerationStructureGeometryMotionTrianglesDataNV(..)
, AccelerationStructureMotionInfoNV(..)
, SRTDataNV(..)
, AccelerationStructureSRTMotionInstanceNV(..)
, AccelerationStructureMatrixMotionInstanceNV(..)
, AccelerationStructureMotionInstanceNV(..)
, AccelerationStructureMotionInstanceDataNV(..)
, AccelerationStructureMotionInfoFlagsNV(..)
, AccelerationStructureMotionInstanceFlagsNV(..)
, AccelerationStructureMotionInstanceTypeNV( ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_STATIC_NV
, ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_MATRIX_MOTION_NV
, ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV
, ..
)
, NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION
, pattern NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION
, NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME
, pattern NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME
, TransformMatrixKHR(..)
, AccelerationStructureInstanceKHR(..)
, DeviceOrHostAddressConstKHR(..)
, GeometryInstanceFlagBitsKHR(..)
, GeometryInstanceFlagsKHR
, BuildAccelerationStructureFlagBitsKHR(..)
, BuildAccelerationStructureFlagsKHR
, AccelerationStructureCreateFlagBitsKHR(..)
, AccelerationStructureCreateFlagsKHR
) where
import Data.Bits (Bits)
import Data.Bits (FiniteBits)
import Data.Bits (shiftL)
import Data.Bits (shiftR)
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import Control.Exception.Base (bracket)
import Data.Bits ((.&.))
import Data.Bits ((.|.))
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Marshal.Alloc (callocBytes)
import Foreign.Marshal.Alloc (free)
import GHC.Ptr (castPtr)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import GHC.Show (showString)
import GHC.Show (showsPrec)
import Numeric (showHex)
import Data.Coerce (coerce)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import Control.Monad.Trans.Cont (runContT)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero)
import Vulkan.Zero (Zero(..))
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.C.Types (CFloat)
import Foreign.C.Types (CFloat(..))
import Foreign.C.Types (CFloat(CFloat))
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import Data.Int (Int32)
import Foreign.Ptr (Ptr)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Data.Word (Word32)
import Data.Word (Word64)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.Extensions.VK_KHR_acceleration_structure (AccelerationStructureInstanceKHR)
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Extensions.VK_KHR_acceleration_structure (DeviceOrHostAddressConstKHR)
import Vulkan.Core10.FundamentalTypes (Flags)
import Vulkan.Extensions.VK_KHR_acceleration_structure (GeometryInstanceFlagsKHR)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Extensions.VK_KHR_acceleration_structure (TransformMatrixKHR)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_MOTION_TRIANGLES_DATA_NV))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MOTION_INFO_NV))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_MOTION_BLUR_FEATURES_NV))
import Vulkan.Extensions.VK_KHR_acceleration_structure (AccelerationStructureCreateFlagBitsKHR(..))
import Vulkan.Extensions.VK_KHR_acceleration_structure (AccelerationStructureCreateFlagsKHR)
import Vulkan.Extensions.VK_KHR_acceleration_structure (AccelerationStructureInstanceKHR(..))
import Vulkan.Extensions.VK_KHR_acceleration_structure (BuildAccelerationStructureFlagBitsKHR(..))
import Vulkan.Extensions.VK_KHR_acceleration_structure (BuildAccelerationStructureFlagsKHR)
import Vulkan.Extensions.VK_KHR_acceleration_structure (DeviceOrHostAddressConstKHR(..))
import Vulkan.Extensions.VK_KHR_acceleration_structure (GeometryInstanceFlagBitsKHR(..))
import Vulkan.Extensions.VK_KHR_acceleration_structure (GeometryInstanceFlagsKHR)
import Vulkan.Extensions.VK_KHR_acceleration_structure (TransformMatrixKHR(..))
-- | VkPhysicalDeviceRayTracingMotionBlurFeaturesNV - Structure describing
-- the ray tracing motion blur features that can be supported by an
-- implementation
--
-- = Members
--
-- This structure describes the following features:
--
-- = Description
--
-- If the 'PhysicalDeviceRayTracingMotionBlurFeaturesNV' structure is
-- included in the @pNext@ chain of the
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 '
-- structure passed to
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2 ' ,
-- it is filled in to indicate whether each corresponding feature is
supported . ' PhysicalDeviceRayTracingMotionBlurFeaturesNV ' also be
used in the @pNext@ chain of ' Vulkan . Core10.Device . DeviceCreateInfo ' to
-- selectively enable these features.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
' Vulkan . Core10.FundamentalTypes . Bool32 ' ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data PhysicalDeviceRayTracingMotionBlurFeaturesNV = PhysicalDeviceRayTracingMotionBlurFeaturesNV
| # features - rayTracingMotionBlur # @rayTracingMotionBlur@ indicates whether
-- the implementation supports the motion blur feature.
rayTracingMotionBlur :: Bool
, -- | #features-rayTracingMotionBlurPipelineTraceRaysIndirect#
-- @rayTracingMotionBlurPipelineTraceRaysIndirect@ indicates whether the
-- implementation supports indirect ray tracing commands with the motion
-- blur feature enabled.
rayTracingMotionBlurPipelineTraceRaysIndirect :: Bool
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDeviceRayTracingMotionBlurFeaturesNV)
#endif
deriving instance Show PhysicalDeviceRayTracingMotionBlurFeaturesNV
instance ToCStruct PhysicalDeviceRayTracingMotionBlurFeaturesNV where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDeviceRayTracingMotionBlurFeaturesNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_MOTION_BLUR_FEATURES_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (rayTracingMotionBlur))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (rayTracingMotionBlurPipelineTraceRaysIndirect))
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_MOTION_BLUR_FEATURES_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct PhysicalDeviceRayTracingMotionBlurFeaturesNV where
peekCStruct p = do
rayTracingMotionBlur <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
rayTracingMotionBlurPipelineTraceRaysIndirect <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32))
pure $ PhysicalDeviceRayTracingMotionBlurFeaturesNV
(bool32ToBool rayTracingMotionBlur)
(bool32ToBool rayTracingMotionBlurPipelineTraceRaysIndirect)
instance Storable PhysicalDeviceRayTracingMotionBlurFeaturesNV where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDeviceRayTracingMotionBlurFeaturesNV where
zero = PhysicalDeviceRayTracingMotionBlurFeaturesNV
zero
zero
-- | VkAccelerationStructureGeometryMotionTrianglesDataNV - Structure
-- specifying vertex motion in a bottom-level acceleration structure
--
-- = Description
--
-- If 'AccelerationStructureGeometryMotionTrianglesDataNV' is included in
-- the @pNext@ chain of a
' Vulkan . Extensions . VK_KHR_acceleration_structure . AccelerationStructureGeometryTrianglesDataKHR '
-- structure, the basic vertex positions are used for the position of the
triangles in the geometry at time 0.0 and the @vertexData@ in
-- 'AccelerationStructureGeometryMotionTrianglesDataNV' is used for the
vertex positions at time 1.0 , with positions linearly interpolated at
-- intermediate times.
--
Indexing for ' AccelerationStructureGeometryMotionTrianglesDataNV '
@vertexData@ is equivalent to the basic vertex position data .
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
' Vulkan . Extensions . VK_KHR_acceleration_structure . DeviceOrHostAddressConstKHR ' ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data AccelerationStructureGeometryMotionTrianglesDataNV = AccelerationStructureGeometryMotionTrianglesDataNV
| @vertexData@ is a pointer to vertex data for this geometry at time 1.0
vertexData :: DeviceOrHostAddressConstKHR }
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (AccelerationStructureGeometryMotionTrianglesDataNV)
#endif
deriving instance Show AccelerationStructureGeometryMotionTrianglesDataNV
instance ToCStruct AccelerationStructureGeometryMotionTrianglesDataNV where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p AccelerationStructureGeometryMotionTrianglesDataNV{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_MOTION_TRIANGLES_DATA_NV)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
ContT $ pokeCStruct ((p `plusPtr` 16 :: Ptr DeviceOrHostAddressConstKHR)) (vertexData) . ($ ())
lift $ f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_MOTION_TRIANGLES_DATA_NV)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
ContT $ pokeCStruct ((p `plusPtr` 16 :: Ptr DeviceOrHostAddressConstKHR)) (zero) . ($ ())
lift $ f
instance Zero AccelerationStructureGeometryMotionTrianglesDataNV where
zero = AccelerationStructureGeometryMotionTrianglesDataNV
zero
-- | VkAccelerationStructureMotionInfoNV - Structure specifying the
-- parameters of a newly created acceleration structure object
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
' ' ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data AccelerationStructureMotionInfoNV = AccelerationStructureMotionInfoNV
| @maxInstances@ is the maximum number of instances that be used in
-- the motion top-level acceleration structure.
maxInstances :: Word32
, -- | @flags@ is 0 and reserved for future use.
--
-- #VUID-VkAccelerationStructureMotionInfoNV-flags-zerobitmask# @flags@
/must/ be @0@
flags :: AccelerationStructureMotionInfoFlagsNV
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (AccelerationStructureMotionInfoNV)
#endif
deriving instance Show AccelerationStructureMotionInfoNV
instance ToCStruct AccelerationStructureMotionInfoNV where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p AccelerationStructureMotionInfoNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MOTION_INFO_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Word32)) (maxInstances)
poke ((p `plusPtr` 20 :: Ptr AccelerationStructureMotionInfoFlagsNV)) (flags)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MOTION_INFO_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Word32)) (zero)
f
instance FromCStruct AccelerationStructureMotionInfoNV where
peekCStruct p = do
maxInstances <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32))
flags <- peek @AccelerationStructureMotionInfoFlagsNV ((p `plusPtr` 20 :: Ptr AccelerationStructureMotionInfoFlagsNV))
pure $ AccelerationStructureMotionInfoNV
maxInstances flags
instance Storable AccelerationStructureMotionInfoNV where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero AccelerationStructureMotionInfoNV where
zero = AccelerationStructureMotionInfoNV
zero
zero
| VkSRTDataNV - Structure specifying a transform in SRT decomposition
--
-- = Description
--
This transform decomposition consists of three elements . The first is a
-- matrix S, consisting of a scale, shear, and translation, usually used to
-- define the pivot point of the following rotation. This matrix is
-- constructed from the parameters above by:
--
\[S =
-- \left(
-- \begin{matrix}
sx & a & b & pvx \\
0 & sy & c & pvy \\
-- 0 & 0 & sz & pvz
}
\right)\ ]
--
-- The rotation quaternion is defined as:
--
- @R@ = [ @qx@ , @qy@ , @qz@ , @qw@ ]
--
This is a rotation around a conceptual normalized axis [ ax , ay , ] of
amount @theta@ such that :
--
- [ @qx@ , @qy@ , @qz@ ] = sin(@theta@\/2 ) × [ @ax@ , @ay@ , @az@ ]
--
-- and
--
-- - @qw@ = cos(@theta@\/2)
--
-- Finally, the transform has a translation T constructed from the
-- parameters above by:
--
-- \[T =
-- \left(
-- \begin{matrix}
1 & 0 & 0 & tx \\
0 & 1 & 0 & ty \\
0 & 0 & 1 & tz
}
\right)\ ]
--
-- The effective derived transform is then given by
--
-- - @T@ × @R@ × @S@
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
' AccelerationStructureSRTMotionInstanceNV '
data SRTDataNV = SRTDataNV
| @sx@ is the x component of the scale of the transform
sx :: Float
| @a@ is one component of the shear for the transform
a :: Float
| @b@ is one component of the shear for the transform
b :: Float
, -- | @pvx@ is the x component of the pivot point of the transform
pvx :: Float
, -- | @sy@ is the y component of the scale of the transform
sy :: Float
| @c@ is one component of the shear for the transform
c :: Float
, -- | @pvy@ is the y component of the pivot point of the transform
pvy :: Float
, -- | @sz@ is the z component of the scale of the transform
sz :: Float
, -- | @pvz@ is the z component of the pivot point of the transform
pvz :: Float
| @qx@ is the x component of the rotation quaternion
qx :: Float
| @qy@ is the y component of the rotation quaternion
qy :: Float
, -- | @qz@ is the z component of the rotation quaternion
qz :: Float
, -- | @qw@ is the w component of the rotation quaternion
qw :: Float
| is the x component of the post - rotation translation
tx :: Float
| @ty@ is the y component of the post - rotation translation
ty :: Float
| @tz@ is the z component of the post - rotation translation
tz :: Float
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SRTDataNV)
#endif
deriving instance Show SRTDataNV
instance ToCStruct SRTDataNV where
withCStruct x f = allocaBytes 64 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SRTDataNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr CFloat)) (CFloat (sx))
poke ((p `plusPtr` 4 :: Ptr CFloat)) (CFloat (a))
poke ((p `plusPtr` 8 :: Ptr CFloat)) (CFloat (b))
poke ((p `plusPtr` 12 :: Ptr CFloat)) (CFloat (pvx))
poke ((p `plusPtr` 16 :: Ptr CFloat)) (CFloat (sy))
poke ((p `plusPtr` 20 :: Ptr CFloat)) (CFloat (c))
poke ((p `plusPtr` 24 :: Ptr CFloat)) (CFloat (pvy))
poke ((p `plusPtr` 28 :: Ptr CFloat)) (CFloat (sz))
poke ((p `plusPtr` 32 :: Ptr CFloat)) (CFloat (pvz))
poke ((p `plusPtr` 36 :: Ptr CFloat)) (CFloat (qx))
poke ((p `plusPtr` 40 :: Ptr CFloat)) (CFloat (qy))
poke ((p `plusPtr` 44 :: Ptr CFloat)) (CFloat (qz))
poke ((p `plusPtr` 48 :: Ptr CFloat)) (CFloat (qw))
poke ((p `plusPtr` 52 :: Ptr CFloat)) (CFloat (tx))
poke ((p `plusPtr` 56 :: Ptr CFloat)) (CFloat (ty))
poke ((p `plusPtr` 60 :: Ptr CFloat)) (CFloat (tz))
f
cStructSize = 64
cStructAlignment = 4
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 4 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 8 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 12 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 16 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 20 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 24 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 28 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 32 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 36 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 40 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 44 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 48 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 52 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 56 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 60 :: Ptr CFloat)) (CFloat (zero))
f
instance FromCStruct SRTDataNV where
peekCStruct p = do
sx <- peek @CFloat ((p `plusPtr` 0 :: Ptr CFloat))
a <- peek @CFloat ((p `plusPtr` 4 :: Ptr CFloat))
b <- peek @CFloat ((p `plusPtr` 8 :: Ptr CFloat))
pvx <- peek @CFloat ((p `plusPtr` 12 :: Ptr CFloat))
sy <- peek @CFloat ((p `plusPtr` 16 :: Ptr CFloat))
c <- peek @CFloat ((p `plusPtr` 20 :: Ptr CFloat))
pvy <- peek @CFloat ((p `plusPtr` 24 :: Ptr CFloat))
sz <- peek @CFloat ((p `plusPtr` 28 :: Ptr CFloat))
pvz <- peek @CFloat ((p `plusPtr` 32 :: Ptr CFloat))
qx <- peek @CFloat ((p `plusPtr` 36 :: Ptr CFloat))
qy <- peek @CFloat ((p `plusPtr` 40 :: Ptr CFloat))
qz <- peek @CFloat ((p `plusPtr` 44 :: Ptr CFloat))
qw <- peek @CFloat ((p `plusPtr` 48 :: Ptr CFloat))
tx <- peek @CFloat ((p `plusPtr` 52 :: Ptr CFloat))
ty <- peek @CFloat ((p `plusPtr` 56 :: Ptr CFloat))
tz <- peek @CFloat ((p `plusPtr` 60 :: Ptr CFloat))
pure $ SRTDataNV
(coerce @CFloat @Float sx)
(coerce @CFloat @Float a)
(coerce @CFloat @Float b)
(coerce @CFloat @Float pvx)
(coerce @CFloat @Float sy)
(coerce @CFloat @Float c)
(coerce @CFloat @Float pvy)
(coerce @CFloat @Float sz)
(coerce @CFloat @Float pvz)
(coerce @CFloat @Float qx)
(coerce @CFloat @Float qy)
(coerce @CFloat @Float qz)
(coerce @CFloat @Float qw)
(coerce @CFloat @Float tx)
(coerce @CFloat @Float ty)
(coerce @CFloat @Float tz)
instance Storable SRTDataNV where
sizeOf ~_ = 64
alignment ~_ = 4
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero SRTDataNV where
zero = SRTDataNV
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
-- | VkAccelerationStructureSRTMotionInstanceNV - Structure specifying a
single acceleration structure SRT motion instance for building into an
-- acceleration structure geometry
--
-- = Description
--
-- The C language specification does not define the ordering of bit-fields,
-- but in practice, this struct produces the correct layout with existing
-- compilers. The intended bit pattern is for the following:
--
-- If a compiler produces code that diverges from that pattern,
-- applications /must/ employ another method to set values according to the
-- correct bit pattern.
--
The transform for a SRT motion instance at a point in time is derived
from component - wise linear interpolation of the two SRT transforms . That
is , for a @time@ in [ 0,1 ] the resulting transform is
--
-- - @transformT0@ × (1 - @time@) + @transformT1@ × @time@
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
-- 'AccelerationStructureMotionInstanceDataNV',
' Vulkan . Extensions . VK_KHR_acceleration_structure . GeometryInstanceFlagsKHR ' ,
-- 'SRTDataNV'
data AccelerationStructureSRTMotionInstanceNV = AccelerationStructureSRTMotionInstanceNV
{ -- | @transformT0@ is a 'SRTDataNV' structure describing a transformation to
-- be applied to the acceleration structure at time 0.
transformT0 :: SRTDataNV
, -- | @transformT1@ is a 'SRTDataNV' structure describing a transformation to
be applied to the acceleration structure at time 1 .
transformT1 :: SRTDataNV
| @instanceCustomIndex@ is a 24 - bit user - specified index value accessible
-- to ray shaders in the @InstanceCustomIndexKHR@ built-in.
--
-- @instanceCustomIndex@ and @mask@ occupy the same memory as if a single
@uint32_t@ was specified in their place
--
- @instanceCustomIndex@ occupies the 24 least significant bits of that
-- memory
--
- @mask@ occupies the 8 most significant bits of that memory
instanceCustomIndex :: Word32
| @mask@ is an 8 - bit visibility mask for the geometry . The instance /may/
-- only be hit if @Cull Mask & instance.mask != 0@
mask :: Word32
| @instanceShaderBindingTableRecordOffset@ is a 24 - bit offset used in
-- calculating the hit shader binding table index.
--
@instanceShaderBindingTableRecordOffset@ and occupy the same
memory as if a single @uint32_t@ was specified in their place
--
- @instanceShaderBindingTableRecordOffset@ occupies the 24 least
-- significant bits of that memory
--
- @flags@ occupies the 8 most significant bits of that memory
instanceShaderBindingTableRecordOffset :: Word32
| @flags@ is an 8 - bit mask of
' Vulkan . Extensions . VK_KHR_acceleration_structure . GeometryInstanceFlagBitsKHR '
-- values to apply to this instance.
--
-- #VUID-VkAccelerationStructureSRTMotionInstanceNV-flags-parameter#
-- @flags@ /must/ be a valid combination of
' Vulkan . Extensions . VK_KHR_acceleration_structure . GeometryInstanceFlagBitsKHR '
-- values
flags :: GeometryInstanceFlagsKHR
, -- | @accelerationStructureReference@ is either:
--
-- - a device address containing the value obtained from
' Vulkan . Extensions . VK_KHR_acceleration_structure.getAccelerationStructureDeviceAddressKHR '
-- or
' Vulkan . Extensions . VK_NV_ray_tracing.getAccelerationStructureHandleNV '
-- (used by device operations which reference acceleration structures)
-- or,
--
- a ' Vulkan . Extensions . Handles . AccelerationStructureKHR ' object ( used
-- by host operations which reference acceleration structures).
accelerationStructureReference :: Word64
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (AccelerationStructureSRTMotionInstanceNV)
#endif
deriving instance Show AccelerationStructureSRTMotionInstanceNV
instance ToCStruct AccelerationStructureSRTMotionInstanceNV where
withCStruct x f = allocaBytes 144 $ \p -> pokeCStruct p x (f p)
pokeCStruct p AccelerationStructureSRTMotionInstanceNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr SRTDataNV)) (transformT0)
poke ((p `plusPtr` 64 :: Ptr SRTDataNV)) (transformT1)
poke ((p `plusPtr` 128 :: Ptr Word32)) (((coerce @_ @Word32 (mask)) `shiftL` 24) .|. (instanceCustomIndex))
poke ((p `plusPtr` 132 :: Ptr Word32)) (((coerce @_ @Word32 (flags)) `shiftL` 24) .|. (instanceShaderBindingTableRecordOffset))
poke ((p `plusPtr` 136 :: Ptr Word64)) (accelerationStructureReference)
f
cStructSize = 144
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr SRTDataNV)) (zero)
poke ((p `plusPtr` 64 :: Ptr SRTDataNV)) (zero)
poke ((p `plusPtr` 136 :: Ptr Word64)) (zero)
f
instance FromCStruct AccelerationStructureSRTMotionInstanceNV where
peekCStruct p = do
transformT0 <- peekCStruct @SRTDataNV ((p `plusPtr` 0 :: Ptr SRTDataNV))
transformT1 <- peekCStruct @SRTDataNV ((p `plusPtr` 64 :: Ptr SRTDataNV))
instanceCustomIndex <- peek @Word32 ((p `plusPtr` 128 :: Ptr Word32))
let instanceCustomIndex' = ((instanceCustomIndex .&. coerce @Word32 0xffffff))
mask <- peek @Word32 ((p `plusPtr` 128 :: Ptr Word32))
let mask' = ((((mask `shiftR` 24)) .&. coerce @Word32 0xff))
instanceShaderBindingTableRecordOffset <- peek @Word32 ((p `plusPtr` 132 :: Ptr Word32))
let instanceShaderBindingTableRecordOffset' = ((instanceShaderBindingTableRecordOffset .&. coerce @Word32 0xffffff))
flags <- peek @GeometryInstanceFlagsKHR ((p `plusPtr` 132 :: Ptr GeometryInstanceFlagsKHR))
let flags' = ((((flags `shiftR` 24)) .&. coerce @Word32 0xff))
accelerationStructureReference <- peek @Word64 ((p `plusPtr` 136 :: Ptr Word64))
pure $ AccelerationStructureSRTMotionInstanceNV
transformT0
transformT1
instanceCustomIndex'
mask'
instanceShaderBindingTableRecordOffset'
flags'
accelerationStructureReference
instance Storable AccelerationStructureSRTMotionInstanceNV where
sizeOf ~_ = 144
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero AccelerationStructureSRTMotionInstanceNV where
zero = AccelerationStructureSRTMotionInstanceNV
zero
zero
zero
zero
zero
zero
zero
-- | VkAccelerationStructureMatrixMotionInstanceNV - Structure specifying a
-- single acceleration structure matrix motion instance for building into
-- an acceleration structure geometry
--
-- = Description
--
-- The C language specification does not define the ordering of bit-fields,
-- but in practice, this struct produces the correct layout with existing
-- compilers. The intended bit pattern is for the following:
--
-- If a compiler produces code that diverges from that pattern,
-- applications /must/ employ another method to set values according to the
-- correct bit pattern.
--
-- The transform for a matrix motion instance at a point in time is derived
by component - wise linear interpolation of the two transforms . That is ,
for a @time@ in [ 0,1 ] the resulting transform is
--
-- - @transformT0@ × (1 - @time@) + @transformT1@ × @time@
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
-- 'AccelerationStructureMotionInstanceDataNV',
' Vulkan . Extensions . VK_KHR_acceleration_structure . GeometryInstanceFlagsKHR ' ,
' Vulkan . Extensions . VK_KHR_acceleration_structure . TransformMatrixKHR '
data AccelerationStructureMatrixMotionInstanceNV = AccelerationStructureMatrixMotionInstanceNV
{ -- | @transformT0@ is a
' Vulkan . Extensions . VK_KHR_acceleration_structure . TransformMatrixKHR '
-- structure describing a transformation to be applied to the acceleration
-- structure at time 0.
transformT0 :: TransformMatrixKHR
, -- | @transformT1@ is a
' Vulkan . Extensions . VK_KHR_acceleration_structure . TransformMatrixKHR '
-- structure describing a transformation to be applied to the acceleration
structure at time 1 .
transformT1 :: TransformMatrixKHR
| @instanceCustomIndex@ is a 24 - bit user - specified index value accessible
-- to ray shaders in the @InstanceCustomIndexKHR@ built-in.
--
-- @instanceCustomIndex@ and @mask@ occupy the same memory as if a single
@uint32_t@ was specified in their place
--
- @instanceCustomIndex@ occupies the 24 least significant bits of that
-- memory
--
- @mask@ occupies the 8 most significant bits of that memory
instanceCustomIndex :: Word32
| @mask@ is an 8 - bit visibility mask for the geometry . The instance /may/
-- only be hit if @Cull Mask & instance.mask != 0@
mask :: Word32
| @instanceShaderBindingTableRecordOffset@ is a 24 - bit offset used in
-- calculating the hit shader binding table index.
--
@instanceShaderBindingTableRecordOffset@ and occupy the same
memory as if a single @uint32_t@ was specified in their place
--
- @instanceShaderBindingTableRecordOffset@ occupies the 24 least
-- significant bits of that memory
--
- @flags@ occupies the 8 most significant bits of that memory
instanceShaderBindingTableRecordOffset :: Word32
| @flags@ is an 8 - bit mask of
' Vulkan . Extensions . VK_KHR_acceleration_structure . GeometryInstanceFlagBitsKHR '
-- values to apply to this instance.
--
-- #VUID-VkAccelerationStructureMatrixMotionInstanceNV-flags-parameter#
-- @flags@ /must/ be a valid combination of
' Vulkan . Extensions . VK_KHR_acceleration_structure . GeometryInstanceFlagBitsKHR '
-- values
flags :: GeometryInstanceFlagsKHR
, -- | @accelerationStructureReference@ is either:
--
-- - a device address containing the value obtained from
' Vulkan . Extensions . VK_KHR_acceleration_structure.getAccelerationStructureDeviceAddressKHR '
-- or
' Vulkan . Extensions . VK_NV_ray_tracing.getAccelerationStructureHandleNV '
-- (used by device operations which reference acceleration structures)
-- or,
--
- a ' Vulkan . Extensions . Handles . AccelerationStructureKHR ' object ( used
-- by host operations which reference acceleration structures).
accelerationStructureReference :: Word64
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (AccelerationStructureMatrixMotionInstanceNV)
#endif
deriving instance Show AccelerationStructureMatrixMotionInstanceNV
instance ToCStruct AccelerationStructureMatrixMotionInstanceNV where
withCStruct x f = allocaBytes 112 $ \p -> pokeCStruct p x (f p)
pokeCStruct p AccelerationStructureMatrixMotionInstanceNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr TransformMatrixKHR)) (transformT0)
poke ((p `plusPtr` 48 :: Ptr TransformMatrixKHR)) (transformT1)
poke ((p `plusPtr` 96 :: Ptr Word32)) (((coerce @_ @Word32 (mask)) `shiftL` 24) .|. (instanceCustomIndex))
poke ((p `plusPtr` 100 :: Ptr Word32)) (((coerce @_ @Word32 (flags)) `shiftL` 24) .|. (instanceShaderBindingTableRecordOffset))
poke ((p `plusPtr` 104 :: Ptr Word64)) (accelerationStructureReference)
f
cStructSize = 112
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr TransformMatrixKHR)) (zero)
poke ((p `plusPtr` 48 :: Ptr TransformMatrixKHR)) (zero)
poke ((p `plusPtr` 104 :: Ptr Word64)) (zero)
f
instance FromCStruct AccelerationStructureMatrixMotionInstanceNV where
peekCStruct p = do
transformT0 <- peekCStruct @TransformMatrixKHR ((p `plusPtr` 0 :: Ptr TransformMatrixKHR))
transformT1 <- peekCStruct @TransformMatrixKHR ((p `plusPtr` 48 :: Ptr TransformMatrixKHR))
instanceCustomIndex <- peek @Word32 ((p `plusPtr` 96 :: Ptr Word32))
let instanceCustomIndex' = ((instanceCustomIndex .&. coerce @Word32 0xffffff))
mask <- peek @Word32 ((p `plusPtr` 96 :: Ptr Word32))
let mask' = ((((mask `shiftR` 24)) .&. coerce @Word32 0xff))
instanceShaderBindingTableRecordOffset <- peek @Word32 ((p `plusPtr` 100 :: Ptr Word32))
let instanceShaderBindingTableRecordOffset' = ((instanceShaderBindingTableRecordOffset .&. coerce @Word32 0xffffff))
flags <- peek @GeometryInstanceFlagsKHR ((p `plusPtr` 100 :: Ptr GeometryInstanceFlagsKHR))
let flags' = ((((flags `shiftR` 24)) .&. coerce @Word32 0xff))
accelerationStructureReference <- peek @Word64 ((p `plusPtr` 104 :: Ptr Word64))
pure $ AccelerationStructureMatrixMotionInstanceNV
transformT0
transformT1
instanceCustomIndex'
mask'
instanceShaderBindingTableRecordOffset'
flags'
accelerationStructureReference
instance Storable AccelerationStructureMatrixMotionInstanceNV where
sizeOf ~_ = 112
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero AccelerationStructureMatrixMotionInstanceNV where
zero = AccelerationStructureMatrixMotionInstanceNV
zero
zero
zero
zero
zero
zero
zero
-- | VkAccelerationStructureMotionInstanceNV - Structure specifying a single
-- acceleration structure motion instance for building into an acceleration
-- structure geometry
--
-- = Description
--
-- Note
--
-- If writing this other than with a standard C compiler, note that the
final structure should be 152 bytes in size .
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkAccelerationStructureMotionInstanceNV-type-parameter# @type@
-- /must/ be a valid 'AccelerationStructureMotionInstanceTypeNV' value
--
-- - #VUID-VkAccelerationStructureMotionInstanceNV-flags-zerobitmask#
@flags@ /must/ be @0@
--
-- - #VUID-VkAccelerationStructureMotionInstanceNV-staticInstance-parameter#
-- If @type@ is
' ' , the
-- @staticInstance@ member of @data@ /must/ be a valid
' Vulkan . Extensions . VK_KHR_acceleration_structure . AccelerationStructureInstanceKHR '
-- structure
--
-- - #VUID-VkAccelerationStructureMotionInstanceNV-matrixMotionInstance-parameter#
-- If @type@ is
' ' , the
@matrixMotionInstance@ member of @data@ /must/ be a valid
-- 'AccelerationStructureMatrixMotionInstanceNV' structure
--
-- - #VUID-VkAccelerationStructureMotionInstanceNV-srtMotionInstance-parameter#
-- If @type@ is
-- 'ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV', the
-- @srtMotionInstance@ member of @data@ /must/ be a valid
-- 'AccelerationStructureSRTMotionInstanceNV' structure
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
-- 'AccelerationStructureMotionInstanceDataNV',
-- 'AccelerationStructureMotionInstanceFlagsNV',
-- 'AccelerationStructureMotionInstanceTypeNV'
data AccelerationStructureMotionInstanceNV = AccelerationStructureMotionInstanceNV
{ -- | @type@ is a 'AccelerationStructureMotionInstanceTypeNV' enumerant
-- identifying which type of motion instance this is and which type of the
-- union is valid.
type' :: AccelerationStructureMotionInstanceTypeNV
, -- | @flags@ is currently unused, but is required to keep natural alignment
-- of @data@.
flags :: AccelerationStructureMotionInstanceFlagsNV
, -- | @data@ is a 'AccelerationStructureMotionInstanceDataNV' containing
-- motion instance data for this instance.
data' :: AccelerationStructureMotionInstanceDataNV
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (AccelerationStructureMotionInstanceNV)
#endif
deriving instance Show AccelerationStructureMotionInstanceNV
instance ToCStruct AccelerationStructureMotionInstanceNV where
withCStruct x f = allocaBytes 152 $ \p -> pokeCStruct p x (f p)
pokeCStruct p AccelerationStructureMotionInstanceNV{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr AccelerationStructureMotionInstanceTypeNV)) (type')
lift $ poke ((p `plusPtr` 4 :: Ptr AccelerationStructureMotionInstanceFlagsNV)) (flags)
ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr AccelerationStructureMotionInstanceDataNV)) (data') . ($ ())
lift $ f
cStructSize = 152
cStructAlignment = 8
pokeZeroCStruct p f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr AccelerationStructureMotionInstanceTypeNV)) (zero)
ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr AccelerationStructureMotionInstanceDataNV)) (zero) . ($ ())
lift $ f
instance Zero AccelerationStructureMotionInstanceNV where
zero = AccelerationStructureMotionInstanceNV
zero
zero
zero
data AccelerationStructureMotionInstanceDataNV
= StaticInstance AccelerationStructureInstanceKHR
| MatrixMotionInstance AccelerationStructureMatrixMotionInstanceNV
| SrtMotionInstance AccelerationStructureSRTMotionInstanceNV
deriving (Show)
instance ToCStruct AccelerationStructureMotionInstanceDataNV where
withCStruct x f = allocaBytes 144 $ \p -> pokeCStruct p x (f p)
pokeCStruct :: Ptr AccelerationStructureMotionInstanceDataNV -> AccelerationStructureMotionInstanceDataNV -> IO a -> IO a
pokeCStruct p = (. const) . runContT . \case
StaticInstance v -> lift $ poke (castPtr @_ @AccelerationStructureInstanceKHR p) (v)
MatrixMotionInstance v -> lift $ poke (castPtr @_ @AccelerationStructureMatrixMotionInstanceNV p) (v)
SrtMotionInstance v -> lift $ poke (castPtr @_ @AccelerationStructureSRTMotionInstanceNV p) (v)
pokeZeroCStruct :: Ptr AccelerationStructureMotionInstanceDataNV -> IO b -> IO b
pokeZeroCStruct _ f = f
cStructSize = 144
cStructAlignment = 8
instance Zero AccelerationStructureMotionInstanceDataNV where
zero = SrtMotionInstance zero
-- | VkAccelerationStructureMotionInfoFlagsNV - Reserved for future use
--
-- = Description
--
' ' is a bitmask type for setting a
-- mask, but is currently reserved for future use.
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
-- 'AccelerationStructureMotionInfoNV'
newtype AccelerationStructureMotionInfoFlagsNV = AccelerationStructureMotionInfoFlagsNV Flags
deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits)
conNameAccelerationStructureMotionInfoFlagsNV :: String
conNameAccelerationStructureMotionInfoFlagsNV = "AccelerationStructureMotionInfoFlagsNV"
enumPrefixAccelerationStructureMotionInfoFlagsNV :: String
enumPrefixAccelerationStructureMotionInfoFlagsNV = ""
showTableAccelerationStructureMotionInfoFlagsNV :: [(AccelerationStructureMotionInfoFlagsNV, String)]
showTableAccelerationStructureMotionInfoFlagsNV = []
instance Show AccelerationStructureMotionInfoFlagsNV where
showsPrec =
enumShowsPrec
enumPrefixAccelerationStructureMotionInfoFlagsNV
showTableAccelerationStructureMotionInfoFlagsNV
conNameAccelerationStructureMotionInfoFlagsNV
(\(AccelerationStructureMotionInfoFlagsNV x) -> x)
(\x -> showString "0x" . showHex x)
instance Read AccelerationStructureMotionInfoFlagsNV where
readPrec =
enumReadPrec
enumPrefixAccelerationStructureMotionInfoFlagsNV
showTableAccelerationStructureMotionInfoFlagsNV
conNameAccelerationStructureMotionInfoFlagsNV
AccelerationStructureMotionInfoFlagsNV
-- | VkAccelerationStructureMotionInstanceFlagsNV - Reserved for future use
--
-- = Description
--
' AccelerationStructureMotionInstanceFlagsNV ' is a bitmask type for
-- setting a mask, but is currently reserved for future use.
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
-- 'AccelerationStructureMotionInstanceNV'
newtype AccelerationStructureMotionInstanceFlagsNV = AccelerationStructureMotionInstanceFlagsNV Flags
deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits)
conNameAccelerationStructureMotionInstanceFlagsNV :: String
conNameAccelerationStructureMotionInstanceFlagsNV = "AccelerationStructureMotionInstanceFlagsNV"
enumPrefixAccelerationStructureMotionInstanceFlagsNV :: String
enumPrefixAccelerationStructureMotionInstanceFlagsNV = ""
showTableAccelerationStructureMotionInstanceFlagsNV :: [(AccelerationStructureMotionInstanceFlagsNV, String)]
showTableAccelerationStructureMotionInstanceFlagsNV = []
instance Show AccelerationStructureMotionInstanceFlagsNV where
showsPrec =
enumShowsPrec
enumPrefixAccelerationStructureMotionInstanceFlagsNV
showTableAccelerationStructureMotionInstanceFlagsNV
conNameAccelerationStructureMotionInstanceFlagsNV
(\(AccelerationStructureMotionInstanceFlagsNV x) -> x)
(\x -> showString "0x" . showHex x)
instance Read AccelerationStructureMotionInstanceFlagsNV where
readPrec =
enumReadPrec
enumPrefixAccelerationStructureMotionInstanceFlagsNV
showTableAccelerationStructureMotionInstanceFlagsNV
conNameAccelerationStructureMotionInstanceFlagsNV
AccelerationStructureMotionInstanceFlagsNV
-- | VkAccelerationStructureMotionInstanceTypeNV - Enum specifying a type of
-- acceleration structure motion instance data for building into an
-- acceleration structure geometry
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
-- 'AccelerationStructureMotionInstanceNV'
newtype AccelerationStructureMotionInstanceTypeNV = AccelerationStructureMotionInstanceTypeNV Int32
deriving newtype (Eq, Ord, Storable, Zero)
| ' ' specifies that
-- the instance is a static instance with no instance motion.
pattern ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_STATIC_NV = AccelerationStructureMotionInstanceTypeNV 0
| ' ' specifies
-- that the instance is a motion instance with motion specified by
interpolation between two matrices .
pattern ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_MATRIX_MOTION_NV = AccelerationStructureMotionInstanceTypeNV 1
-- | 'ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV' specifies
-- that the instance is a motion instance with motion specified by
interpolation in the SRT decomposition .
pattern ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV = AccelerationStructureMotionInstanceTypeNV 2
# COMPLETE
, , ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV : :
AccelerationStructureMotionInstanceTypeNV
#
ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_STATIC_NV
, ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_MATRIX_MOTION_NV
, ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV ::
AccelerationStructureMotionInstanceTypeNV
#-}
conNameAccelerationStructureMotionInstanceTypeNV :: String
conNameAccelerationStructureMotionInstanceTypeNV = "AccelerationStructureMotionInstanceTypeNV"
enumPrefixAccelerationStructureMotionInstanceTypeNV :: String
enumPrefixAccelerationStructureMotionInstanceTypeNV = "ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_"
showTableAccelerationStructureMotionInstanceTypeNV :: [(AccelerationStructureMotionInstanceTypeNV, String)]
showTableAccelerationStructureMotionInstanceTypeNV =
[
( ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_STATIC_NV
, "STATIC_NV"
)
,
( ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_MATRIX_MOTION_NV
, "MATRIX_MOTION_NV"
)
,
( ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV
, "SRT_MOTION_NV"
)
]
instance Show AccelerationStructureMotionInstanceTypeNV where
showsPrec =
enumShowsPrec
enumPrefixAccelerationStructureMotionInstanceTypeNV
showTableAccelerationStructureMotionInstanceTypeNV
conNameAccelerationStructureMotionInstanceTypeNV
(\(AccelerationStructureMotionInstanceTypeNV x) -> x)
(showsPrec 11)
instance Read AccelerationStructureMotionInstanceTypeNV where
readPrec =
enumReadPrec
enumPrefixAccelerationStructureMotionInstanceTypeNV
showTableAccelerationStructureMotionInstanceTypeNV
conNameAccelerationStructureMotionInstanceTypeNV
AccelerationStructureMotionInstanceTypeNV
type NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION = 1
No documentation found for TopLevel " VK_NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION "
pattern NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION :: forall a . Integral a => a
pattern NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION = 1
type NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME = "VK_NV_ray_tracing_motion_blur"
No documentation found for TopLevel " "
pattern NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME = "VK_NV_ray_tracing_motion_blur"
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/70d8cca16893f8de76c0eb89e79e73f5a455db76/src/Vulkan/Extensions/VK_NV_ray_tracing_motion_blur.hs | haskell | # language CPP #
| = Name
VK_NV_ray_tracing_motion_blur - device extension
== VK_NV_ray_tracing_motion_blur
[__Name String__]
[__Extension Type__]
Device extension
[__Registered Extension Number__]
[__Revision__]
[__Extension and Version Dependencies__]
- Requires @VK_KHR_ray_tracing_pipeline@ to be enabled for any
device-level functionality
[__Contact__]
== Other Extension Metadata
[__Last Modified Date__]
[__Interactions and External Dependencies__]
- This extension requires
- This extension provides API support for
< GL_NV_ray_tracing_motion_blur>
[__Contributors__]
== Description
intersect rays against static geometry, but rendering algorithms often
want to support motion, which is more efficiently supported with
motion-specific algorithms. This extension adds a set of mechanisms to
support fast tracing of moving geometry:
- A ray pipeline trace call which takes a time parameter
- Flags to enable motion support in an acceleration structure
- Support for time-varying vertex positions in a geometry
- Motion instances to move existing instances over time
The motion represented here is parameterized across a normalized
provides a time within that normalized range to be used when
intersecting that ray with geometry. The geometry can be provided with
providing multiple transforms in the instance using
'AccelerationStructureMotionInstanceNV'.
== New Structures
- 'AccelerationStructureMatrixMotionInstanceNV'
- 'AccelerationStructureMotionInstanceNV'
- 'SRTDataNV'
- Extending
- 'AccelerationStructureMotionInfoNV'
- Extending
- Extending
- 'PhysicalDeviceRayTracingMotionBlurFeaturesNV'
== New Unions
- 'AccelerationStructureMotionInstanceDataNV'
== New Enums
- 'AccelerationStructureMotionInstanceTypeNV'
== New Bitmasks
== New Enum Constants
- 'NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME'
- 'NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION'
- Extending
- Extending
- Extending
== Issues
- Added a note on the structure size and made the stride explicit in
the language.
- Yes, with a packed encoding to minimize the amount of data sent for
metadata.
== Version History
- Initial external release
== See Also
'AccelerationStructureGeometryMotionTrianglesDataNV',
'AccelerationStructureMatrixMotionInstanceNV',
'AccelerationStructureMotionInfoNV',
'AccelerationStructureMotionInstanceDataNV',
'AccelerationStructureMotionInstanceFlagsNV',
'AccelerationStructureMotionInstanceNV',
'AccelerationStructureMotionInstanceTypeNV',
'PhysicalDeviceRayTracingMotionBlurFeaturesNV', 'SRTDataNV'
== Document Notes
For more information, see the
This page is a generated document. Fixes and changes should be made to
the generator scripts, not directly.
| VkPhysicalDeviceRayTracingMotionBlurFeaturesNV - Structure describing
the ray tracing motion blur features that can be supported by an
implementation
= Members
This structure describes the following features:
= Description
If the 'PhysicalDeviceRayTracingMotionBlurFeaturesNV' structure is
included in the @pNext@ chain of the
structure passed to
it is filled in to indicate whether each corresponding feature is
selectively enable these features.
== Valid Usage (Implicit)
= See Also
<-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
the implementation supports the motion blur feature.
| #features-rayTracingMotionBlurPipelineTraceRaysIndirect#
@rayTracingMotionBlurPipelineTraceRaysIndirect@ indicates whether the
implementation supports indirect ray tracing commands with the motion
blur feature enabled.
| VkAccelerationStructureGeometryMotionTrianglesDataNV - Structure
specifying vertex motion in a bottom-level acceleration structure
= Description
If 'AccelerationStructureGeometryMotionTrianglesDataNV' is included in
the @pNext@ chain of a
structure, the basic vertex positions are used for the position of the
'AccelerationStructureGeometryMotionTrianglesDataNV' is used for the
intermediate times.
== Valid Usage (Implicit)
= See Also
<-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
| VkAccelerationStructureMotionInfoNV - Structure specifying the
parameters of a newly created acceleration structure object
== Valid Usage (Implicit)
= See Also
<-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
the motion top-level acceleration structure.
| @flags@ is 0 and reserved for future use.
#VUID-VkAccelerationStructureMotionInfoNV-flags-zerobitmask# @flags@
= Description
matrix S, consisting of a scale, shear, and translation, usually used to
define the pivot point of the following rotation. This matrix is
constructed from the parameters above by:
\left(
\begin{matrix}
0 & 0 & sz & pvz
The rotation quaternion is defined as:
and
- @qw@ = cos(@theta@\/2)
Finally, the transform has a translation T constructed from the
parameters above by:
\[T =
\left(
\begin{matrix}
The effective derived transform is then given by
- @T@ × @R@ × @S@
= See Also
<-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
| @pvx@ is the x component of the pivot point of the transform
| @sy@ is the y component of the scale of the transform
| @pvy@ is the y component of the pivot point of the transform
| @sz@ is the z component of the scale of the transform
| @pvz@ is the z component of the pivot point of the transform
| @qz@ is the z component of the rotation quaternion
| @qw@ is the w component of the rotation quaternion
| VkAccelerationStructureSRTMotionInstanceNV - Structure specifying a
acceleration structure geometry
= Description
The C language specification does not define the ordering of bit-fields,
but in practice, this struct produces the correct layout with existing
compilers. The intended bit pattern is for the following:
If a compiler produces code that diverges from that pattern,
applications /must/ employ another method to set values according to the
correct bit pattern.
- @transformT0@ × (1 - @time@) + @transformT1@ × @time@
== Valid Usage (Implicit)
= See Also
<-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
'AccelerationStructureMotionInstanceDataNV',
'SRTDataNV'
| @transformT0@ is a 'SRTDataNV' structure describing a transformation to
be applied to the acceleration structure at time 0.
| @transformT1@ is a 'SRTDataNV' structure describing a transformation to
to ray shaders in the @InstanceCustomIndexKHR@ built-in.
@instanceCustomIndex@ and @mask@ occupy the same memory as if a single
memory
only be hit if @Cull Mask & instance.mask != 0@
calculating the hit shader binding table index.
significant bits of that memory
values to apply to this instance.
#VUID-VkAccelerationStructureSRTMotionInstanceNV-flags-parameter#
@flags@ /must/ be a valid combination of
values
| @accelerationStructureReference@ is either:
- a device address containing the value obtained from
or
(used by device operations which reference acceleration structures)
or,
by host operations which reference acceleration structures).
| VkAccelerationStructureMatrixMotionInstanceNV - Structure specifying a
single acceleration structure matrix motion instance for building into
an acceleration structure geometry
= Description
The C language specification does not define the ordering of bit-fields,
but in practice, this struct produces the correct layout with existing
compilers. The intended bit pattern is for the following:
If a compiler produces code that diverges from that pattern,
applications /must/ employ another method to set values according to the
correct bit pattern.
The transform for a matrix motion instance at a point in time is derived
- @transformT0@ × (1 - @time@) + @transformT1@ × @time@
== Valid Usage (Implicit)
= See Also
<-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
'AccelerationStructureMotionInstanceDataNV',
| @transformT0@ is a
structure describing a transformation to be applied to the acceleration
structure at time 0.
| @transformT1@ is a
structure describing a transformation to be applied to the acceleration
to ray shaders in the @InstanceCustomIndexKHR@ built-in.
@instanceCustomIndex@ and @mask@ occupy the same memory as if a single
memory
only be hit if @Cull Mask & instance.mask != 0@
calculating the hit shader binding table index.
significant bits of that memory
values to apply to this instance.
#VUID-VkAccelerationStructureMatrixMotionInstanceNV-flags-parameter#
@flags@ /must/ be a valid combination of
values
| @accelerationStructureReference@ is either:
- a device address containing the value obtained from
or
(used by device operations which reference acceleration structures)
or,
by host operations which reference acceleration structures).
| VkAccelerationStructureMotionInstanceNV - Structure specifying a single
acceleration structure motion instance for building into an acceleration
structure geometry
= Description
Note
If writing this other than with a standard C compiler, note that the
== Valid Usage (Implicit)
- #VUID-VkAccelerationStructureMotionInstanceNV-type-parameter# @type@
/must/ be a valid 'AccelerationStructureMotionInstanceTypeNV' value
- #VUID-VkAccelerationStructureMotionInstanceNV-flags-zerobitmask#
- #VUID-VkAccelerationStructureMotionInstanceNV-staticInstance-parameter#
If @type@ is
@staticInstance@ member of @data@ /must/ be a valid
structure
- #VUID-VkAccelerationStructureMotionInstanceNV-matrixMotionInstance-parameter#
If @type@ is
'AccelerationStructureMatrixMotionInstanceNV' structure
- #VUID-VkAccelerationStructureMotionInstanceNV-srtMotionInstance-parameter#
If @type@ is
'ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV', the
@srtMotionInstance@ member of @data@ /must/ be a valid
'AccelerationStructureSRTMotionInstanceNV' structure
= See Also
<-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
'AccelerationStructureMotionInstanceDataNV',
'AccelerationStructureMotionInstanceFlagsNV',
'AccelerationStructureMotionInstanceTypeNV'
| @type@ is a 'AccelerationStructureMotionInstanceTypeNV' enumerant
identifying which type of motion instance this is and which type of the
union is valid.
| @flags@ is currently unused, but is required to keep natural alignment
of @data@.
| @data@ is a 'AccelerationStructureMotionInstanceDataNV' containing
motion instance data for this instance.
| VkAccelerationStructureMotionInfoFlagsNV - Reserved for future use
= Description
mask, but is currently reserved for future use.
= See Also
<-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
'AccelerationStructureMotionInfoNV'
| VkAccelerationStructureMotionInstanceFlagsNV - Reserved for future use
= Description
setting a mask, but is currently reserved for future use.
= See Also
<-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
'AccelerationStructureMotionInstanceNV'
| VkAccelerationStructureMotionInstanceTypeNV - Enum specifying a type of
acceleration structure motion instance data for building into an
acceleration structure geometry
= See Also
<-extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur VK_NV_ray_tracing_motion_blur>,
'AccelerationStructureMotionInstanceNV'
the instance is a static instance with no instance motion.
that the instance is a motion instance with motion specified by
| 'ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV' specifies
that the instance is a motion instance with motion specified by | @VK_NV_ray_tracing_motion_blur@
328
1
- Requires support for Vulkan 1.0
-
2021 - 06 - 16
< >
- , NVIDIA
- , NVIDIA
tracing support in the API provides an efficient mechanism to
timestep between 0.0 and 1.0 . A motion trace using @OpTraceRayMotionNV@
motion by a combination of adding a second vertex position for time of
1.0 using ' AccelerationStructureGeometryMotionTrianglesDataNV ' and
- ' AccelerationStructureSRTMotionInstanceNV '
' Vulkan . Extensions . VK_KHR_acceleration_structure . AccelerationStructureCreateInfoKHR ' :
' Vulkan . Extensions . VK_KHR_acceleration_structure . AccelerationStructureGeometryTrianglesDataKHR ' :
- ' AccelerationStructureGeometryMotionTrianglesDataNV '
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 ' ,
' Vulkan . Core10.Device . DeviceCreateInfo ' :
- ' '
- ' AccelerationStructureMotionInstanceFlagsNV '
' Vulkan . Extensions . VK_KHR_acceleration_structure . AccelerationStructureCreateFlagBitsKHR ' :
- ' Vulkan . Extensions . VK_KHR_acceleration_structure . ACCELERATION_STRUCTURE_CREATE_MOTION_BIT_NV '
' Vulkan . Extensions . VK_KHR_acceleration_structure . BuildAccelerationStructureFlagBitsKHR ' :
- ' Vulkan . Extensions . VK_KHR_acceleration_structure . '
' Vulkan . Core10.Enums . PipelineCreateFlagBits . ' :
- ' Vulkan . Core10.Enums . PipelineCreateFlagBits . PIPELINE_CREATE_RAY_TRACING_ALLOW_MOTION_BIT_NV '
- Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' :
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_MOTION_TRIANGLES_DATA_NV '
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MOTION_INFO_NV '
- ' Vulkan . Core10.Enums . StructureType . '
( 1 ) What size is VkAccelerationStructureMotionInstanceNV ?
( 2 ) Allow arrayOfPointers for motion ?
- Revision 1 , 2020 - 06 - 16 ( , )
' ' ,
' AccelerationStructureSRTMotionInstanceNV ' ,
< -extensions/html/vkspec.html#VK_NV_ray_tracing_motion_blur Vulkan Specification >
module Vulkan.Extensions.VK_NV_ray_tracing_motion_blur ( PhysicalDeviceRayTracingMotionBlurFeaturesNV(..)
, AccelerationStructureGeometryMotionTrianglesDataNV(..)
, AccelerationStructureMotionInfoNV(..)
, SRTDataNV(..)
, AccelerationStructureSRTMotionInstanceNV(..)
, AccelerationStructureMatrixMotionInstanceNV(..)
, AccelerationStructureMotionInstanceNV(..)
, AccelerationStructureMotionInstanceDataNV(..)
, AccelerationStructureMotionInfoFlagsNV(..)
, AccelerationStructureMotionInstanceFlagsNV(..)
, AccelerationStructureMotionInstanceTypeNV( ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_STATIC_NV
, ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_MATRIX_MOTION_NV
, ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV
, ..
)
, NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION
, pattern NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION
, NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME
, pattern NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME
, TransformMatrixKHR(..)
, AccelerationStructureInstanceKHR(..)
, DeviceOrHostAddressConstKHR(..)
, GeometryInstanceFlagBitsKHR(..)
, GeometryInstanceFlagsKHR
, BuildAccelerationStructureFlagBitsKHR(..)
, BuildAccelerationStructureFlagsKHR
, AccelerationStructureCreateFlagBitsKHR(..)
, AccelerationStructureCreateFlagsKHR
) where
import Data.Bits (Bits)
import Data.Bits (FiniteBits)
import Data.Bits (shiftL)
import Data.Bits (shiftR)
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import Control.Exception.Base (bracket)
import Data.Bits ((.&.))
import Data.Bits ((.|.))
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Marshal.Alloc (callocBytes)
import Foreign.Marshal.Alloc (free)
import GHC.Ptr (castPtr)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import GHC.Show (showString)
import GHC.Show (showsPrec)
import Numeric (showHex)
import Data.Coerce (coerce)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import Control.Monad.Trans.Cont (runContT)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero)
import Vulkan.Zero (Zero(..))
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.C.Types (CFloat)
import Foreign.C.Types (CFloat(..))
import Foreign.C.Types (CFloat(CFloat))
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import Data.Int (Int32)
import Foreign.Ptr (Ptr)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Data.Word (Word32)
import Data.Word (Word64)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.Extensions.VK_KHR_acceleration_structure (AccelerationStructureInstanceKHR)
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Extensions.VK_KHR_acceleration_structure (DeviceOrHostAddressConstKHR)
import Vulkan.Core10.FundamentalTypes (Flags)
import Vulkan.Extensions.VK_KHR_acceleration_structure (GeometryInstanceFlagsKHR)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Extensions.VK_KHR_acceleration_structure (TransformMatrixKHR)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_MOTION_TRIANGLES_DATA_NV))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MOTION_INFO_NV))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_MOTION_BLUR_FEATURES_NV))
import Vulkan.Extensions.VK_KHR_acceleration_structure (AccelerationStructureCreateFlagBitsKHR(..))
import Vulkan.Extensions.VK_KHR_acceleration_structure (AccelerationStructureCreateFlagsKHR)
import Vulkan.Extensions.VK_KHR_acceleration_structure (AccelerationStructureInstanceKHR(..))
import Vulkan.Extensions.VK_KHR_acceleration_structure (BuildAccelerationStructureFlagBitsKHR(..))
import Vulkan.Extensions.VK_KHR_acceleration_structure (BuildAccelerationStructureFlagsKHR)
import Vulkan.Extensions.VK_KHR_acceleration_structure (DeviceOrHostAddressConstKHR(..))
import Vulkan.Extensions.VK_KHR_acceleration_structure (GeometryInstanceFlagBitsKHR(..))
import Vulkan.Extensions.VK_KHR_acceleration_structure (GeometryInstanceFlagsKHR)
import Vulkan.Extensions.VK_KHR_acceleration_structure (TransformMatrixKHR(..))
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 '
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2 ' ,
supported . ' PhysicalDeviceRayTracingMotionBlurFeaturesNV ' also be
used in the @pNext@ chain of ' Vulkan . Core10.Device . DeviceCreateInfo ' to
' Vulkan . Core10.FundamentalTypes . Bool32 ' ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data PhysicalDeviceRayTracingMotionBlurFeaturesNV = PhysicalDeviceRayTracingMotionBlurFeaturesNV
| # features - rayTracingMotionBlur # @rayTracingMotionBlur@ indicates whether
rayTracingMotionBlur :: Bool
rayTracingMotionBlurPipelineTraceRaysIndirect :: Bool
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDeviceRayTracingMotionBlurFeaturesNV)
#endif
deriving instance Show PhysicalDeviceRayTracingMotionBlurFeaturesNV
instance ToCStruct PhysicalDeviceRayTracingMotionBlurFeaturesNV where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDeviceRayTracingMotionBlurFeaturesNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_MOTION_BLUR_FEATURES_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (rayTracingMotionBlur))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (rayTracingMotionBlurPipelineTraceRaysIndirect))
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_MOTION_BLUR_FEATURES_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct PhysicalDeviceRayTracingMotionBlurFeaturesNV where
peekCStruct p = do
rayTracingMotionBlur <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
rayTracingMotionBlurPipelineTraceRaysIndirect <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32))
pure $ PhysicalDeviceRayTracingMotionBlurFeaturesNV
(bool32ToBool rayTracingMotionBlur)
(bool32ToBool rayTracingMotionBlurPipelineTraceRaysIndirect)
instance Storable PhysicalDeviceRayTracingMotionBlurFeaturesNV where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDeviceRayTracingMotionBlurFeaturesNV where
zero = PhysicalDeviceRayTracingMotionBlurFeaturesNV
zero
zero
' Vulkan . Extensions . VK_KHR_acceleration_structure . AccelerationStructureGeometryTrianglesDataKHR '
triangles in the geometry at time 0.0 and the @vertexData@ in
vertex positions at time 1.0 , with positions linearly interpolated at
Indexing for ' AccelerationStructureGeometryMotionTrianglesDataNV '
@vertexData@ is equivalent to the basic vertex position data .
' Vulkan . Extensions . VK_KHR_acceleration_structure . DeviceOrHostAddressConstKHR ' ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data AccelerationStructureGeometryMotionTrianglesDataNV = AccelerationStructureGeometryMotionTrianglesDataNV
| @vertexData@ is a pointer to vertex data for this geometry at time 1.0
vertexData :: DeviceOrHostAddressConstKHR }
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (AccelerationStructureGeometryMotionTrianglesDataNV)
#endif
deriving instance Show AccelerationStructureGeometryMotionTrianglesDataNV
instance ToCStruct AccelerationStructureGeometryMotionTrianglesDataNV where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p AccelerationStructureGeometryMotionTrianglesDataNV{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_MOTION_TRIANGLES_DATA_NV)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
ContT $ pokeCStruct ((p `plusPtr` 16 :: Ptr DeviceOrHostAddressConstKHR)) (vertexData) . ($ ())
lift $ f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_MOTION_TRIANGLES_DATA_NV)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
ContT $ pokeCStruct ((p `plusPtr` 16 :: Ptr DeviceOrHostAddressConstKHR)) (zero) . ($ ())
lift $ f
instance Zero AccelerationStructureGeometryMotionTrianglesDataNV where
zero = AccelerationStructureGeometryMotionTrianglesDataNV
zero
' ' ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data AccelerationStructureMotionInfoNV = AccelerationStructureMotionInfoNV
| @maxInstances@ is the maximum number of instances that be used in
maxInstances :: Word32
/must/ be @0@
flags :: AccelerationStructureMotionInfoFlagsNV
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (AccelerationStructureMotionInfoNV)
#endif
deriving instance Show AccelerationStructureMotionInfoNV
instance ToCStruct AccelerationStructureMotionInfoNV where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p AccelerationStructureMotionInfoNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MOTION_INFO_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Word32)) (maxInstances)
poke ((p `plusPtr` 20 :: Ptr AccelerationStructureMotionInfoFlagsNV)) (flags)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MOTION_INFO_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Word32)) (zero)
f
instance FromCStruct AccelerationStructureMotionInfoNV where
peekCStruct p = do
maxInstances <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32))
flags <- peek @AccelerationStructureMotionInfoFlagsNV ((p `plusPtr` 20 :: Ptr AccelerationStructureMotionInfoFlagsNV))
pure $ AccelerationStructureMotionInfoNV
maxInstances flags
instance Storable AccelerationStructureMotionInfoNV where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero AccelerationStructureMotionInfoNV where
zero = AccelerationStructureMotionInfoNV
zero
zero
| VkSRTDataNV - Structure specifying a transform in SRT decomposition
This transform decomposition consists of three elements . The first is a
\[S =
sx & a & b & pvx \\
0 & sy & c & pvy \\
}
\right)\ ]
- @R@ = [ @qx@ , @qy@ , @qz@ , @qw@ ]
This is a rotation around a conceptual normalized axis [ ax , ay , ] of
amount @theta@ such that :
- [ @qx@ , @qy@ , @qz@ ] = sin(@theta@\/2 ) × [ @ax@ , @ay@ , @az@ ]
1 & 0 & 0 & tx \\
0 & 1 & 0 & ty \\
0 & 0 & 1 & tz
}
\right)\ ]
' AccelerationStructureSRTMotionInstanceNV '
data SRTDataNV = SRTDataNV
| @sx@ is the x component of the scale of the transform
sx :: Float
| @a@ is one component of the shear for the transform
a :: Float
| @b@ is one component of the shear for the transform
b :: Float
pvx :: Float
sy :: Float
| @c@ is one component of the shear for the transform
c :: Float
pvy :: Float
sz :: Float
pvz :: Float
| @qx@ is the x component of the rotation quaternion
qx :: Float
| @qy@ is the y component of the rotation quaternion
qy :: Float
qz :: Float
qw :: Float
| is the x component of the post - rotation translation
tx :: Float
| @ty@ is the y component of the post - rotation translation
ty :: Float
| @tz@ is the z component of the post - rotation translation
tz :: Float
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SRTDataNV)
#endif
deriving instance Show SRTDataNV
instance ToCStruct SRTDataNV where
withCStruct x f = allocaBytes 64 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SRTDataNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr CFloat)) (CFloat (sx))
poke ((p `plusPtr` 4 :: Ptr CFloat)) (CFloat (a))
poke ((p `plusPtr` 8 :: Ptr CFloat)) (CFloat (b))
poke ((p `plusPtr` 12 :: Ptr CFloat)) (CFloat (pvx))
poke ((p `plusPtr` 16 :: Ptr CFloat)) (CFloat (sy))
poke ((p `plusPtr` 20 :: Ptr CFloat)) (CFloat (c))
poke ((p `plusPtr` 24 :: Ptr CFloat)) (CFloat (pvy))
poke ((p `plusPtr` 28 :: Ptr CFloat)) (CFloat (sz))
poke ((p `plusPtr` 32 :: Ptr CFloat)) (CFloat (pvz))
poke ((p `plusPtr` 36 :: Ptr CFloat)) (CFloat (qx))
poke ((p `plusPtr` 40 :: Ptr CFloat)) (CFloat (qy))
poke ((p `plusPtr` 44 :: Ptr CFloat)) (CFloat (qz))
poke ((p `plusPtr` 48 :: Ptr CFloat)) (CFloat (qw))
poke ((p `plusPtr` 52 :: Ptr CFloat)) (CFloat (tx))
poke ((p `plusPtr` 56 :: Ptr CFloat)) (CFloat (ty))
poke ((p `plusPtr` 60 :: Ptr CFloat)) (CFloat (tz))
f
cStructSize = 64
cStructAlignment = 4
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 4 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 8 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 12 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 16 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 20 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 24 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 28 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 32 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 36 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 40 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 44 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 48 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 52 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 56 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 60 :: Ptr CFloat)) (CFloat (zero))
f
instance FromCStruct SRTDataNV where
peekCStruct p = do
sx <- peek @CFloat ((p `plusPtr` 0 :: Ptr CFloat))
a <- peek @CFloat ((p `plusPtr` 4 :: Ptr CFloat))
b <- peek @CFloat ((p `plusPtr` 8 :: Ptr CFloat))
pvx <- peek @CFloat ((p `plusPtr` 12 :: Ptr CFloat))
sy <- peek @CFloat ((p `plusPtr` 16 :: Ptr CFloat))
c <- peek @CFloat ((p `plusPtr` 20 :: Ptr CFloat))
pvy <- peek @CFloat ((p `plusPtr` 24 :: Ptr CFloat))
sz <- peek @CFloat ((p `plusPtr` 28 :: Ptr CFloat))
pvz <- peek @CFloat ((p `plusPtr` 32 :: Ptr CFloat))
qx <- peek @CFloat ((p `plusPtr` 36 :: Ptr CFloat))
qy <- peek @CFloat ((p `plusPtr` 40 :: Ptr CFloat))
qz <- peek @CFloat ((p `plusPtr` 44 :: Ptr CFloat))
qw <- peek @CFloat ((p `plusPtr` 48 :: Ptr CFloat))
tx <- peek @CFloat ((p `plusPtr` 52 :: Ptr CFloat))
ty <- peek @CFloat ((p `plusPtr` 56 :: Ptr CFloat))
tz <- peek @CFloat ((p `plusPtr` 60 :: Ptr CFloat))
pure $ SRTDataNV
(coerce @CFloat @Float sx)
(coerce @CFloat @Float a)
(coerce @CFloat @Float b)
(coerce @CFloat @Float pvx)
(coerce @CFloat @Float sy)
(coerce @CFloat @Float c)
(coerce @CFloat @Float pvy)
(coerce @CFloat @Float sz)
(coerce @CFloat @Float pvz)
(coerce @CFloat @Float qx)
(coerce @CFloat @Float qy)
(coerce @CFloat @Float qz)
(coerce @CFloat @Float qw)
(coerce @CFloat @Float tx)
(coerce @CFloat @Float ty)
(coerce @CFloat @Float tz)
instance Storable SRTDataNV where
sizeOf ~_ = 64
alignment ~_ = 4
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero SRTDataNV where
zero = SRTDataNV
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
zero
single acceleration structure SRT motion instance for building into an
The transform for a SRT motion instance at a point in time is derived
from component - wise linear interpolation of the two SRT transforms . That
is , for a @time@ in [ 0,1 ] the resulting transform is
' Vulkan . Extensions . VK_KHR_acceleration_structure . GeometryInstanceFlagsKHR ' ,
data AccelerationStructureSRTMotionInstanceNV = AccelerationStructureSRTMotionInstanceNV
transformT0 :: SRTDataNV
be applied to the acceleration structure at time 1 .
transformT1 :: SRTDataNV
| @instanceCustomIndex@ is a 24 - bit user - specified index value accessible
@uint32_t@ was specified in their place
- @instanceCustomIndex@ occupies the 24 least significant bits of that
- @mask@ occupies the 8 most significant bits of that memory
instanceCustomIndex :: Word32
| @mask@ is an 8 - bit visibility mask for the geometry . The instance /may/
mask :: Word32
| @instanceShaderBindingTableRecordOffset@ is a 24 - bit offset used in
@instanceShaderBindingTableRecordOffset@ and occupy the same
memory as if a single @uint32_t@ was specified in their place
- @instanceShaderBindingTableRecordOffset@ occupies the 24 least
- @flags@ occupies the 8 most significant bits of that memory
instanceShaderBindingTableRecordOffset :: Word32
| @flags@ is an 8 - bit mask of
' Vulkan . Extensions . VK_KHR_acceleration_structure . GeometryInstanceFlagBitsKHR '
' Vulkan . Extensions . VK_KHR_acceleration_structure . GeometryInstanceFlagBitsKHR '
flags :: GeometryInstanceFlagsKHR
' Vulkan . Extensions . VK_KHR_acceleration_structure.getAccelerationStructureDeviceAddressKHR '
' Vulkan . Extensions . VK_NV_ray_tracing.getAccelerationStructureHandleNV '
- a ' Vulkan . Extensions . Handles . AccelerationStructureKHR ' object ( used
accelerationStructureReference :: Word64
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (AccelerationStructureSRTMotionInstanceNV)
#endif
deriving instance Show AccelerationStructureSRTMotionInstanceNV
instance ToCStruct AccelerationStructureSRTMotionInstanceNV where
withCStruct x f = allocaBytes 144 $ \p -> pokeCStruct p x (f p)
pokeCStruct p AccelerationStructureSRTMotionInstanceNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr SRTDataNV)) (transformT0)
poke ((p `plusPtr` 64 :: Ptr SRTDataNV)) (transformT1)
poke ((p `plusPtr` 128 :: Ptr Word32)) (((coerce @_ @Word32 (mask)) `shiftL` 24) .|. (instanceCustomIndex))
poke ((p `plusPtr` 132 :: Ptr Word32)) (((coerce @_ @Word32 (flags)) `shiftL` 24) .|. (instanceShaderBindingTableRecordOffset))
poke ((p `plusPtr` 136 :: Ptr Word64)) (accelerationStructureReference)
f
cStructSize = 144
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr SRTDataNV)) (zero)
poke ((p `plusPtr` 64 :: Ptr SRTDataNV)) (zero)
poke ((p `plusPtr` 136 :: Ptr Word64)) (zero)
f
instance FromCStruct AccelerationStructureSRTMotionInstanceNV where
peekCStruct p = do
transformT0 <- peekCStruct @SRTDataNV ((p `plusPtr` 0 :: Ptr SRTDataNV))
transformT1 <- peekCStruct @SRTDataNV ((p `plusPtr` 64 :: Ptr SRTDataNV))
instanceCustomIndex <- peek @Word32 ((p `plusPtr` 128 :: Ptr Word32))
let instanceCustomIndex' = ((instanceCustomIndex .&. coerce @Word32 0xffffff))
mask <- peek @Word32 ((p `plusPtr` 128 :: Ptr Word32))
let mask' = ((((mask `shiftR` 24)) .&. coerce @Word32 0xff))
instanceShaderBindingTableRecordOffset <- peek @Word32 ((p `plusPtr` 132 :: Ptr Word32))
let instanceShaderBindingTableRecordOffset' = ((instanceShaderBindingTableRecordOffset .&. coerce @Word32 0xffffff))
flags <- peek @GeometryInstanceFlagsKHR ((p `plusPtr` 132 :: Ptr GeometryInstanceFlagsKHR))
let flags' = ((((flags `shiftR` 24)) .&. coerce @Word32 0xff))
accelerationStructureReference <- peek @Word64 ((p `plusPtr` 136 :: Ptr Word64))
pure $ AccelerationStructureSRTMotionInstanceNV
transformT0
transformT1
instanceCustomIndex'
mask'
instanceShaderBindingTableRecordOffset'
flags'
accelerationStructureReference
instance Storable AccelerationStructureSRTMotionInstanceNV where
sizeOf ~_ = 144
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero AccelerationStructureSRTMotionInstanceNV where
zero = AccelerationStructureSRTMotionInstanceNV
zero
zero
zero
zero
zero
zero
zero
by component - wise linear interpolation of the two transforms . That is ,
for a @time@ in [ 0,1 ] the resulting transform is
' Vulkan . Extensions . VK_KHR_acceleration_structure . GeometryInstanceFlagsKHR ' ,
' Vulkan . Extensions . VK_KHR_acceleration_structure . TransformMatrixKHR '
data AccelerationStructureMatrixMotionInstanceNV = AccelerationStructureMatrixMotionInstanceNV
' Vulkan . Extensions . VK_KHR_acceleration_structure . TransformMatrixKHR '
transformT0 :: TransformMatrixKHR
' Vulkan . Extensions . VK_KHR_acceleration_structure . TransformMatrixKHR '
structure at time 1 .
transformT1 :: TransformMatrixKHR
| @instanceCustomIndex@ is a 24 - bit user - specified index value accessible
@uint32_t@ was specified in their place
- @instanceCustomIndex@ occupies the 24 least significant bits of that
- @mask@ occupies the 8 most significant bits of that memory
instanceCustomIndex :: Word32
| @mask@ is an 8 - bit visibility mask for the geometry . The instance /may/
mask :: Word32
| @instanceShaderBindingTableRecordOffset@ is a 24 - bit offset used in
@instanceShaderBindingTableRecordOffset@ and occupy the same
memory as if a single @uint32_t@ was specified in their place
- @instanceShaderBindingTableRecordOffset@ occupies the 24 least
- @flags@ occupies the 8 most significant bits of that memory
instanceShaderBindingTableRecordOffset :: Word32
| @flags@ is an 8 - bit mask of
' Vulkan . Extensions . VK_KHR_acceleration_structure . GeometryInstanceFlagBitsKHR '
' Vulkan . Extensions . VK_KHR_acceleration_structure . GeometryInstanceFlagBitsKHR '
flags :: GeometryInstanceFlagsKHR
' Vulkan . Extensions . VK_KHR_acceleration_structure.getAccelerationStructureDeviceAddressKHR '
' Vulkan . Extensions . VK_NV_ray_tracing.getAccelerationStructureHandleNV '
- a ' Vulkan . Extensions . Handles . AccelerationStructureKHR ' object ( used
accelerationStructureReference :: Word64
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (AccelerationStructureMatrixMotionInstanceNV)
#endif
deriving instance Show AccelerationStructureMatrixMotionInstanceNV
instance ToCStruct AccelerationStructureMatrixMotionInstanceNV where
withCStruct x f = allocaBytes 112 $ \p -> pokeCStruct p x (f p)
pokeCStruct p AccelerationStructureMatrixMotionInstanceNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr TransformMatrixKHR)) (transformT0)
poke ((p `plusPtr` 48 :: Ptr TransformMatrixKHR)) (transformT1)
poke ((p `plusPtr` 96 :: Ptr Word32)) (((coerce @_ @Word32 (mask)) `shiftL` 24) .|. (instanceCustomIndex))
poke ((p `plusPtr` 100 :: Ptr Word32)) (((coerce @_ @Word32 (flags)) `shiftL` 24) .|. (instanceShaderBindingTableRecordOffset))
poke ((p `plusPtr` 104 :: Ptr Word64)) (accelerationStructureReference)
f
cStructSize = 112
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr TransformMatrixKHR)) (zero)
poke ((p `plusPtr` 48 :: Ptr TransformMatrixKHR)) (zero)
poke ((p `plusPtr` 104 :: Ptr Word64)) (zero)
f
instance FromCStruct AccelerationStructureMatrixMotionInstanceNV where
peekCStruct p = do
transformT0 <- peekCStruct @TransformMatrixKHR ((p `plusPtr` 0 :: Ptr TransformMatrixKHR))
transformT1 <- peekCStruct @TransformMatrixKHR ((p `plusPtr` 48 :: Ptr TransformMatrixKHR))
instanceCustomIndex <- peek @Word32 ((p `plusPtr` 96 :: Ptr Word32))
let instanceCustomIndex' = ((instanceCustomIndex .&. coerce @Word32 0xffffff))
mask <- peek @Word32 ((p `plusPtr` 96 :: Ptr Word32))
let mask' = ((((mask `shiftR` 24)) .&. coerce @Word32 0xff))
instanceShaderBindingTableRecordOffset <- peek @Word32 ((p `plusPtr` 100 :: Ptr Word32))
let instanceShaderBindingTableRecordOffset' = ((instanceShaderBindingTableRecordOffset .&. coerce @Word32 0xffffff))
flags <- peek @GeometryInstanceFlagsKHR ((p `plusPtr` 100 :: Ptr GeometryInstanceFlagsKHR))
let flags' = ((((flags `shiftR` 24)) .&. coerce @Word32 0xff))
accelerationStructureReference <- peek @Word64 ((p `plusPtr` 104 :: Ptr Word64))
pure $ AccelerationStructureMatrixMotionInstanceNV
transformT0
transformT1
instanceCustomIndex'
mask'
instanceShaderBindingTableRecordOffset'
flags'
accelerationStructureReference
instance Storable AccelerationStructureMatrixMotionInstanceNV where
sizeOf ~_ = 112
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero AccelerationStructureMatrixMotionInstanceNV where
zero = AccelerationStructureMatrixMotionInstanceNV
zero
zero
zero
zero
zero
zero
zero
final structure should be 152 bytes in size .
@flags@ /must/ be @0@
' ' , the
' Vulkan . Extensions . VK_KHR_acceleration_structure . AccelerationStructureInstanceKHR '
' ' , the
@matrixMotionInstance@ member of @data@ /must/ be a valid
data AccelerationStructureMotionInstanceNV = AccelerationStructureMotionInstanceNV
type' :: AccelerationStructureMotionInstanceTypeNV
flags :: AccelerationStructureMotionInstanceFlagsNV
data' :: AccelerationStructureMotionInstanceDataNV
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (AccelerationStructureMotionInstanceNV)
#endif
deriving instance Show AccelerationStructureMotionInstanceNV
instance ToCStruct AccelerationStructureMotionInstanceNV where
withCStruct x f = allocaBytes 152 $ \p -> pokeCStruct p x (f p)
pokeCStruct p AccelerationStructureMotionInstanceNV{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr AccelerationStructureMotionInstanceTypeNV)) (type')
lift $ poke ((p `plusPtr` 4 :: Ptr AccelerationStructureMotionInstanceFlagsNV)) (flags)
ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr AccelerationStructureMotionInstanceDataNV)) (data') . ($ ())
lift $ f
cStructSize = 152
cStructAlignment = 8
pokeZeroCStruct p f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr AccelerationStructureMotionInstanceTypeNV)) (zero)
ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr AccelerationStructureMotionInstanceDataNV)) (zero) . ($ ())
lift $ f
instance Zero AccelerationStructureMotionInstanceNV where
zero = AccelerationStructureMotionInstanceNV
zero
zero
zero
data AccelerationStructureMotionInstanceDataNV
= StaticInstance AccelerationStructureInstanceKHR
| MatrixMotionInstance AccelerationStructureMatrixMotionInstanceNV
| SrtMotionInstance AccelerationStructureSRTMotionInstanceNV
deriving (Show)
instance ToCStruct AccelerationStructureMotionInstanceDataNV where
withCStruct x f = allocaBytes 144 $ \p -> pokeCStruct p x (f p)
pokeCStruct :: Ptr AccelerationStructureMotionInstanceDataNV -> AccelerationStructureMotionInstanceDataNV -> IO a -> IO a
pokeCStruct p = (. const) . runContT . \case
StaticInstance v -> lift $ poke (castPtr @_ @AccelerationStructureInstanceKHR p) (v)
MatrixMotionInstance v -> lift $ poke (castPtr @_ @AccelerationStructureMatrixMotionInstanceNV p) (v)
SrtMotionInstance v -> lift $ poke (castPtr @_ @AccelerationStructureSRTMotionInstanceNV p) (v)
pokeZeroCStruct :: Ptr AccelerationStructureMotionInstanceDataNV -> IO b -> IO b
pokeZeroCStruct _ f = f
cStructSize = 144
cStructAlignment = 8
instance Zero AccelerationStructureMotionInstanceDataNV where
zero = SrtMotionInstance zero
' ' is a bitmask type for setting a
newtype AccelerationStructureMotionInfoFlagsNV = AccelerationStructureMotionInfoFlagsNV Flags
deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits)
conNameAccelerationStructureMotionInfoFlagsNV :: String
conNameAccelerationStructureMotionInfoFlagsNV = "AccelerationStructureMotionInfoFlagsNV"
enumPrefixAccelerationStructureMotionInfoFlagsNV :: String
enumPrefixAccelerationStructureMotionInfoFlagsNV = ""
showTableAccelerationStructureMotionInfoFlagsNV :: [(AccelerationStructureMotionInfoFlagsNV, String)]
showTableAccelerationStructureMotionInfoFlagsNV = []
instance Show AccelerationStructureMotionInfoFlagsNV where
showsPrec =
enumShowsPrec
enumPrefixAccelerationStructureMotionInfoFlagsNV
showTableAccelerationStructureMotionInfoFlagsNV
conNameAccelerationStructureMotionInfoFlagsNV
(\(AccelerationStructureMotionInfoFlagsNV x) -> x)
(\x -> showString "0x" . showHex x)
instance Read AccelerationStructureMotionInfoFlagsNV where
readPrec =
enumReadPrec
enumPrefixAccelerationStructureMotionInfoFlagsNV
showTableAccelerationStructureMotionInfoFlagsNV
conNameAccelerationStructureMotionInfoFlagsNV
AccelerationStructureMotionInfoFlagsNV
' AccelerationStructureMotionInstanceFlagsNV ' is a bitmask type for
newtype AccelerationStructureMotionInstanceFlagsNV = AccelerationStructureMotionInstanceFlagsNV Flags
deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits)
conNameAccelerationStructureMotionInstanceFlagsNV :: String
conNameAccelerationStructureMotionInstanceFlagsNV = "AccelerationStructureMotionInstanceFlagsNV"
enumPrefixAccelerationStructureMotionInstanceFlagsNV :: String
enumPrefixAccelerationStructureMotionInstanceFlagsNV = ""
showTableAccelerationStructureMotionInstanceFlagsNV :: [(AccelerationStructureMotionInstanceFlagsNV, String)]
showTableAccelerationStructureMotionInstanceFlagsNV = []
instance Show AccelerationStructureMotionInstanceFlagsNV where
showsPrec =
enumShowsPrec
enumPrefixAccelerationStructureMotionInstanceFlagsNV
showTableAccelerationStructureMotionInstanceFlagsNV
conNameAccelerationStructureMotionInstanceFlagsNV
(\(AccelerationStructureMotionInstanceFlagsNV x) -> x)
(\x -> showString "0x" . showHex x)
instance Read AccelerationStructureMotionInstanceFlagsNV where
readPrec =
enumReadPrec
enumPrefixAccelerationStructureMotionInstanceFlagsNV
showTableAccelerationStructureMotionInstanceFlagsNV
conNameAccelerationStructureMotionInstanceFlagsNV
AccelerationStructureMotionInstanceFlagsNV
newtype AccelerationStructureMotionInstanceTypeNV = AccelerationStructureMotionInstanceTypeNV Int32
deriving newtype (Eq, Ord, Storable, Zero)
| ' ' specifies that
pattern ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_STATIC_NV = AccelerationStructureMotionInstanceTypeNV 0
| ' ' specifies
interpolation between two matrices .
pattern ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_MATRIX_MOTION_NV = AccelerationStructureMotionInstanceTypeNV 1
interpolation in the SRT decomposition .
pattern ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV = AccelerationStructureMotionInstanceTypeNV 2
# COMPLETE
, , ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV : :
AccelerationStructureMotionInstanceTypeNV
#
ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_STATIC_NV
, ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_MATRIX_MOTION_NV
, ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV ::
AccelerationStructureMotionInstanceTypeNV
#-}
conNameAccelerationStructureMotionInstanceTypeNV :: String
conNameAccelerationStructureMotionInstanceTypeNV = "AccelerationStructureMotionInstanceTypeNV"
enumPrefixAccelerationStructureMotionInstanceTypeNV :: String
enumPrefixAccelerationStructureMotionInstanceTypeNV = "ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_"
showTableAccelerationStructureMotionInstanceTypeNV :: [(AccelerationStructureMotionInstanceTypeNV, String)]
showTableAccelerationStructureMotionInstanceTypeNV =
[
( ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_STATIC_NV
, "STATIC_NV"
)
,
( ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_MATRIX_MOTION_NV
, "MATRIX_MOTION_NV"
)
,
( ACCELERATION_STRUCTURE_MOTION_INSTANCE_TYPE_SRT_MOTION_NV
, "SRT_MOTION_NV"
)
]
instance Show AccelerationStructureMotionInstanceTypeNV where
showsPrec =
enumShowsPrec
enumPrefixAccelerationStructureMotionInstanceTypeNV
showTableAccelerationStructureMotionInstanceTypeNV
conNameAccelerationStructureMotionInstanceTypeNV
(\(AccelerationStructureMotionInstanceTypeNV x) -> x)
(showsPrec 11)
instance Read AccelerationStructureMotionInstanceTypeNV where
readPrec =
enumReadPrec
enumPrefixAccelerationStructureMotionInstanceTypeNV
showTableAccelerationStructureMotionInstanceTypeNV
conNameAccelerationStructureMotionInstanceTypeNV
AccelerationStructureMotionInstanceTypeNV
type NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION = 1
No documentation found for TopLevel " VK_NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION "
pattern NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION :: forall a . Integral a => a
pattern NV_RAY_TRACING_MOTION_BLUR_SPEC_VERSION = 1
type NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME = "VK_NV_ray_tracing_motion_blur"
No documentation found for TopLevel " "
pattern NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME = "VK_NV_ray_tracing_motion_blur"
|
43539484a6a5051334e63f0d5dd5e2e4abafa7c8be1f8d08ba0eefae5c9852d7 | aryx/xix | draw_marshal.ml | open Common
open Point
open Rectangle
open Color
(* todo: sanity check range *)
let bp_byte x =
String.make 1 (Char.chr x)
let bp_short x =
(* less: sanity check range? *)
let x1 = Char.chr (x land 0xFF) in
let x2 = Char.chr ((x asr 8) land 0xFF) in
let str = String.make 2 ' ' in
str.[0] <- x1;
str.[1] <- x2;
str
(* less: use commons/byte_order.ml? *)
let bp_long x =
let x1 = Char.chr (x land 0xFF) in
let x2 = Char.chr ((x asr 8) land 0xFF) in
let x3 = Char.chr ((x asr 16) land 0xFF) in
let x4 = Char.chr ((x asr 24) land 0xFF) in
let str = String.make 4 ' ' in
str.[0] <- x1;
str.[1] <- x2;
str.[2] <- x3;
str.[3] <- x4;
str
let bp_bool b =
if b
then String.make 1 (Char.chr 1)
else String.make 1 (Char.chr 0)
let bp_point pt =
bp_long pt.x ^ bp_long pt.y
let bp_rect r =
bp_long r.min.x ^ bp_long r.min.y ^
bp_long r.max.x ^ bp_long r.max.y
let bp_color c =
bp_byte c.a ^ bp_byte c.b ^ bp_byte c.g ^ bp_byte c.r
let bp_chans chans =
let i = Channel.mk_channels_serial chans in
bp_long i
(* alt:
* marshall full AST if kernel was written in OCaml:
*
type msg =
| AllocImage of int
| Draw of int
| Line of int
| Ellipse of int
| Arc of int
*)
| null | https://raw.githubusercontent.com/aryx/xix/60ce1bd9a3f923e0e8bb2192f8938a9aa49c739c/lib_graphics/draw/draw_marshal.ml | ocaml | todo: sanity check range
less: sanity check range?
less: use commons/byte_order.ml?
alt:
* marshall full AST if kernel was written in OCaml:
*
type msg =
| AllocImage of int
| Draw of int
| Line of int
| Ellipse of int
| Arc of int
| open Common
open Point
open Rectangle
open Color
let bp_byte x =
String.make 1 (Char.chr x)
let bp_short x =
let x1 = Char.chr (x land 0xFF) in
let x2 = Char.chr ((x asr 8) land 0xFF) in
let str = String.make 2 ' ' in
str.[0] <- x1;
str.[1] <- x2;
str
let bp_long x =
let x1 = Char.chr (x land 0xFF) in
let x2 = Char.chr ((x asr 8) land 0xFF) in
let x3 = Char.chr ((x asr 16) land 0xFF) in
let x4 = Char.chr ((x asr 24) land 0xFF) in
let str = String.make 4 ' ' in
str.[0] <- x1;
str.[1] <- x2;
str.[2] <- x3;
str.[3] <- x4;
str
let bp_bool b =
if b
then String.make 1 (Char.chr 1)
else String.make 1 (Char.chr 0)
let bp_point pt =
bp_long pt.x ^ bp_long pt.y
let bp_rect r =
bp_long r.min.x ^ bp_long r.min.y ^
bp_long r.max.x ^ bp_long r.max.y
let bp_color c =
bp_byte c.a ^ bp_byte c.b ^ bp_byte c.g ^ bp_byte c.r
let bp_chans chans =
let i = Channel.mk_channels_serial chans in
bp_long i
|
517851788b0b6765d78a0d1c0cbba30c83f7a16f493881ee6607582cbb4d1721 | ivanjovanovic/sicp | e-3.15.scm | Exercise 3.15 . Draw box - and - pointer diagrams to explain the effect of
; set-to-wow! on the structures z1 and z2 above.
; ------------------------------------------------------------
; I will not draw them here, but I did them on paper. Could have scanned
; them if my handwriting is not destroyed by typing :)
In case of z1 , both car and cdr point to the same x and therefor
; when rendering output of z2 we wil see
; ((wow b) wow b)
;
In case of z2 both car and cdr values point to the same symbo , but as
; soon as we change one, they will just point to the different symbols,
; but car and cdr pointers will still point ot different objects.
| null | https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/3.3/e-3.15.scm | scheme | set-to-wow! on the structures z1 and z2 above.
------------------------------------------------------------
I will not draw them here, but I did them on paper. Could have scanned
them if my handwriting is not destroyed by typing :)
when rendering output of z2 we wil see
((wow b) wow b)
soon as we change one, they will just point to the different symbols,
but car and cdr pointers will still point ot different objects. | Exercise 3.15 . Draw box - and - pointer diagrams to explain the effect of
In case of z1 , both car and cdr point to the same x and therefor
In case of z2 both car and cdr values point to the same symbo , but as
|
da7b5db709925fcc7214c67f57f512ba0e1673139cd5376693d65f9894bf385c | naryl/cl-tui | 7chat.lisp |
(defpackage cl-tui.examples
(:use :cl :cl-tui))
(in-package cl-tui.examples)
(define-frame log (log-frame) :on :root)
edit - frame implements a single - line text editor . It will misbehave if its height is not 1
(define-frame input (edit-frame :prompt "> ") :on :root :h 1)
(defun finish-input ()
;; Get text from edit-frame
(let ((text (get-text 'input)))
;; Append it to the log-frame
(append-line 'log text)
;; And clear the text in edit-frame
(clear-text 'input)))
(defun start ()
(with-screen ()
(set-split-type :root :vertical)
(append-line 'log "Enter some text.")
(append-line 'log "Esc to quit")
(loop
(refresh)
(let ((key (read-key)))
(case key
;; Esc and Newline are handled here
(#\Esc (return))
(#\Newline (finish-input))
(:key-up (cl-tui:scroll-log 'log 1))
(:key-down (cl-tui:scroll-log 'log -1))
;; Everything else is sent to the edit-frame.
(t (handle-key 'input key)))))))
| null | https://raw.githubusercontent.com/naryl/cl-tui/4e8a06f50c682fba48884e5a35a6d16101298c08/examples/7chat.lisp | lisp | Get text from edit-frame
Append it to the log-frame
And clear the text in edit-frame
Esc and Newline are handled here
Everything else is sent to the edit-frame. |
(defpackage cl-tui.examples
(:use :cl :cl-tui))
(in-package cl-tui.examples)
(define-frame log (log-frame) :on :root)
edit - frame implements a single - line text editor . It will misbehave if its height is not 1
(define-frame input (edit-frame :prompt "> ") :on :root :h 1)
(defun finish-input ()
(let ((text (get-text 'input)))
(append-line 'log text)
(clear-text 'input)))
(defun start ()
(with-screen ()
(set-split-type :root :vertical)
(append-line 'log "Enter some text.")
(append-line 'log "Esc to quit")
(loop
(refresh)
(let ((key (read-key)))
(case key
(#\Esc (return))
(#\Newline (finish-input))
(:key-up (cl-tui:scroll-log 'log 1))
(:key-down (cl-tui:scroll-log 'log -1))
(t (handle-key 'input key)))))))
|
91fe073cb104be883fa6ac39bf0737e3ca1db9fecb059be14dd963fbbff3b39f | xapi-project/xen-api | data_channel.mli |
* Copyright ( c ) 2012 Citrix Inc
*
* Permission to use , copy , modify , and 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 .
*
* Copyright (c) 2012 Citrix Inc
*
* Permission to use, copy, modify, and 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.
*
*)
(** a bidirectional channel which allows reading into and writing from
Cstruct.t buffers *)
type t = {
really_read: Cstruct.t -> unit Lwt.t
(** [really_read buffer] reads a whole [buffer] of data from the channel *)
; really_write: Cstruct.t -> unit Lwt.t
* [ buffer writes a whole [ buffer ] to the channel
; really_write_offset: int64 ref (** the current file write offset *)
; skip: int64 -> unit Lwt.t
(** [skip bytes] seeks past the next [bytes] bytes in the output *)
; close: unit -> unit Lwt.t (** [close ()] closes the channel *)
}
val of_fd : Lwt_unix.file_descr -> seekable:bool -> t Lwt.t
(** [of_fd fd seekable] creates a channel from a Lwt_unix.file_descr.
If [seekable] then seek() will be called on the fd *)
val of_ssl_fd : Lwt_unix.file_descr -> t Lwt.t
(** [of_ssl_fd fd] creates a channel from an SSL Lwt_unix.file_descr. *)
| null | https://raw.githubusercontent.com/xapi-project/xen-api/5c2fb7b8de6b511cf17f141f3d03895c6d767b55/ocaml/xen-api-client/lwt/data_channel.mli | ocaml | * a bidirectional channel which allows reading into and writing from
Cstruct.t buffers
* [really_read buffer] reads a whole [buffer] of data from the channel
* the current file write offset
* [skip bytes] seeks past the next [bytes] bytes in the output
* [close ()] closes the channel
* [of_fd fd seekable] creates a channel from a Lwt_unix.file_descr.
If [seekable] then seek() will be called on the fd
* [of_ssl_fd fd] creates a channel from an SSL Lwt_unix.file_descr. |
* Copyright ( c ) 2012 Citrix Inc
*
* Permission to use , copy , modify , and 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 .
*
* Copyright (c) 2012 Citrix Inc
*
* Permission to use, copy, modify, and 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.
*
*)
type t = {
really_read: Cstruct.t -> unit Lwt.t
; really_write: Cstruct.t -> unit Lwt.t
* [ buffer writes a whole [ buffer ] to the channel
; skip: int64 -> unit Lwt.t
}
val of_fd : Lwt_unix.file_descr -> seekable:bool -> t Lwt.t
val of_ssl_fd : Lwt_unix.file_descr -> t Lwt.t
|
64a8d35af9233fcd52d42999d40ddee03a5337ebe95eaa0437746dcfbf9ed78f | clojure-interop/aws-api | AbstractAmazonMachineLearningAsync.clj | (ns com.amazonaws.services.machinelearning.AbstractAmazonMachineLearningAsync
"Abstract implementation of AmazonMachineLearningAsync. Convenient method forms pass through to the
corresponding overload that takes a request object and an AsyncHandler, which throws an
UnsupportedOperationException."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.machinelearning AbstractAmazonMachineLearningAsync]))
(defn create-realtime-endpoint-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateRealtimeEndpointRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateRealtimeEndpoint operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateRealtimeEndpointResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateRealtimeEndpointRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createRealtimeEndpointAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateRealtimeEndpointRequest request]
(-> this (.createRealtimeEndpointAsync request))))
(defn create-ml-model-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateMLModelRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateMLModel operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateMLModelResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateMLModelRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createMLModelAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateMLModelRequest request]
(-> this (.createMLModelAsync request))))
(defn predict-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.PredictRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the Predict operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.PredictResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.PredictRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.predictAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.PredictRequest request]
(-> this (.predictAsync request))))
(defn delete-evaluation-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DeleteEvaluationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteEvaluation operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DeleteEvaluationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteEvaluationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteEvaluationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteEvaluationRequest request]
(-> this (.deleteEvaluationAsync request))))
(defn create-data-source-from-rds-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateDataSourceFromRDSRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateDataSourceFromRDS operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateDataSourceFromRDSResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateDataSourceFromRDSRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createDataSourceFromRDSAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateDataSourceFromRDSRequest request]
(-> this (.createDataSourceFromRDSAsync request))))
(defn delete-tags-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DeleteTagsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteTags operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DeleteTagsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteTagsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteTagsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteTagsRequest request]
(-> this (.deleteTagsAsync request))))
(defn get-batch-prediction-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.GetBatchPredictionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetBatchPrediction operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.GetBatchPredictionResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetBatchPredictionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getBatchPredictionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetBatchPredictionRequest request]
(-> this (.getBatchPredictionAsync request))))
(defn get-evaluation-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.GetEvaluationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetEvaluation operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.GetEvaluationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetEvaluationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getEvaluationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetEvaluationRequest request]
(-> this (.getEvaluationAsync request))))
(defn create-data-source-from-s-3-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateDataSourceFromS3Request`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateDataSourceFromS3 operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateDataSourceFromS3Result>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateDataSourceFromS3Request request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createDataSourceFromS3Async request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateDataSourceFromS3Request request]
(-> this (.createDataSourceFromS3Async request))))
(defn update-ml-model-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.UpdateMLModelRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateMLModel operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.UpdateMLModelResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateMLModelRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateMLModelAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateMLModelRequest request]
(-> this (.updateMLModelAsync request))))
(defn get-ml-model-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.GetMLModelRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetMLModel operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.GetMLModelResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetMLModelRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getMLModelAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetMLModelRequest request]
(-> this (.getMLModelAsync request))))
(defn create-batch-prediction-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateBatchPredictionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateBatchPrediction operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateBatchPredictionResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateBatchPredictionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createBatchPredictionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateBatchPredictionRequest request]
(-> this (.createBatchPredictionAsync request))))
(defn delete-ml-model-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DeleteMLModelRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteMLModel operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DeleteMLModelResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteMLModelRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteMLModelAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteMLModelRequest request]
(-> this (.deleteMLModelAsync request))))
(defn describe-batch-predictions-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DescribeBatchPredictionsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeBatchPredictions operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DescribeBatchPredictionsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeBatchPredictionsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeBatchPredictionsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeBatchPredictionsRequest request]
(-> this (.describeBatchPredictionsAsync request)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this]
(-> this (.describeBatchPredictionsAsync))))
(defn create-evaluation-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateEvaluationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateEvaluation operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateEvaluationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateEvaluationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createEvaluationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateEvaluationRequest request]
(-> this (.createEvaluationAsync request))))
(defn describe-evaluations-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DescribeEvaluationsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeEvaluations operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DescribeEvaluationsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeEvaluationsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeEvaluationsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeEvaluationsRequest request]
(-> this (.describeEvaluationsAsync request)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this]
(-> this (.describeEvaluationsAsync))))
(defn delete-batch-prediction-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DeleteBatchPredictionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteBatchPrediction operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DeleteBatchPredictionResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteBatchPredictionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteBatchPredictionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteBatchPredictionRequest request]
(-> this (.deleteBatchPredictionAsync request))))
(defn update-evaluation-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.UpdateEvaluationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateEvaluation operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.UpdateEvaluationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateEvaluationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateEvaluationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateEvaluationRequest request]
(-> this (.updateEvaluationAsync request))))
(defn update-batch-prediction-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.UpdateBatchPredictionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateBatchPrediction operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.UpdateBatchPredictionResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateBatchPredictionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateBatchPredictionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateBatchPredictionRequest request]
(-> this (.updateBatchPredictionAsync request))))
(defn update-data-source-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.UpdateDataSourceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateDataSource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.UpdateDataSourceResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateDataSourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateDataSourceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateDataSourceRequest request]
(-> this (.updateDataSourceAsync request))))
(defn create-data-source-from-redshift-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateDataSourceFromRedshiftRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateDataSourceFromRedshift operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateDataSourceFromRedshiftResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateDataSourceFromRedshiftRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createDataSourceFromRedshiftAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateDataSourceFromRedshiftRequest request]
(-> this (.createDataSourceFromRedshiftAsync request))))
(defn describe-ml-models-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DescribeMLModelsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeMLModels operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DescribeMLModelsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeMLModelsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeMLModelsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeMLModelsRequest request]
(-> this (.describeMLModelsAsync request)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this]
(-> this (.describeMLModelsAsync))))
(defn describe-tags-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DescribeTagsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeTags operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DescribeTagsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeTagsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeTagsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeTagsRequest request]
(-> this (.describeTagsAsync request))))
(defn describe-data-sources-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DescribeDataSourcesRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeDataSources operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DescribeDataSourcesResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeDataSourcesRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeDataSourcesAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeDataSourcesRequest request]
(-> this (.describeDataSourcesAsync request)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this]
(-> this (.describeDataSourcesAsync))))
(defn delete-realtime-endpoint-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DeleteRealtimeEndpointRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteRealtimeEndpoint operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DeleteRealtimeEndpointResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteRealtimeEndpointRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteRealtimeEndpointAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteRealtimeEndpointRequest request]
(-> this (.deleteRealtimeEndpointAsync request))))
(defn get-data-source-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.GetDataSourceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetDataSource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.GetDataSourceResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetDataSourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getDataSourceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetDataSourceRequest request]
(-> this (.getDataSourceAsync request))))
(defn delete-data-source-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DeleteDataSourceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteDataSource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DeleteDataSourceResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteDataSourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteDataSourceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteDataSourceRequest request]
(-> this (.deleteDataSourceAsync request))))
(defn add-tags-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.AddTagsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the AddTags operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.AddTagsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.AddTagsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.addTagsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.AddTagsRequest request]
(-> this (.addTagsAsync request))))
| null | https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.machinelearning/src/com/amazonaws/services/machinelearning/AbstractAmazonMachineLearningAsync.clj | clojure | (ns com.amazonaws.services.machinelearning.AbstractAmazonMachineLearningAsync
"Abstract implementation of AmazonMachineLearningAsync. Convenient method forms pass through to the
corresponding overload that takes a request object and an AsyncHandler, which throws an
UnsupportedOperationException."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.machinelearning AbstractAmazonMachineLearningAsync]))
(defn create-realtime-endpoint-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateRealtimeEndpointRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateRealtimeEndpoint operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateRealtimeEndpointResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateRealtimeEndpointRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createRealtimeEndpointAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateRealtimeEndpointRequest request]
(-> this (.createRealtimeEndpointAsync request))))
(defn create-ml-model-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateMLModelRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateMLModel operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateMLModelResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateMLModelRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createMLModelAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateMLModelRequest request]
(-> this (.createMLModelAsync request))))
(defn predict-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.PredictRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the Predict operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.PredictResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.PredictRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.predictAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.PredictRequest request]
(-> this (.predictAsync request))))
(defn delete-evaluation-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DeleteEvaluationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteEvaluation operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DeleteEvaluationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteEvaluationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteEvaluationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteEvaluationRequest request]
(-> this (.deleteEvaluationAsync request))))
(defn create-data-source-from-rds-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateDataSourceFromRDSRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateDataSourceFromRDS operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateDataSourceFromRDSResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateDataSourceFromRDSRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createDataSourceFromRDSAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateDataSourceFromRDSRequest request]
(-> this (.createDataSourceFromRDSAsync request))))
(defn delete-tags-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DeleteTagsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteTags operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DeleteTagsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteTagsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteTagsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteTagsRequest request]
(-> this (.deleteTagsAsync request))))
(defn get-batch-prediction-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.GetBatchPredictionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetBatchPrediction operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.GetBatchPredictionResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetBatchPredictionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getBatchPredictionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetBatchPredictionRequest request]
(-> this (.getBatchPredictionAsync request))))
(defn get-evaluation-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.GetEvaluationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetEvaluation operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.GetEvaluationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetEvaluationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getEvaluationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetEvaluationRequest request]
(-> this (.getEvaluationAsync request))))
(defn create-data-source-from-s-3-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateDataSourceFromS3Request`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateDataSourceFromS3 operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateDataSourceFromS3Result>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateDataSourceFromS3Request request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createDataSourceFromS3Async request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateDataSourceFromS3Request request]
(-> this (.createDataSourceFromS3Async request))))
(defn update-ml-model-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.UpdateMLModelRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateMLModel operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.UpdateMLModelResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateMLModelRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateMLModelAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateMLModelRequest request]
(-> this (.updateMLModelAsync request))))
(defn get-ml-model-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.GetMLModelRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetMLModel operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.GetMLModelResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetMLModelRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getMLModelAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetMLModelRequest request]
(-> this (.getMLModelAsync request))))
(defn create-batch-prediction-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateBatchPredictionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateBatchPrediction operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateBatchPredictionResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateBatchPredictionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createBatchPredictionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateBatchPredictionRequest request]
(-> this (.createBatchPredictionAsync request))))
(defn delete-ml-model-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DeleteMLModelRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteMLModel operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DeleteMLModelResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteMLModelRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteMLModelAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteMLModelRequest request]
(-> this (.deleteMLModelAsync request))))
(defn describe-batch-predictions-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DescribeBatchPredictionsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeBatchPredictions operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DescribeBatchPredictionsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeBatchPredictionsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeBatchPredictionsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeBatchPredictionsRequest request]
(-> this (.describeBatchPredictionsAsync request)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this]
(-> this (.describeBatchPredictionsAsync))))
(defn create-evaluation-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateEvaluationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateEvaluation operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateEvaluationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateEvaluationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createEvaluationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateEvaluationRequest request]
(-> this (.createEvaluationAsync request))))
(defn describe-evaluations-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DescribeEvaluationsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeEvaluations operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DescribeEvaluationsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeEvaluationsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeEvaluationsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeEvaluationsRequest request]
(-> this (.describeEvaluationsAsync request)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this]
(-> this (.describeEvaluationsAsync))))
(defn delete-batch-prediction-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DeleteBatchPredictionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteBatchPrediction operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DeleteBatchPredictionResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteBatchPredictionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteBatchPredictionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteBatchPredictionRequest request]
(-> this (.deleteBatchPredictionAsync request))))
(defn update-evaluation-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.UpdateEvaluationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateEvaluation operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.UpdateEvaluationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateEvaluationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateEvaluationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateEvaluationRequest request]
(-> this (.updateEvaluationAsync request))))
(defn update-batch-prediction-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.UpdateBatchPredictionRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateBatchPrediction operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.UpdateBatchPredictionResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateBatchPredictionRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateBatchPredictionAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateBatchPredictionRequest request]
(-> this (.updateBatchPredictionAsync request))))
(defn update-data-source-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.UpdateDataSourceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateDataSource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.UpdateDataSourceResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateDataSourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateDataSourceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.UpdateDataSourceRequest request]
(-> this (.updateDataSourceAsync request))))
(defn create-data-source-from-redshift-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.CreateDataSourceFromRedshiftRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateDataSourceFromRedshift operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.CreateDataSourceFromRedshiftResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateDataSourceFromRedshiftRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createDataSourceFromRedshiftAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.CreateDataSourceFromRedshiftRequest request]
(-> this (.createDataSourceFromRedshiftAsync request))))
(defn describe-ml-models-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DescribeMLModelsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeMLModels operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DescribeMLModelsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeMLModelsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeMLModelsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeMLModelsRequest request]
(-> this (.describeMLModelsAsync request)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this]
(-> this (.describeMLModelsAsync))))
(defn describe-tags-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DescribeTagsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeTags operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DescribeTagsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeTagsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeTagsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeTagsRequest request]
(-> this (.describeTagsAsync request))))
(defn describe-data-sources-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DescribeDataSourcesRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeDataSources operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DescribeDataSourcesResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeDataSourcesRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeDataSourcesAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DescribeDataSourcesRequest request]
(-> this (.describeDataSourcesAsync request)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this]
(-> this (.describeDataSourcesAsync))))
(defn delete-realtime-endpoint-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DeleteRealtimeEndpointRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteRealtimeEndpoint operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DeleteRealtimeEndpointResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteRealtimeEndpointRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteRealtimeEndpointAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteRealtimeEndpointRequest request]
(-> this (.deleteRealtimeEndpointAsync request))))
(defn get-data-source-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.GetDataSourceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetDataSource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.GetDataSourceResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetDataSourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getDataSourceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.GetDataSourceRequest request]
(-> this (.getDataSourceAsync request))))
(defn delete-data-source-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.DeleteDataSourceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteDataSource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.DeleteDataSourceResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteDataSourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteDataSourceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.DeleteDataSourceRequest request]
(-> this (.deleteDataSourceAsync request))))
(defn add-tags-async
"Description copied from interface: AmazonMachineLearningAsync
request - `com.amazonaws.services.machinelearning.model.AddTagsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the AddTags operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.machinelearning.model.AddTagsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.AddTagsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.addTagsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonMachineLearningAsync this ^com.amazonaws.services.machinelearning.model.AddTagsRequest request]
(-> this (.addTagsAsync request))))
| |
cd5513a5007508a4e6dab31173223952ef921698ec26b0c1c5266ec53b544f03 | bos/rwh | SimpleJSON.hs | {-- snippet module --}
module SimpleJSON
(
JValue(..)
, getString
, getInt
, getDouble
, getBool
, getObject
, getArray
, isNull
) where
{-- /snippet module --}
- snippet -
-- file: SimpleJSON.hs
data JValue = JString String
| JNumber Double
| JBool Bool
| JNull
| JObject [(String, JValue)]
| JArray [JValue]
deriving (Eq, Ord, Show)
{-- /snippet JValue --}
- snippet -
getString :: JValue -> Maybe String
getString (JString s) = Just s
getString _ = Nothing
{-- /snippet getString --}
{-- snippet getters --}
getInt (JNumber n) = Just (truncate n)
getInt _ = Nothing
getDouble (JNumber n) = Just n
getDouble _ = Nothing
getBool (JBool b) = Just b
getBool _ = Nothing
getObject (JObject o) = Just o
getObject _ = Nothing
getArray (JArray a) = Just a
getArray _ = Nothing
isNull v = v == JNull
{-- /snippet getters --}
| null | https://raw.githubusercontent.com/bos/rwh/7fd1e467d54aef832f5476ebf5f4f6a898a895d1/examples/ch06/SimpleJSON.hs | haskell | - snippet module -
- /snippet module -
file: SimpleJSON.hs
- /snippet JValue -
- /snippet getString -
- snippet getters -
- /snippet getters - | module SimpleJSON
(
JValue(..)
, getString
, getInt
, getDouble
, getBool
, getObject
, getArray
, isNull
) where
- snippet -
data JValue = JString String
| JNumber Double
| JBool Bool
| JNull
| JObject [(String, JValue)]
| JArray [JValue]
deriving (Eq, Ord, Show)
- snippet -
getString :: JValue -> Maybe String
getString (JString s) = Just s
getString _ = Nothing
getInt (JNumber n) = Just (truncate n)
getInt _ = Nothing
getDouble (JNumber n) = Just n
getDouble _ = Nothing
getBool (JBool b) = Just b
getBool _ = Nothing
getObject (JObject o) = Just o
getObject _ = Nothing
getArray (JArray a) = Just a
getArray _ = Nothing
isNull v = v == JNull
|
d42d3ecd71af45ecb9a7ec810edb31380f93e6ec77b0f626941101980c43a4f5 | google-research/dex-lang | Imp.hs | Copyright 2022 Google LLC
--
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE file or at
-- -source/licenses/bsd
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE StrictData #-}
# LANGUAGE DeriveFunctor #
# LANGUAGE ViewPatterns #
# LANGUAGE TypeFamilies #
# LANGUAGE InstanceSigs #
# LANGUAGE UndecidableInstances #
# LANGUAGE StandaloneDeriving #
# LANGUAGE DerivingStrategies #
# LANGUAGE DerivingVia #
# LANGUAGE DefaultSignatures #
module Types.Imp where
import Foreign.Ptr
import Data.Hashable
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString as BS
import GHC.Generics (Generic (..))
import Data.Store (Store (..))
import Name
import Util (IsBool (..))
import Types.Primitives
type ImpName = Name ImpNameC
type ImpFunName = Name TopFunNameC
data IExpr n = ILit LitVal
| IVar (ImpName n) BaseType
| IPtrVar (Name PtrNameC n) PtrType
deriving (Show, Generic)
data IBinder n l = IBinder (NameBinder ImpNameC n l) IType
deriving (Show, Generic)
only ILit and IRef constructors
type IType = BaseType
type Size = IExpr
type IVectorType = BaseType -- has to be a vector type
type IFunName = String
type IFunVar = (IFunName, IFunType)
data IFunType = IFunType CallingConvention [IType] [IType] -- args, results
deriving (Show, Eq, Generic)
data IsCUDARequired = CUDARequired | CUDANotRequired deriving (Eq, Show, Generic)
instance IsBool IsCUDARequired where
toBool CUDARequired = True
toBool CUDANotRequired = False
data CallingConvention =
Scalar args by value , arrays by pointer , dests allocated by caller and passed as pointers .
Used for standalone functions and for functions called from Python without XLA .
StandardCC
Used for functions called from within an XLA computation .
| XLACC
Dests allocated within the function and passed back to the caller ( packed
-- in a number-of-results-length buffer supplied by the caller)
| EntryFunCC IsCUDARequired
Scalars only . as args , result as result . Used for calling C function
from that return a single scalar .
| FFICC
| FFIMultiResultCC
| CUDAKernelLaunch
| MCThreadLaunch
deriving (Show, Eq, Generic)
data ImpFunction n = ImpFunction IFunType (Abs (Nest IBinder) ImpBlock n)
deriving (Show, Generic)
data ImpBlock n where
ImpBlock :: Nest ImpDecl n l -> [IExpr l] -> ImpBlock n
deriving instance Show (ImpBlock n)
data ImpDecl n l = ImpLet (Nest IBinder n l) (ImpInstr n)
deriving (Show, Generic)
data ImpInstr n =
IFor Direction (Size n) (Abs IBinder ImpBlock n)
| IWhile (ImpBlock n)
| ICond (IExpr n) (ImpBlock n) (ImpBlock n)
| IQueryParallelism IFunVar (IExpr n) -- returns the number of available concurrent threads
| ISyncWorkgroup
| ILaunch IFunVar (Size n) [IExpr n]
| ICall (ImpFunName n) [IExpr n]
| Store (IExpr n) (IExpr n) -- dest, val
| Alloc AddressSpace IType (Size n)
| StackAlloc IType (Size n)
dest , source , numel
| Free (IExpr n)
ptr , numel
gives size in numel
| IThrowError -- TODO: parameterize by a run-time string
| ICastOp IType (IExpr n)
| IBitcastOp IType (IExpr n)
| IVectorBroadcast (IExpr n) IVectorType
| IVectorIota IVectorType
| IPtrLoad (IExpr n)
| IPtrOffset (IExpr n) (IExpr n)
| IBinOp BinOp (IExpr n) (IExpr n)
| IUnOp UnOp (IExpr n)
| ISelect (IExpr n) (IExpr n) (IExpr n)
| IOutputStream
just prints an int64 value
| IShowScalar (IExpr n) (IExpr n) -- pointer to result table, value
deriving (Show, Generic)
iBinderType :: IBinder n l -> IType
iBinderType (IBinder _ ty) = ty
# INLINE iBinderType #
data Backend = LLVM | LLVMCUDA | LLVMMC | MLIR | Interpreter deriving (Show, Eq)
newtype CUDAKernel = CUDAKernel B.ByteString deriving (Show)
= = = Closed Imp functions , and object file representation = = =
Object files and LLVM modules expose ordinary C - toolchain names rather than
-- our internal scoped naming system. The `CNameInterface` data structure
-- describes how to interpret the names exposed by an LLVM module and its
-- corresponding object code. These names are all considered local to the
-- module. The module as a whole is a closed object corresponding to a
-- `ClosedImpFunction`.
-- TODO: consider adding more information here: types of required functions,
-- calling conventions etc.
type CName = String
data WithCNameInterface a = WithCNameInterface
{ cniCode :: a -- module itself (an LLVM.AST.Module or a bytestring of object code)
, cniMainFunName :: CName -- name of function defined in this module
, cniRequiredFuns :: [CName] -- names of functions required by this module
, cniRequiredPtrs :: [CName] -- names of data pointers
, cniDtorList :: [CName] -- names of destructors (CUDA only) defined by this module
} deriving (Show, Generic, Functor, Foldable, Traversable)
type RawObjCode = BS.ByteString
type FunObjCode = WithCNameInterface RawObjCode
data IFunBinder n l = IFunBinder (NameBinder TopFunNameC n l) IFunType
-- Imp function with link-time objects abstracted out, suitable for standalone
compilation . TODO : enforce actual ` ` as the scope parameter .
data ClosedImpFunction n where
ClosedImpFunction
:: Nest IFunBinder n1 n2 -- binders for required functions
-> Nest PtrBinder n2 n3 -- binders for required data pointers
-> ImpFunction n3
-> ClosedImpFunction n1
data PtrBinder n l = PtrBinder (NameBinder PtrNameC n l) PtrType
data LinktimeNames n = LinktimeNames [Name FunObjCodeNameC n] [Name PtrNameC n] deriving (Show, Generic)
data LinktimeVals = LinktimeVals [FunPtr ()] [Ptr ()] deriving (Show, Generic)
instance BindsAtMostOneName IFunBinder TopFunNameC where
IFunBinder b _ @> x = b @> x
{-# INLINE (@>) #-}
instance BindsOneName IFunBinder TopFunNameC where
binderName (IFunBinder b _) = binderName b
# INLINE binderName #
instance HasNameHint (IFunBinder n l) where
getNameHint (IFunBinder b _) = getNameHint b
instance GenericB IFunBinder where
type RepB IFunBinder = BinderP TopFunNameC (LiftE IFunType)
fromB (IFunBinder b ty) = b :> LiftE ty
toB (b :> LiftE ty) = IFunBinder b ty
instance ProvesExt IFunBinder
instance BindsNames IFunBinder
instance SinkableB IFunBinder
instance HoistableB IFunBinder
instance RenameB IFunBinder
instance AlphaEqB IFunBinder
instance AlphaHashableB IFunBinder
instance GenericB PtrBinder where
type RepB PtrBinder = BinderP PtrNameC (LiftE PtrType)
fromB (PtrBinder b ty) = b :> LiftE ty
toB (b :> LiftE ty) = PtrBinder b ty
instance BindsAtMostOneName PtrBinder PtrNameC where
PtrBinder b _ @> x = b @> x
{-# INLINE (@>) #-}
instance HasNameHint (PtrBinder n l) where
getNameHint (PtrBinder b _) = getNameHint b
instance ProvesExt PtrBinder
instance BindsNames PtrBinder
instance SinkableB PtrBinder
instance HoistableB PtrBinder
instance RenameB PtrBinder
instance AlphaEqB PtrBinder
instance AlphaHashableB PtrBinder
-- === instances ===
instance GenericE ImpInstr where
type RepE ImpInstr = EitherE5
(EitherE4
{- IFor -} (LiftE Direction `PairE` Size `PairE` Abs IBinder ImpBlock)
{- IWhile -} (ImpBlock)
ICond
IQuery
) (EitherE4
{- ISyncW -} (UnitE)
{- ILaunch -} (LiftE IFunVar `PairE` Size `PairE` ListE IExpr)
ICall
{- Store -} (IExpr `PairE` IExpr)
) (EitherE7
Alloc
{- StackAlloc -} (LiftE IType `PairE` Size)
MemCopy
InitializeZeros
{- GetAllocSize -} IExpr
{- Free -} (IExpr)
{- IThrowE -} (UnitE)
) (EitherE6
{- ICastOp -} (LiftE IType `PairE` IExpr)
{- IBitcastOp -} (LiftE IType `PairE` IExpr)
{- IVectorBroadcast -} (IExpr `PairE` LiftE IVectorType)
{- IVectorIota -} ( LiftE IVectorType)
{- DebugPrint -} (LiftE String `PairE` IExpr)
{- IShowScalar -} (IExpr `PairE` IExpr)
) (EitherE6
{- IPtrLoad -} IExpr
{- IPtrOffset -} (IExpr `PairE` IExpr)
{- IBinOp -} (LiftE BinOp `PairE` IExpr `PairE` IExpr)
{- IUnOp -} (LiftE UnOp `PairE` IExpr)
{- ISelect -} (IExpr`PairE` IExpr `PairE`IExpr)
{- IOutputStream -} UnitE
)
fromE instr = case instr of
IFor d n ab -> Case0 $ Case0 $ LiftE d `PairE` n `PairE` ab
IWhile body -> Case0 $ Case1 body
ICond p cons alt -> Case0 $ Case2 $ p `PairE` cons `PairE` alt
IQueryParallelism f s -> Case0 $ Case3 $ LiftE f `PairE` s
ISyncWorkgroup -> Case1 $ Case0 UnitE
ILaunch f n args -> Case1 $ Case1 $ LiftE f `PairE` n `PairE` ListE args
ICall f args -> Case1 $ Case2 $ f `PairE` ListE args
Store dest val -> Case1 $ Case3 $ dest `PairE` val
Alloc a t s -> Case2 $ Case0 $ LiftE (a, t) `PairE` s
StackAlloc t s -> Case2 $ Case1 $ LiftE t `PairE` s
MemCopy dest src numel -> Case2 $ Case2 $ dest `PairE` src `PairE` numel
InitializeZeros ptr numel -> Case2 $ Case3 $ ptr `PairE` numel
GetAllocSize ptr -> Case2 $ Case4 $ ptr
Free ptr -> Case2 $ Case5 ptr
IThrowError -> Case2 $ Case6 UnitE
ICastOp idt ix -> Case3 $ Case0 $ LiftE idt `PairE` ix
IBitcastOp idt ix -> Case3 $ Case1 $ LiftE idt `PairE` ix
IVectorBroadcast v vty -> Case3 $ Case2 $ v `PairE` LiftE vty
IVectorIota vty -> Case3 $ Case3 $ LiftE vty
DebugPrint s x -> Case3 $ Case4 $ LiftE s `PairE` x
IShowScalar x y -> Case3 $ Case5 $ x `PairE` y
IPtrLoad x -> Case4 $ Case0 $ x
IPtrOffset x y -> Case4 $ Case1 $ x `PairE` y
IBinOp op x y -> Case4 $ Case2 $ LiftE op `PairE` x `PairE` y
IUnOp op x -> Case4 $ Case3 $ LiftE op `PairE` x
ISelect x y z -> Case4 $ Case4 $ x `PairE` y `PairE` z
IOutputStream -> Case4 $ Case5 $ UnitE
# INLINE fromE #
toE instr = case instr of
Case0 instr' -> case instr' of
Case0 (LiftE d `PairE` n `PairE` ab) -> IFor d n ab
Case1 body -> IWhile body
Case2 (p `PairE` cons `PairE` alt) -> ICond p cons alt
Case3 (LiftE f `PairE` s) -> IQueryParallelism f s
_ -> error "impossible"
Case1 instr' -> case instr' of
Case0 UnitE -> ISyncWorkgroup
Case1 (LiftE f `PairE` n `PairE` ListE args) -> ILaunch f n args
Case2 (f `PairE` ListE args) -> ICall f args
Case3 (dest `PairE` val ) -> Store dest val
_ -> error "impossible"
Case2 instr' -> case instr' of
Case0 (LiftE (a, t) `PairE` s ) -> Alloc a t s
Case1 (LiftE t `PairE` s ) -> StackAlloc t s
Case2 (dest `PairE` src `PairE` numel) -> MemCopy dest src numel
Case3 (ptr `PairE` numel) -> InitializeZeros ptr numel
Case4 ptr -> GetAllocSize ptr
Case5 ptr -> Free ptr
Case6 UnitE -> IThrowError
_ -> error "impossible"
Case3 instr' -> case instr' of
Case0 (LiftE idt `PairE` ix ) -> ICastOp idt ix
Case1 (LiftE idt `PairE` ix ) -> IBitcastOp idt ix
Case2 (v `PairE` LiftE vty) -> IVectorBroadcast v vty
Case3 ( LiftE vty) -> IVectorIota vty
Case4 (LiftE s `PairE` x) -> DebugPrint s x
Case5 (x `PairE` y) -> IShowScalar x y
_ -> error "impossible"
_ -> error "impossible"
# INLINE toE #
instance SinkableE ImpInstr
instance HoistableE ImpInstr
instance AlphaEqE ImpInstr
instance AlphaHashableE ImpInstr
instance RenameE ImpInstr
instance GenericE ImpBlock where
type RepE ImpBlock = Abs (Nest ImpDecl) (ListE IExpr)
fromE (ImpBlock decls results) = Abs decls (ListE results)
# INLINE fromE #
toE (Abs decls (ListE results)) = ImpBlock decls results
# INLINE toE #
instance SinkableE ImpBlock
instance HoistableE ImpBlock
instance AlphaEqE ImpBlock
instance AlphaHashableE ImpBlock
instance RenameE ImpBlock
deriving via WrapE ImpBlock n instance Generic (ImpBlock n)
instance GenericE IExpr where
type RepE IExpr = EitherE3 (LiftE LitVal)
(PairE ImpName (LiftE BaseType))
(PairE (Name PtrNameC) (LiftE PtrType))
fromE iexpr = case iexpr of
ILit x -> Case0 (LiftE x)
IVar v ty -> Case1 (v `PairE` LiftE ty)
IPtrVar v ty -> Case2 (v `PairE` LiftE ty)
# INLINE fromE #
toE rep = case rep of
Case0 (LiftE x) -> ILit x
Case1 (v `PairE` LiftE ty) -> IVar v ty
Case2 (v `PairE` LiftE ty) -> IPtrVar v ty
_ -> error "impossible"
# INLINE toE #
instance SinkableE IExpr
instance HoistableE IExpr
instance AlphaEqE IExpr
instance AlphaHashableE IExpr
instance RenameE IExpr
instance GenericB IBinder where
type RepB IBinder = PairB (LiftB (LiftE IType)) (NameBinder ImpNameC)
fromB (IBinder b ty) = PairB (LiftB (LiftE ty)) b
toB (PairB (LiftB (LiftE ty)) b) = IBinder b ty
instance HasNameHint (IBinder n l) where
getNameHint (IBinder b _) = getNameHint b
instance BindsAtMostOneName IBinder ImpNameC where
IBinder b _ @> x = b @> x
instance BindsOneName IBinder ImpNameC where
binderName (IBinder b _) = binderName b
instance BindsNames IBinder where
toScopeFrag (IBinder b _) = toScopeFrag b
instance ProvesExt IBinder
instance SinkableB IBinder
instance HoistableB IBinder
instance RenameB IBinder
instance AlphaEqB IBinder
instance AlphaHashableB IBinder
instance GenericB ImpDecl where
type RepB ImpDecl = PairB (LiftB ImpInstr) (Nest IBinder)
fromB (ImpLet bs instr) = PairB (LiftB instr) bs
toB (PairB (LiftB instr) bs) = ImpLet bs instr
instance SinkableB ImpDecl
instance HoistableB ImpDecl
instance RenameB ImpDecl
instance AlphaEqB ImpDecl
instance AlphaHashableB ImpDecl
instance ProvesExt ImpDecl
instance BindsNames ImpDecl
instance GenericE ImpFunction where
type RepE ImpFunction = LiftE IFunType `PairE` Abs (Nest IBinder) ImpBlock
fromE (ImpFunction ty ab) =LiftE ty `PairE` ab
# INLINE fromE #
toE (LiftE ty `PairE` ab) = ImpFunction ty ab
# INLINE toE #
instance SinkableE ImpFunction
instance HoistableE ImpFunction
instance AlphaEqE ImpFunction
instance AlphaHashableE ImpFunction
instance RenameE ImpFunction
instance GenericE LinktimeNames where
type RepE LinktimeNames = ListE (Name FunObjCodeNameC)
`PairE` ListE (Name PtrNameC)
fromE (LinktimeNames funs ptrs) = ListE funs `PairE` ListE ptrs
# INLINE fromE #
toE (ListE funs `PairE` ListE ptrs) = LinktimeNames funs ptrs
# INLINE toE #
instance SinkableE LinktimeNames
instance HoistableE LinktimeNames
instance AlphaEqE LinktimeNames
instance AlphaHashableE LinktimeNames
instance RenameE LinktimeNames
instance Store IsCUDARequired
instance Store CallingConvention
instance Store a => Store (WithCNameInterface a)
instance Store (IBinder n l)
instance Store (ImpDecl n l)
instance Store (IFunType)
instance Store (ImpInstr n)
instance Store (IExpr n)
instance Store (ImpBlock n)
instance Store (ImpFunction n)
instance Store (LinktimeNames n)
instance Store LinktimeVals
instance Hashable IsCUDARequired
instance Hashable CallingConvention
instance Hashable IFunType
| null | https://raw.githubusercontent.com/google-research/dex-lang/2e7bcda20a853e0764dc53991d495ae94e9a24b2/src/lib/Types/Imp.hs | haskell |
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
-source/licenses/bsd
# LANGUAGE StrictData #
has to be a vector type
args, results
in a number-of-results-length buffer supplied by the caller)
returns the number of available concurrent threads
dest, val
TODO: parameterize by a run-time string
pointer to result table, value
our internal scoped naming system. The `CNameInterface` data structure
describes how to interpret the names exposed by an LLVM module and its
corresponding object code. These names are all considered local to the
module. The module as a whole is a closed object corresponding to a
`ClosedImpFunction`.
TODO: consider adding more information here: types of required functions,
calling conventions etc.
module itself (an LLVM.AST.Module or a bytestring of object code)
name of function defined in this module
names of functions required by this module
names of data pointers
names of destructors (CUDA only) defined by this module
Imp function with link-time objects abstracted out, suitable for standalone
binders for required functions
binders for required data pointers
# INLINE (@>) #
# INLINE (@>) #
=== instances ===
IFor
IWhile
ISyncW
ILaunch
Store
StackAlloc
GetAllocSize
Free
IThrowE
ICastOp
IBitcastOp
IVectorBroadcast
IVectorIota
DebugPrint
IShowScalar
IPtrLoad
IPtrOffset
IBinOp
IUnOp
ISelect
IOutputStream | Copyright 2022 Google LLC
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE DeriveFunctor #
# LANGUAGE ViewPatterns #
# LANGUAGE TypeFamilies #
# LANGUAGE InstanceSigs #
# LANGUAGE UndecidableInstances #
# LANGUAGE StandaloneDeriving #
# LANGUAGE DerivingStrategies #
# LANGUAGE DerivingVia #
# LANGUAGE DefaultSignatures #
module Types.Imp where
import Foreign.Ptr
import Data.Hashable
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString as BS
import GHC.Generics (Generic (..))
import Data.Store (Store (..))
import Name
import Util (IsBool (..))
import Types.Primitives
type ImpName = Name ImpNameC
type ImpFunName = Name TopFunNameC
data IExpr n = ILit LitVal
| IVar (ImpName n) BaseType
| IPtrVar (Name PtrNameC n) PtrType
deriving (Show, Generic)
data IBinder n l = IBinder (NameBinder ImpNameC n l) IType
deriving (Show, Generic)
only ILit and IRef constructors
type IType = BaseType
type Size = IExpr
type IFunName = String
type IFunVar = (IFunName, IFunType)
deriving (Show, Eq, Generic)
data IsCUDARequired = CUDARequired | CUDANotRequired deriving (Eq, Show, Generic)
instance IsBool IsCUDARequired where
toBool CUDARequired = True
toBool CUDANotRequired = False
data CallingConvention =
Scalar args by value , arrays by pointer , dests allocated by caller and passed as pointers .
Used for standalone functions and for functions called from Python without XLA .
StandardCC
Used for functions called from within an XLA computation .
| XLACC
Dests allocated within the function and passed back to the caller ( packed
| EntryFunCC IsCUDARequired
Scalars only . as args , result as result . Used for calling C function
from that return a single scalar .
| FFICC
| FFIMultiResultCC
| CUDAKernelLaunch
| MCThreadLaunch
deriving (Show, Eq, Generic)
data ImpFunction n = ImpFunction IFunType (Abs (Nest IBinder) ImpBlock n)
deriving (Show, Generic)
data ImpBlock n where
ImpBlock :: Nest ImpDecl n l -> [IExpr l] -> ImpBlock n
deriving instance Show (ImpBlock n)
data ImpDecl n l = ImpLet (Nest IBinder n l) (ImpInstr n)
deriving (Show, Generic)
data ImpInstr n =
IFor Direction (Size n) (Abs IBinder ImpBlock n)
| IWhile (ImpBlock n)
| ICond (IExpr n) (ImpBlock n) (ImpBlock n)
| ISyncWorkgroup
| ILaunch IFunVar (Size n) [IExpr n]
| ICall (ImpFunName n) [IExpr n]
| Alloc AddressSpace IType (Size n)
| StackAlloc IType (Size n)
dest , source , numel
| Free (IExpr n)
ptr , numel
gives size in numel
| ICastOp IType (IExpr n)
| IBitcastOp IType (IExpr n)
| IVectorBroadcast (IExpr n) IVectorType
| IVectorIota IVectorType
| IPtrLoad (IExpr n)
| IPtrOffset (IExpr n) (IExpr n)
| IBinOp BinOp (IExpr n) (IExpr n)
| IUnOp UnOp (IExpr n)
| ISelect (IExpr n) (IExpr n) (IExpr n)
| IOutputStream
just prints an int64 value
deriving (Show, Generic)
iBinderType :: IBinder n l -> IType
iBinderType (IBinder _ ty) = ty
# INLINE iBinderType #
data Backend = LLVM | LLVMCUDA | LLVMMC | MLIR | Interpreter deriving (Show, Eq)
newtype CUDAKernel = CUDAKernel B.ByteString deriving (Show)
= = = Closed Imp functions , and object file representation = = =
Object files and LLVM modules expose ordinary C - toolchain names rather than
type CName = String
data WithCNameInterface a = WithCNameInterface
} deriving (Show, Generic, Functor, Foldable, Traversable)
type RawObjCode = BS.ByteString
type FunObjCode = WithCNameInterface RawObjCode
data IFunBinder n l = IFunBinder (NameBinder TopFunNameC n l) IFunType
compilation . TODO : enforce actual ` ` as the scope parameter .
data ClosedImpFunction n where
ClosedImpFunction
-> ImpFunction n3
-> ClosedImpFunction n1
data PtrBinder n l = PtrBinder (NameBinder PtrNameC n l) PtrType
data LinktimeNames n = LinktimeNames [Name FunObjCodeNameC n] [Name PtrNameC n] deriving (Show, Generic)
data LinktimeVals = LinktimeVals [FunPtr ()] [Ptr ()] deriving (Show, Generic)
instance BindsAtMostOneName IFunBinder TopFunNameC where
IFunBinder b _ @> x = b @> x
instance BindsOneName IFunBinder TopFunNameC where
binderName (IFunBinder b _) = binderName b
# INLINE binderName #
instance HasNameHint (IFunBinder n l) where
getNameHint (IFunBinder b _) = getNameHint b
instance GenericB IFunBinder where
type RepB IFunBinder = BinderP TopFunNameC (LiftE IFunType)
fromB (IFunBinder b ty) = b :> LiftE ty
toB (b :> LiftE ty) = IFunBinder b ty
instance ProvesExt IFunBinder
instance BindsNames IFunBinder
instance SinkableB IFunBinder
instance HoistableB IFunBinder
instance RenameB IFunBinder
instance AlphaEqB IFunBinder
instance AlphaHashableB IFunBinder
instance GenericB PtrBinder where
type RepB PtrBinder = BinderP PtrNameC (LiftE PtrType)
fromB (PtrBinder b ty) = b :> LiftE ty
toB (b :> LiftE ty) = PtrBinder b ty
instance BindsAtMostOneName PtrBinder PtrNameC where
PtrBinder b _ @> x = b @> x
instance HasNameHint (PtrBinder n l) where
getNameHint (PtrBinder b _) = getNameHint b
instance ProvesExt PtrBinder
instance BindsNames PtrBinder
instance SinkableB PtrBinder
instance HoistableB PtrBinder
instance RenameB PtrBinder
instance AlphaEqB PtrBinder
instance AlphaHashableB PtrBinder
instance GenericE ImpInstr where
type RepE ImpInstr = EitherE5
(EitherE4
ICond
IQuery
) (EitherE4
ICall
) (EitherE7
Alloc
MemCopy
InitializeZeros
) (EitherE6
) (EitherE6
)
fromE instr = case instr of
IFor d n ab -> Case0 $ Case0 $ LiftE d `PairE` n `PairE` ab
IWhile body -> Case0 $ Case1 body
ICond p cons alt -> Case0 $ Case2 $ p `PairE` cons `PairE` alt
IQueryParallelism f s -> Case0 $ Case3 $ LiftE f `PairE` s
ISyncWorkgroup -> Case1 $ Case0 UnitE
ILaunch f n args -> Case1 $ Case1 $ LiftE f `PairE` n `PairE` ListE args
ICall f args -> Case1 $ Case2 $ f `PairE` ListE args
Store dest val -> Case1 $ Case3 $ dest `PairE` val
Alloc a t s -> Case2 $ Case0 $ LiftE (a, t) `PairE` s
StackAlloc t s -> Case2 $ Case1 $ LiftE t `PairE` s
MemCopy dest src numel -> Case2 $ Case2 $ dest `PairE` src `PairE` numel
InitializeZeros ptr numel -> Case2 $ Case3 $ ptr `PairE` numel
GetAllocSize ptr -> Case2 $ Case4 $ ptr
Free ptr -> Case2 $ Case5 ptr
IThrowError -> Case2 $ Case6 UnitE
ICastOp idt ix -> Case3 $ Case0 $ LiftE idt `PairE` ix
IBitcastOp idt ix -> Case3 $ Case1 $ LiftE idt `PairE` ix
IVectorBroadcast v vty -> Case3 $ Case2 $ v `PairE` LiftE vty
IVectorIota vty -> Case3 $ Case3 $ LiftE vty
DebugPrint s x -> Case3 $ Case4 $ LiftE s `PairE` x
IShowScalar x y -> Case3 $ Case5 $ x `PairE` y
IPtrLoad x -> Case4 $ Case0 $ x
IPtrOffset x y -> Case4 $ Case1 $ x `PairE` y
IBinOp op x y -> Case4 $ Case2 $ LiftE op `PairE` x `PairE` y
IUnOp op x -> Case4 $ Case3 $ LiftE op `PairE` x
ISelect x y z -> Case4 $ Case4 $ x `PairE` y `PairE` z
IOutputStream -> Case4 $ Case5 $ UnitE
# INLINE fromE #
toE instr = case instr of
Case0 instr' -> case instr' of
Case0 (LiftE d `PairE` n `PairE` ab) -> IFor d n ab
Case1 body -> IWhile body
Case2 (p `PairE` cons `PairE` alt) -> ICond p cons alt
Case3 (LiftE f `PairE` s) -> IQueryParallelism f s
_ -> error "impossible"
Case1 instr' -> case instr' of
Case0 UnitE -> ISyncWorkgroup
Case1 (LiftE f `PairE` n `PairE` ListE args) -> ILaunch f n args
Case2 (f `PairE` ListE args) -> ICall f args
Case3 (dest `PairE` val ) -> Store dest val
_ -> error "impossible"
Case2 instr' -> case instr' of
Case0 (LiftE (a, t) `PairE` s ) -> Alloc a t s
Case1 (LiftE t `PairE` s ) -> StackAlloc t s
Case2 (dest `PairE` src `PairE` numel) -> MemCopy dest src numel
Case3 (ptr `PairE` numel) -> InitializeZeros ptr numel
Case4 ptr -> GetAllocSize ptr
Case5 ptr -> Free ptr
Case6 UnitE -> IThrowError
_ -> error "impossible"
Case3 instr' -> case instr' of
Case0 (LiftE idt `PairE` ix ) -> ICastOp idt ix
Case1 (LiftE idt `PairE` ix ) -> IBitcastOp idt ix
Case2 (v `PairE` LiftE vty) -> IVectorBroadcast v vty
Case3 ( LiftE vty) -> IVectorIota vty
Case4 (LiftE s `PairE` x) -> DebugPrint s x
Case5 (x `PairE` y) -> IShowScalar x y
_ -> error "impossible"
_ -> error "impossible"
# INLINE toE #
instance SinkableE ImpInstr
instance HoistableE ImpInstr
instance AlphaEqE ImpInstr
instance AlphaHashableE ImpInstr
instance RenameE ImpInstr
instance GenericE ImpBlock where
type RepE ImpBlock = Abs (Nest ImpDecl) (ListE IExpr)
fromE (ImpBlock decls results) = Abs decls (ListE results)
# INLINE fromE #
toE (Abs decls (ListE results)) = ImpBlock decls results
# INLINE toE #
instance SinkableE ImpBlock
instance HoistableE ImpBlock
instance AlphaEqE ImpBlock
instance AlphaHashableE ImpBlock
instance RenameE ImpBlock
deriving via WrapE ImpBlock n instance Generic (ImpBlock n)
instance GenericE IExpr where
type RepE IExpr = EitherE3 (LiftE LitVal)
(PairE ImpName (LiftE BaseType))
(PairE (Name PtrNameC) (LiftE PtrType))
fromE iexpr = case iexpr of
ILit x -> Case0 (LiftE x)
IVar v ty -> Case1 (v `PairE` LiftE ty)
IPtrVar v ty -> Case2 (v `PairE` LiftE ty)
# INLINE fromE #
toE rep = case rep of
Case0 (LiftE x) -> ILit x
Case1 (v `PairE` LiftE ty) -> IVar v ty
Case2 (v `PairE` LiftE ty) -> IPtrVar v ty
_ -> error "impossible"
# INLINE toE #
instance SinkableE IExpr
instance HoistableE IExpr
instance AlphaEqE IExpr
instance AlphaHashableE IExpr
instance RenameE IExpr
instance GenericB IBinder where
type RepB IBinder = PairB (LiftB (LiftE IType)) (NameBinder ImpNameC)
fromB (IBinder b ty) = PairB (LiftB (LiftE ty)) b
toB (PairB (LiftB (LiftE ty)) b) = IBinder b ty
instance HasNameHint (IBinder n l) where
getNameHint (IBinder b _) = getNameHint b
instance BindsAtMostOneName IBinder ImpNameC where
IBinder b _ @> x = b @> x
instance BindsOneName IBinder ImpNameC where
binderName (IBinder b _) = binderName b
instance BindsNames IBinder where
toScopeFrag (IBinder b _) = toScopeFrag b
instance ProvesExt IBinder
instance SinkableB IBinder
instance HoistableB IBinder
instance RenameB IBinder
instance AlphaEqB IBinder
instance AlphaHashableB IBinder
instance GenericB ImpDecl where
type RepB ImpDecl = PairB (LiftB ImpInstr) (Nest IBinder)
fromB (ImpLet bs instr) = PairB (LiftB instr) bs
toB (PairB (LiftB instr) bs) = ImpLet bs instr
instance SinkableB ImpDecl
instance HoistableB ImpDecl
instance RenameB ImpDecl
instance AlphaEqB ImpDecl
instance AlphaHashableB ImpDecl
instance ProvesExt ImpDecl
instance BindsNames ImpDecl
instance GenericE ImpFunction where
type RepE ImpFunction = LiftE IFunType `PairE` Abs (Nest IBinder) ImpBlock
fromE (ImpFunction ty ab) =LiftE ty `PairE` ab
# INLINE fromE #
toE (LiftE ty `PairE` ab) = ImpFunction ty ab
# INLINE toE #
instance SinkableE ImpFunction
instance HoistableE ImpFunction
instance AlphaEqE ImpFunction
instance AlphaHashableE ImpFunction
instance RenameE ImpFunction
instance GenericE LinktimeNames where
type RepE LinktimeNames = ListE (Name FunObjCodeNameC)
`PairE` ListE (Name PtrNameC)
fromE (LinktimeNames funs ptrs) = ListE funs `PairE` ListE ptrs
# INLINE fromE #
toE (ListE funs `PairE` ListE ptrs) = LinktimeNames funs ptrs
# INLINE toE #
instance SinkableE LinktimeNames
instance HoistableE LinktimeNames
instance AlphaEqE LinktimeNames
instance AlphaHashableE LinktimeNames
instance RenameE LinktimeNames
instance Store IsCUDARequired
instance Store CallingConvention
instance Store a => Store (WithCNameInterface a)
instance Store (IBinder n l)
instance Store (ImpDecl n l)
instance Store (IFunType)
instance Store (ImpInstr n)
instance Store (IExpr n)
instance Store (ImpBlock n)
instance Store (ImpFunction n)
instance Store (LinktimeNames n)
instance Store LinktimeVals
instance Hashable IsCUDARequired
instance Hashable CallingConvention
instance Hashable IFunType
|
40373aaaedc11aec1b6acb4400fc74c16e028f48f41cb6c449460eb0ecdf9e21 | bsaleil/lc | chars.scm | ;;---------------------------------------------------------------------------
;;
Copyright ( c ) 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. The name of the author may not be used to endorse or promote
;; products derived from this software without specific prior written
;; permission.
;;
THIS SOFTWARE IS PROVIDED ` ` AS IS '' AND ANY EXPRESS OR
;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
;; MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
;; NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT
;; NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;
;;---------------------------------------------------------------------------
(pp (char=? #\A #\B))
(pp (char=? #\A #\A))
(pp (char=? #\B #\A))
(pp (char<? #\A #\B))
(pp (char<? #\A #\A))
(pp (char<? #\B #\A))
(pp (char>? #\A #\B))
(pp (char>? #\A #\A))
(pp (char>? #\B #\A))
(pp (char<=? #\A #\B))
(pp (char<=? #\A #\A))
(pp (char<=? #\B #\A))
(pp (char>=? #\A #\B))
(pp (char>=? #\A #\A))
(pp (char>=? #\B #\A))
(pp 1234567890)
(pp (char=? #\a #\b))
(pp (char=? #\a #\a))
(pp (char=? #\b #\a))
(pp (char<? #\a #\b))
(pp (char<? #\a #\a))
(pp (char<? #\b #\a))
(pp (char>? #\a #\b))
(pp (char>? #\a #\a))
(pp (char>? #\b #\a))
(pp (char<=? #\a #\b))
(pp (char<=? #\a #\a))
(pp (char<=? #\b #\a))
(pp (char>=? #\a #\b))
(pp (char>=? #\a #\a))
(pp (char>=? #\b #\a))
(pp 1234567890)
(pp (char<? #\0 #\9))
(pp (char<? #\5 #\5))
(pp (char<? #\9 #\0))
(pp (char>? #\0 #\9))
(pp (char>? #\5 #\5))
(pp (char>? #\9 #\0))
(pp (char<=? #\0 #\9))
(pp (char<=? #\5 #\5))
(pp (char<=? #\9 #\0))
(pp (char>=? #\0 #\9))
(pp (char>=? #\5 #\5))
(pp (char>=? #\9 #\0))
(pp 1234567890)
(pp (char=? #\a #\1))
(pp (char=? #\A #\1))
(pp (char=? #\1 #\a))
(pp (char=? #\1 #\A))
(pp (char=? #\a #\A))
(pp (char=? #\A #\a))
(pp (char<? #\a #\1))
(pp (char<? #\A #\1))
(pp (char<? #\1 #\a))
(pp (char<? #\1 #\A))
(pp (char<? #\a #\A))
(pp (char<? #\A #\a))
(pp (char>? #\a #\1))
(pp (char>? #\A #\1))
(pp (char>? #\1 #\a))
(pp (char>? #\1 #\A))
(pp (char>? #\a #\A))
(pp (char>? #\A #\a))
(pp (char<=? #\a #\1))
(pp (char<=? #\A #\1))
(pp (char<=? #\1 #\a))
(pp (char<=? #\1 #\A))
(pp (char<=? #\a #\A))
(pp (char<=? #\A #\a))
(pp (char>=? #\a #\1))
(pp (char>=? #\A #\1))
(pp (char>=? #\1 #\a))
(pp (char>=? #\1 #\A))
(pp (char>=? #\a #\A))
(pp (char>=? #\A #\a))
(pp 1234567890)
(pp (char-alphabetic? #\`))
(pp (char-alphabetic? #\a))
(pp (char-alphabetic? #\s))
(pp (char-alphabetic? #\z))
(pp (char-alphabetic? #\{))
(pp (char-alphabetic? #\@))
(pp (char-alphabetic? #\A))
(pp (char-alphabetic? #\S))
(pp (char-alphabetic? #\Z))
(pp (char-alphabetic? #\[))
(pp (char-alphabetic? #\_))
(pp (char-alphabetic? #\5))
(pp 1234567890)
(pp (char-numeric? #\/))
(pp (char-numeric? #\0))
(pp (char-numeric? #\5))
(pp (char-numeric? #\9))
(pp (char-numeric? #\:))
(pp (char-numeric? #\e))
(pp (char-numeric? #\E))
(pp (char-numeric? #\+))
(pp 1234567890)
(pp (char-whitespace? #\a))
(pp (char-whitespace? #\6))
(pp (char-whitespace? #\A))
(pp (char-whitespace? #\+))
(pp (char-whitespace? #\{))
(pp (char-whitespace? #\space))
(pp (char-whitespace? #\tab))
(pp (char-whitespace? #\newline))
(pp (char-whitespace? #\page))
(pp (char-whitespace? #\return))
(pp 1234567890)
(pp (char-upper-case? #\a))
(pp (char-upper-case? #\6))
(pp (char-upper-case? #\{))
(pp (char-upper-case? #\*))
(pp (char-upper-case? #\return))
(pp (char-upper-case? #\A))
(pp (char-upper-case? #\S))
(pp (char-upper-case? #\Z))
(pp (char-upper-case? #\@))
(pp (char-upper-case? #\[))
(pp 1234567890)
(pp (char-lower-case? #\A))
(pp (char-lower-case? #\6))
(pp (char-lower-case? #\{))
(pp (char-lower-case? #\*))
(pp (char-lower-case? #\return))
(pp (char-lower-case? #\a))
(pp (char-lower-case? #\s))
(pp (char-lower-case? #\z))
(pp (char-lower-case? #\`))
(pp (char-lower-case? #\{))
(pp 1234567890)
(pp (char-upcase #\a))
(pp (char-upcase #\A))
(pp (char-upcase #\?))
(pp (char-upcase #\}))
(pp (char-upcase #\0))
(pp (char-upcase #\z))
(pp (char-upcase #\Z))
(pp (char-upcase #\r))
(pp (char-upcase #\R))
(pp 1234567890)
(pp (char-downcase #\a))
(pp (char-downcase #\A))
(pp (char-downcase #\?))
(pp (char-downcase #\}))
(pp (char-downcase #\0))
(pp (char-downcase #\z))
(pp (char-downcase #\Z))
(pp (char-downcase #\r))
(pp (char-downcase #\R))
(pp 1234567890)
(pp (char-ci=? #\A #\B))
(pp (char-ci=? #\A #\A))
(pp (char-ci=? #\B #\A))
(pp (char-ci<? #\A #\B))
(pp (char-ci<? #\A #\A))
(pp (char-ci<? #\B #\A))
(pp (char-ci>? #\A #\B))
(pp (char-ci>? #\A #\A))
(pp (char-ci>? #\B #\A))
(pp (char-ci<=? #\A #\B))
(pp (char-ci<=? #\A #\A))
(pp (char-ci<=? #\B #\A))
(pp (char-ci>=? #\A #\B))
(pp (char-ci>=? #\A #\A))
(pp (char-ci>=? #\B #\A))
(pp 1234567890)
(pp (char-ci=? #\a #\b))
(pp (char-ci=? #\a #\a))
(pp (char-ci=? #\b #\a))
(pp (char-ci<? #\a #\b))
(pp (char-ci<? #\a #\a))
(pp (char-ci<? #\b #\a))
(pp (char-ci>? #\a #\b))
(pp (char-ci>? #\a #\a))
(pp (char-ci>? #\b #\a))
(pp (char-ci<=? #\a #\b))
(pp (char-ci<=? #\a #\a))
(pp (char-ci<=? #\b #\a))
(pp (char-ci>=? #\a #\b))
(pp (char-ci>=? #\a #\a))
(pp (char-ci>=? #\b #\a))
(pp 1234567890)
(pp (char-ci<? #\0 #\9))
(pp (char-ci<? #\5 #\5))
(pp (char-ci<? #\9 #\0))
(pp (char-ci>? #\0 #\9))
(pp (char-ci>? #\5 #\5))
(pp (char-ci>? #\9 #\0))
(pp (char-ci<=? #\0 #\9))
(pp (char-ci<=? #\5 #\5))
(pp (char-ci<=? #\9 #\0))
(pp (char-ci>=? #\0 #\9))
(pp (char-ci>=? #\5 #\5))
(pp (char-ci>=? #\9 #\0))
(pp 1234567890)
(pp (char-ci=? #\a #\1))
(pp (char-ci=? #\A #\1))
(pp (char-ci=? #\1 #\a))
(pp (char-ci=? #\1 #\A))
(pp (char-ci=? #\a #\A))
(pp (char-ci=? #\A #\a))
(pp (char-ci<? #\a #\1))
(pp (char-ci<? #\A #\1))
(pp (char-ci<? #\1 #\a))
(pp (char-ci<? #\1 #\A))
(pp (char-ci<? #\a #\A))
(pp (char-ci<? #\A #\a))
(pp (char-ci>? #\a #\1))
(pp (char-ci>? #\A #\1))
(pp (char-ci>? #\1 #\a))
(pp (char-ci>? #\1 #\A))
(pp (char-ci>? #\a #\A))
(pp (char-ci>? #\A #\a))
(pp (char-ci<=? #\a #\1))
(pp (char-ci<=? #\A #\1))
(pp (char-ci<=? #\1 #\a))
(pp (char-ci<=? #\1 #\A))
(pp (char-ci<=? #\a #\A))
(pp (char-ci<=? #\A #\a))
(pp (char-ci>=? #\a #\1))
(pp (char-ci>=? #\A #\1))
(pp (char-ci>=? #\1 #\a))
(pp (char-ci>=? #\1 #\A))
(pp (char-ci>=? #\a #\A))
(pp (char-ci>=? #\A #\a))
;#f
;#t
;#f
;#t
;#f
;#f
;#f
;#f
;#t
;#t
;#t
;#f
;#f
;#t
;#t
1234567890
;#f
;#t
;#f
;#t
;#f
;#f
;#f
;#f
;#t
;#t
;#t
;#f
;#f
;#t
;#t
1234567890
;#t
;#f
;#f
;#f
;#f
;#t
;#t
;#t
;#f
;#f
;#t
;#t
1234567890
;#f
;#f
;#f
;#f
;#f
;#f
;#f
;#f
;#t
;#t
;#f
;#t
;#t
;#t
;#f
;#f
;#t
;#f
;#f
;#f
;#t
;#t
;#f
;#t
;#t
;#t
;#f
;#f
;#t
;#f
1234567890
;#f
;#t
;#t
;#t
;#f
;#f
;#t
;#t
;#t
;#f
;#f
;#f
1234567890
;#f
;#t
;#t
;#t
;#f
;#f
;#f
;#f
1234567890
;#f
;#f
;#f
;#f
;#f
;#t
;#t
;#t
;#t
;#t
1234567890
;#f
;#f
;#f
;#f
;#f
;#t
;#t
;#t
;#f
;#f
1234567890
;#f
;#f
;#f
;#f
;#f
;#t
;#t
;#t
;#f
;#f
1234567890
# \A
# \A
;#\?
;#\}
;#\0
;#\Z
;#\Z
# \R
# \R
1234567890
# \a
# \a
;#\?
;#\}
;#\0
;#\z
;#\z
# \r
# \r
1234567890
;#f
;#t
;#f
;#t
;#f
;#f
;#f
;#f
;#t
;#t
;#t
;#f
;#f
;#t
;#t
1234567890
;#f
;#t
;#f
;#t
;#f
;#f
;#f
;#f
;#t
;#t
;#t
;#f
;#f
;#t
;#t
1234567890
;#t
;#f
;#f
;#f
;#f
;#t
;#t
;#t
;#f
;#f
;#t
;#t
1234567890
;#f
;#f
;#f
;#f
;#t
;#t
;#f
;#f
;#t
;#t
;#f
;#f
;#t
;#t
;#f
;#f
;#f
;#f
;#f
;#f
;#t
;#t
;#t
;#t
;#t
;#t
;#f
;#f
;#t
;#t
| null | https://raw.githubusercontent.com/bsaleil/lc/ee7867fd2bdbbe88924300e10b14ea717ee6434b/unit-tests/chars.scm | scheme | ---------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
#f
#t
#f
#t
#f
#f
#f
#f
#t
#t
#t
#f
#f
#t
#t
#f
#t
#f
#t
#f
#f
#f
#f
#t
#t
#t
#f
#f
#t
#t
#t
#f
#f
#f
#f
#t
#t
#t
#f
#f
#t
#t
#f
#f
#f
#f
#f
#f
#f
#f
#t
#t
#f
#t
#t
#t
#f
#f
#t
#f
#f
#f
#t
#t
#f
#t
#t
#t
#f
#f
#t
#f
#f
#t
#t
#t
#f
#f
#t
#t
#t
#f
#f
#f
#f
#t
#t
#t
#f
#f
#f
#f
#f
#f
#f
#f
#f
#t
#t
#t
#t
#t
#f
#f
#f
#f
#f
#t
#t
#t
#f
#f
#f
#f
#f
#f
#f
#t
#t
#t
#f
#f
#\?
#\}
#\0
#\Z
#\Z
#\?
#\}
#\0
#\z
#\z
#f
#t
#f
#t
#f
#f
#f
#f
#t
#t
#t
#f
#f
#t
#t
#f
#t
#f
#t
#f
#f
#f
#f
#t
#t
#t
#f
#f
#t
#t
#t
#f
#f
#f
#f
#t
#t
#t
#f
#f
#t
#t
#f
#f
#f
#f
#t
#t
#f
#f
#t
#t
#f
#f
#t
#t
#f
#f
#f
#f
#f
#f
#t
#t
#t
#t
#t
#t
#f
#f
#t
#t | Copyright ( c ) 2015 , . All rights reserved .
THIS SOFTWARE IS PROVIDED ` ` AS IS '' AND ANY EXPRESS OR
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
(pp (char=? #\A #\B))
(pp (char=? #\A #\A))
(pp (char=? #\B #\A))
(pp (char<? #\A #\B))
(pp (char<? #\A #\A))
(pp (char<? #\B #\A))
(pp (char>? #\A #\B))
(pp (char>? #\A #\A))
(pp (char>? #\B #\A))
(pp (char<=? #\A #\B))
(pp (char<=? #\A #\A))
(pp (char<=? #\B #\A))
(pp (char>=? #\A #\B))
(pp (char>=? #\A #\A))
(pp (char>=? #\B #\A))
(pp 1234567890)
(pp (char=? #\a #\b))
(pp (char=? #\a #\a))
(pp (char=? #\b #\a))
(pp (char<? #\a #\b))
(pp (char<? #\a #\a))
(pp (char<? #\b #\a))
(pp (char>? #\a #\b))
(pp (char>? #\a #\a))
(pp (char>? #\b #\a))
(pp (char<=? #\a #\b))
(pp (char<=? #\a #\a))
(pp (char<=? #\b #\a))
(pp (char>=? #\a #\b))
(pp (char>=? #\a #\a))
(pp (char>=? #\b #\a))
(pp 1234567890)
(pp (char<? #\0 #\9))
(pp (char<? #\5 #\5))
(pp (char<? #\9 #\0))
(pp (char>? #\0 #\9))
(pp (char>? #\5 #\5))
(pp (char>? #\9 #\0))
(pp (char<=? #\0 #\9))
(pp (char<=? #\5 #\5))
(pp (char<=? #\9 #\0))
(pp (char>=? #\0 #\9))
(pp (char>=? #\5 #\5))
(pp (char>=? #\9 #\0))
(pp 1234567890)
(pp (char=? #\a #\1))
(pp (char=? #\A #\1))
(pp (char=? #\1 #\a))
(pp (char=? #\1 #\A))
(pp (char=? #\a #\A))
(pp (char=? #\A #\a))
(pp (char<? #\a #\1))
(pp (char<? #\A #\1))
(pp (char<? #\1 #\a))
(pp (char<? #\1 #\A))
(pp (char<? #\a #\A))
(pp (char<? #\A #\a))
(pp (char>? #\a #\1))
(pp (char>? #\A #\1))
(pp (char>? #\1 #\a))
(pp (char>? #\1 #\A))
(pp (char>? #\a #\A))
(pp (char>? #\A #\a))
(pp (char<=? #\a #\1))
(pp (char<=? #\A #\1))
(pp (char<=? #\1 #\a))
(pp (char<=? #\1 #\A))
(pp (char<=? #\a #\A))
(pp (char<=? #\A #\a))
(pp (char>=? #\a #\1))
(pp (char>=? #\A #\1))
(pp (char>=? #\1 #\a))
(pp (char>=? #\1 #\A))
(pp (char>=? #\a #\A))
(pp (char>=? #\A #\a))
(pp 1234567890)
(pp (char-alphabetic? #\`))
(pp (char-alphabetic? #\a))
(pp (char-alphabetic? #\s))
(pp (char-alphabetic? #\z))
(pp (char-alphabetic? #\{))
(pp (char-alphabetic? #\@))
(pp (char-alphabetic? #\A))
(pp (char-alphabetic? #\S))
(pp (char-alphabetic? #\Z))
(pp (char-alphabetic? #\[))
(pp (char-alphabetic? #\_))
(pp (char-alphabetic? #\5))
(pp 1234567890)
(pp (char-numeric? #\/))
(pp (char-numeric? #\0))
(pp (char-numeric? #\5))
(pp (char-numeric? #\9))
(pp (char-numeric? #\:))
(pp (char-numeric? #\e))
(pp (char-numeric? #\E))
(pp (char-numeric? #\+))
(pp 1234567890)
(pp (char-whitespace? #\a))
(pp (char-whitespace? #\6))
(pp (char-whitespace? #\A))
(pp (char-whitespace? #\+))
(pp (char-whitespace? #\{))
(pp (char-whitespace? #\space))
(pp (char-whitespace? #\tab))
(pp (char-whitespace? #\newline))
(pp (char-whitespace? #\page))
(pp (char-whitespace? #\return))
(pp 1234567890)
(pp (char-upper-case? #\a))
(pp (char-upper-case? #\6))
(pp (char-upper-case? #\{))
(pp (char-upper-case? #\*))
(pp (char-upper-case? #\return))
(pp (char-upper-case? #\A))
(pp (char-upper-case? #\S))
(pp (char-upper-case? #\Z))
(pp (char-upper-case? #\@))
(pp (char-upper-case? #\[))
(pp 1234567890)
(pp (char-lower-case? #\A))
(pp (char-lower-case? #\6))
(pp (char-lower-case? #\{))
(pp (char-lower-case? #\*))
(pp (char-lower-case? #\return))
(pp (char-lower-case? #\a))
(pp (char-lower-case? #\s))
(pp (char-lower-case? #\z))
(pp (char-lower-case? #\`))
(pp (char-lower-case? #\{))
(pp 1234567890)
(pp (char-upcase #\a))
(pp (char-upcase #\A))
(pp (char-upcase #\?))
(pp (char-upcase #\}))
(pp (char-upcase #\0))
(pp (char-upcase #\z))
(pp (char-upcase #\Z))
(pp (char-upcase #\r))
(pp (char-upcase #\R))
(pp 1234567890)
(pp (char-downcase #\a))
(pp (char-downcase #\A))
(pp (char-downcase #\?))
(pp (char-downcase #\}))
(pp (char-downcase #\0))
(pp (char-downcase #\z))
(pp (char-downcase #\Z))
(pp (char-downcase #\r))
(pp (char-downcase #\R))
(pp 1234567890)
(pp (char-ci=? #\A #\B))
(pp (char-ci=? #\A #\A))
(pp (char-ci=? #\B #\A))
(pp (char-ci<? #\A #\B))
(pp (char-ci<? #\A #\A))
(pp (char-ci<? #\B #\A))
(pp (char-ci>? #\A #\B))
(pp (char-ci>? #\A #\A))
(pp (char-ci>? #\B #\A))
(pp (char-ci<=? #\A #\B))
(pp (char-ci<=? #\A #\A))
(pp (char-ci<=? #\B #\A))
(pp (char-ci>=? #\A #\B))
(pp (char-ci>=? #\A #\A))
(pp (char-ci>=? #\B #\A))
(pp 1234567890)
(pp (char-ci=? #\a #\b))
(pp (char-ci=? #\a #\a))
(pp (char-ci=? #\b #\a))
(pp (char-ci<? #\a #\b))
(pp (char-ci<? #\a #\a))
(pp (char-ci<? #\b #\a))
(pp (char-ci>? #\a #\b))
(pp (char-ci>? #\a #\a))
(pp (char-ci>? #\b #\a))
(pp (char-ci<=? #\a #\b))
(pp (char-ci<=? #\a #\a))
(pp (char-ci<=? #\b #\a))
(pp (char-ci>=? #\a #\b))
(pp (char-ci>=? #\a #\a))
(pp (char-ci>=? #\b #\a))
(pp 1234567890)
(pp (char-ci<? #\0 #\9))
(pp (char-ci<? #\5 #\5))
(pp (char-ci<? #\9 #\0))
(pp (char-ci>? #\0 #\9))
(pp (char-ci>? #\5 #\5))
(pp (char-ci>? #\9 #\0))
(pp (char-ci<=? #\0 #\9))
(pp (char-ci<=? #\5 #\5))
(pp (char-ci<=? #\9 #\0))
(pp (char-ci>=? #\0 #\9))
(pp (char-ci>=? #\5 #\5))
(pp (char-ci>=? #\9 #\0))
(pp 1234567890)
(pp (char-ci=? #\a #\1))
(pp (char-ci=? #\A #\1))
(pp (char-ci=? #\1 #\a))
(pp (char-ci=? #\1 #\A))
(pp (char-ci=? #\a #\A))
(pp (char-ci=? #\A #\a))
(pp (char-ci<? #\a #\1))
(pp (char-ci<? #\A #\1))
(pp (char-ci<? #\1 #\a))
(pp (char-ci<? #\1 #\A))
(pp (char-ci<? #\a #\A))
(pp (char-ci<? #\A #\a))
(pp (char-ci>? #\a #\1))
(pp (char-ci>? #\A #\1))
(pp (char-ci>? #\1 #\a))
(pp (char-ci>? #\1 #\A))
(pp (char-ci>? #\a #\A))
(pp (char-ci>? #\A #\a))
(pp (char-ci<=? #\a #\1))
(pp (char-ci<=? #\A #\1))
(pp (char-ci<=? #\1 #\a))
(pp (char-ci<=? #\1 #\A))
(pp (char-ci<=? #\a #\A))
(pp (char-ci<=? #\A #\a))
(pp (char-ci>=? #\a #\1))
(pp (char-ci>=? #\A #\1))
(pp (char-ci>=? #\1 #\a))
(pp (char-ci>=? #\1 #\A))
(pp (char-ci>=? #\a #\A))
(pp (char-ci>=? #\A #\a))
1234567890
1234567890
1234567890
1234567890
1234567890
1234567890
1234567890
1234567890
1234567890
# \A
# \A
# \R
# \R
1234567890
# \a
# \a
# \r
# \r
1234567890
1234567890
1234567890
1234567890
|
a463e886446daea581d23c0071a8564441f01b9fd44a440a4ab4039f7b170c04 | soulomoon/haskell-katas | AdditionAssoc.hs | # LANGUAGE TypeOperators , TypeFamilies , GADTs #
module Kyu4.AdditionAssoc where
-- | The natural numbers, encoded in types.
data Z
data S n
-- | Predicate describing natural numbers.
-- | This allows us to reason with `Nat`s.
data Natural :: * -> * where
NumZ :: Natural Z
NumS :: Natural n -> Natural (S n)
-- | Predicate describing equality of natural numbers.
data Equal :: * -> * -> * where
EqlZ :: Equal Z Z
EqlS :: Equal n m -> Equal (S n) (S m)
-- | Peano definition of addition.
type family (:+:) (n :: *) (m :: *) :: *
type instance Z :+: m = m
type instance S n :+: m = S (n :+: m)
-- Helpers
-- | For any n, n = n.
reflexive :: Natural n -> Equal n n
reflexive NumZ = EqlZ
reflexive (NumS x) = EqlS $ reflexive x
-- | if a = b, then b = a.
symmetric :: Equal a b -> Equal b a
symmetric EqlZ = EqlZ
symmetric (EqlS eq) = EqlS $ symmetric eq
-- This is the proof that the kata requires.
-- | a + (b + c) = (a + b) + c
plusAssoc :: Natural a -> Natural b -> Natural c -> Equal (a :+: (b :+: c)) ((a :+: b) :+: c)
plusAssoc NumZ NumZ a = reflexive a
plusAssoc NumZ (NumS b) c= EqlS $ symmetric $ plusAssoc NumZ b c
plusAssoc (NumS a) b c= EqlS $ plusAssoc a b c
| null | https://raw.githubusercontent.com/soulomoon/haskell-katas/0861338e945e5cbaadf98138cf8f5f24a6ca8bb3/src/Kyu4/AdditionAssoc.hs | haskell | | The natural numbers, encoded in types.
| Predicate describing natural numbers.
| This allows us to reason with `Nat`s.
| Predicate describing equality of natural numbers.
| Peano definition of addition.
Helpers
| For any n, n = n.
| if a = b, then b = a.
This is the proof that the kata requires.
| a + (b + c) = (a + b) + c | # LANGUAGE TypeOperators , TypeFamilies , GADTs #
module Kyu4.AdditionAssoc where
data Z
data S n
data Natural :: * -> * where
NumZ :: Natural Z
NumS :: Natural n -> Natural (S n)
data Equal :: * -> * -> * where
EqlZ :: Equal Z Z
EqlS :: Equal n m -> Equal (S n) (S m)
type family (:+:) (n :: *) (m :: *) :: *
type instance Z :+: m = m
type instance S n :+: m = S (n :+: m)
reflexive :: Natural n -> Equal n n
reflexive NumZ = EqlZ
reflexive (NumS x) = EqlS $ reflexive x
symmetric :: Equal a b -> Equal b a
symmetric EqlZ = EqlZ
symmetric (EqlS eq) = EqlS $ symmetric eq
plusAssoc :: Natural a -> Natural b -> Natural c -> Equal (a :+: (b :+: c)) ((a :+: b) :+: c)
plusAssoc NumZ NumZ a = reflexive a
plusAssoc NumZ (NumS b) c= EqlS $ symmetric $ plusAssoc NumZ b c
plusAssoc (NumS a) b c= EqlS $ plusAssoc a b c
|
2210da206131098d5d42211e418efd132e20bc654fd77a79ad4ba20a2e804bda | mzp/coq-ide-for-ios | type_errors.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
$ I d : type_errors.ml 8845 2006 - 05 - 23 07:41:58Z herbelin $
open Names
open Term
open Environ
type unsafe_judgment = constr * constr
let nf_betaiota c = c
(* Type errors. *)
type guard_error =
(* Fixpoints *)
| NotEnoughAbstractionInFixBody
| RecursionNotOnInductiveType of constr
| RecursionOnIllegalTerm of int * constr * int list * int list
| NotEnoughArgumentsForFixCall of int
(* CoFixpoints *)
| CodomainNotInductiveType of constr
| NestedRecursiveOccurrences
| UnguardedRecursiveCall of constr
| RecCallInTypeOfAbstraction of constr
| RecCallInNonRecArgOfConstructor of constr
| RecCallInTypeOfDef of constr
| RecCallInCaseFun of constr
| RecCallInCaseArg of constr
| RecCallInCasePred of constr
| NotGuardedForm of constr
type arity_error =
| NonInformativeToInformative
| StrongEliminationOnNonSmallType
| WrongArity
type type_error =
| UnboundRel of int
| UnboundVar of variable
| NotAType of unsafe_judgment
| BadAssumption of unsafe_judgment
| ReferenceVariables of constr
| ElimArity of inductive * sorts_family list * constr * unsafe_judgment
* (sorts_family * sorts_family * arity_error) option
| CaseNotInductive of unsafe_judgment
| WrongCaseInfo of inductive * case_info
| NumberBranches of unsafe_judgment * int
| IllFormedBranch of constr * int * constr * constr
| Generalization of (name * constr) * unsafe_judgment
| ActualType of unsafe_judgment * constr
| CantApplyBadType of
(int * constr * constr) * unsafe_judgment * unsafe_judgment array
| CantApplyNonFunctional of unsafe_judgment * unsafe_judgment array
| IllFormedRecBody of guard_error * name array * int
| IllTypedRecBody of
int * name array * unsafe_judgment array * constr array
exception TypeError of env * type_error
let nfj (c,ct) = (c, nf_betaiota ct)
let error_unbound_rel env n =
raise (TypeError (env, UnboundRel n))
let error_unbound_var env v =
raise (TypeError (env, UnboundVar v))
let error_not_type env j =
raise (TypeError (env, NotAType j))
let error_assumption env j =
raise (TypeError (env, BadAssumption j))
let error_reference_variables env id =
raise (TypeError (env, ReferenceVariables id))
let error_elim_arity env ind aritylst c pj okinds =
raise (TypeError (env, ElimArity (ind,aritylst,c,pj,okinds)))
let error_case_not_inductive env j =
raise (TypeError (env, CaseNotInductive j))
let error_number_branches env cj expn =
raise (TypeError (env, NumberBranches (nfj cj,expn)))
let error_ill_formed_branch env c i actty expty =
raise (TypeError (env,
IllFormedBranch (c,i,nf_betaiota actty, nf_betaiota expty)))
let error_generalization env nvar c =
raise (TypeError (env, Generalization (nvar,c)))
let error_actual_type env j expty =
raise (TypeError (env, ActualType (j,expty)))
let error_cant_apply_not_functional env rator randl =
raise (TypeError (env, CantApplyNonFunctional (rator,randl)))
let error_cant_apply_bad_type env t rator randl =
raise (TypeError (env, CantApplyBadType (t,rator,randl)))
let error_ill_formed_rec_body env why lna i =
raise (TypeError (env, IllFormedRecBody (why,lna,i)))
let error_ill_typed_rec_body env i lna vdefj vargs =
raise (TypeError (env, IllTypedRecBody (i,lna,vdefj,vargs)))
| null | https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/checker/type_errors.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Type errors.
Fixpoints
CoFixpoints | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
$ I d : type_errors.ml 8845 2006 - 05 - 23 07:41:58Z herbelin $
open Names
open Term
open Environ
type unsafe_judgment = constr * constr
let nf_betaiota c = c
type guard_error =
| NotEnoughAbstractionInFixBody
| RecursionNotOnInductiveType of constr
| RecursionOnIllegalTerm of int * constr * int list * int list
| NotEnoughArgumentsForFixCall of int
| CodomainNotInductiveType of constr
| NestedRecursiveOccurrences
| UnguardedRecursiveCall of constr
| RecCallInTypeOfAbstraction of constr
| RecCallInNonRecArgOfConstructor of constr
| RecCallInTypeOfDef of constr
| RecCallInCaseFun of constr
| RecCallInCaseArg of constr
| RecCallInCasePred of constr
| NotGuardedForm of constr
type arity_error =
| NonInformativeToInformative
| StrongEliminationOnNonSmallType
| WrongArity
type type_error =
| UnboundRel of int
| UnboundVar of variable
| NotAType of unsafe_judgment
| BadAssumption of unsafe_judgment
| ReferenceVariables of constr
| ElimArity of inductive * sorts_family list * constr * unsafe_judgment
* (sorts_family * sorts_family * arity_error) option
| CaseNotInductive of unsafe_judgment
| WrongCaseInfo of inductive * case_info
| NumberBranches of unsafe_judgment * int
| IllFormedBranch of constr * int * constr * constr
| Generalization of (name * constr) * unsafe_judgment
| ActualType of unsafe_judgment * constr
| CantApplyBadType of
(int * constr * constr) * unsafe_judgment * unsafe_judgment array
| CantApplyNonFunctional of unsafe_judgment * unsafe_judgment array
| IllFormedRecBody of guard_error * name array * int
| IllTypedRecBody of
int * name array * unsafe_judgment array * constr array
exception TypeError of env * type_error
let nfj (c,ct) = (c, nf_betaiota ct)
let error_unbound_rel env n =
raise (TypeError (env, UnboundRel n))
let error_unbound_var env v =
raise (TypeError (env, UnboundVar v))
let error_not_type env j =
raise (TypeError (env, NotAType j))
let error_assumption env j =
raise (TypeError (env, BadAssumption j))
let error_reference_variables env id =
raise (TypeError (env, ReferenceVariables id))
let error_elim_arity env ind aritylst c pj okinds =
raise (TypeError (env, ElimArity (ind,aritylst,c,pj,okinds)))
let error_case_not_inductive env j =
raise (TypeError (env, CaseNotInductive j))
let error_number_branches env cj expn =
raise (TypeError (env, NumberBranches (nfj cj,expn)))
let error_ill_formed_branch env c i actty expty =
raise (TypeError (env,
IllFormedBranch (c,i,nf_betaiota actty, nf_betaiota expty)))
let error_generalization env nvar c =
raise (TypeError (env, Generalization (nvar,c)))
let error_actual_type env j expty =
raise (TypeError (env, ActualType (j,expty)))
let error_cant_apply_not_functional env rator randl =
raise (TypeError (env, CantApplyNonFunctional (rator,randl)))
let error_cant_apply_bad_type env t rator randl =
raise (TypeError (env, CantApplyBadType (t,rator,randl)))
let error_ill_formed_rec_body env why lna i =
raise (TypeError (env, IllFormedRecBody (why,lna,i)))
let error_ill_typed_rec_body env i lna vdefj vargs =
raise (TypeError (env, IllTypedRecBody (i,lna,vdefj,vargs)))
|
ecf726d833485b1e57f244e3d181ed62f2c2ca9a930a807fda2880869a9cf23d | rowangithub/DOrder | delaunay.mli | (**************************************************************************)
(* *)
: a generic graph library for OCaml
Copyright ( C ) 2004 - 2007
, and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU Library General Public
License version 2 , with the special exception on linking
(* described in file LICENSE. *)
(* *)
(* This software 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. *)
(* *)
(**************************************************************************)
$ I d : delaunay.mli , v 1.8 2004 - 02 - 20 14:37:40 signoles Exp $
* triangulation
* triangulation is available for any CCC system in the sense
of Knuth 's ` ` Axioms and Hulls ''
of Knuth's ``Axioms and Hulls'' *)
module type CCC = sig
type point
val ccw : point -> point -> point -> bool
* The counterclockwise relation [ ccw p q r ] states that the
circle through points [ ( p , q , r ) ] is traversed counterclockwise
when we encounter the points in cyclic order [ p , q , r , p , ... ] *
circle through points [(p,q,r)] is traversed counterclockwise
when we encounter the points in cyclic order [p,q,r,p,...] **)
val in_circle : point -> point -> point -> point -> bool
* The relation [ in_circle p q r s ] states that [ s ] lies
inside the circle [ ( p , q , r ) ] if [ ccw p q r ] is true , or outside that
circle if [ ccw p q r ] is false .
inside the circle [(p,q,r)] if [ccw p q r] is true, or outside that
circle if [ccw p q r] is false. *)
end
(** The result of triangulation is an abstract value of type [triangulation].
Then one can iterate over all edges of the triangulation. *)
module type Triangulation = sig
module S : CCC
type triangulation
val triangulate : S.point array -> triangulation
* [ triangulate a ] computes the Delaunay triangulation of a set of
points , given as an array [ a ] . If [ N ] is the number of points
( that is [ Array.length a ] ) , then the running time is $ O(N \log N)$
on the average and $ O(N^2)$ on the worst - case . The space used is
always $ O(N)$.
points, given as an array [a]. If [N] is the number of points
(that is [Array.length a]), then the running time is $O(N \log N)$
on the average and $O(N^2)$ on the worst-case. The space used is
always $O(N)$. *)
val iter : (S.point -> S.point -> unit) -> triangulation -> unit
(** [iter f t] iterates over all edges of the triangulation [t].
[f u v] is called once for each undirected edge [(u,v)]. *)
val fold : (S.point -> S.point -> 'a -> 'a) -> triangulation -> 'a -> 'a
end
(** Generic Delaunay triangulation *)
module Make(S : CCC) : Triangulation with module S = S
(** Points with integer coordinates *)
module IntPoints : CCC with type point = int * int
* triangulation with integer coordinates
module Int : Triangulation with module S = IntPoints
(** Points with floating point coordinates *)
module FloatPoints : CCC with type point = float * float
* triangulation with floating point coordinates
module Float : Triangulation with module S = FloatPoints
| null | https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/external/ocamlgraph/src/delaunay.mli | ocaml | ************************************************************************
This software is free software; you can redistribute it and/or
described in file LICENSE.
This software 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.
************************************************************************
* The result of triangulation is an abstract value of type [triangulation].
Then one can iterate over all edges of the triangulation.
* [iter f t] iterates over all edges of the triangulation [t].
[f u v] is called once for each undirected edge [(u,v)].
* Generic Delaunay triangulation
* Points with integer coordinates
* Points with floating point coordinates | : a generic graph library for OCaml
Copyright ( C ) 2004 - 2007
, and
modify it under the terms of the GNU Library General Public
License version 2 , with the special exception on linking
$ I d : delaunay.mli , v 1.8 2004 - 02 - 20 14:37:40 signoles Exp $
* triangulation
* triangulation is available for any CCC system in the sense
of Knuth 's ` ` Axioms and Hulls ''
of Knuth's ``Axioms and Hulls'' *)
module type CCC = sig
type point
val ccw : point -> point -> point -> bool
* The counterclockwise relation [ ccw p q r ] states that the
circle through points [ ( p , q , r ) ] is traversed counterclockwise
when we encounter the points in cyclic order [ p , q , r , p , ... ] *
circle through points [(p,q,r)] is traversed counterclockwise
when we encounter the points in cyclic order [p,q,r,p,...] **)
val in_circle : point -> point -> point -> point -> bool
* The relation [ in_circle p q r s ] states that [ s ] lies
inside the circle [ ( p , q , r ) ] if [ ccw p q r ] is true , or outside that
circle if [ ccw p q r ] is false .
inside the circle [(p,q,r)] if [ccw p q r] is true, or outside that
circle if [ccw p q r] is false. *)
end
module type Triangulation = sig
module S : CCC
type triangulation
val triangulate : S.point array -> triangulation
* [ triangulate a ] computes the Delaunay triangulation of a set of
points , given as an array [ a ] . If [ N ] is the number of points
( that is [ Array.length a ] ) , then the running time is $ O(N \log N)$
on the average and $ O(N^2)$ on the worst - case . The space used is
always $ O(N)$.
points, given as an array [a]. If [N] is the number of points
(that is [Array.length a]), then the running time is $O(N \log N)$
on the average and $O(N^2)$ on the worst-case. The space used is
always $O(N)$. *)
val iter : (S.point -> S.point -> unit) -> triangulation -> unit
val fold : (S.point -> S.point -> 'a -> 'a) -> triangulation -> 'a -> 'a
end
module Make(S : CCC) : Triangulation with module S = S
module IntPoints : CCC with type point = int * int
* triangulation with integer coordinates
module Int : Triangulation with module S = IntPoints
module FloatPoints : CCC with type point = float * float
* triangulation with floating point coordinates
module Float : Triangulation with module S = FloatPoints
|
8f814ef66023c810a2defdbb52fd81af00b47cd550de35226903d82d28b177d3 | LexiFi/dead_code_analyzer | fooFn.ml | let f x = 12
let g x = 0
| null | https://raw.githubusercontent.com/LexiFi/dead_code_analyzer/c44dc2ea5ccb13df2145e9316e21c39f09dad506/examples/fooFn.ml | ocaml | let f x = 12
let g x = 0
| |
0f98a727c0326aa4c142b036e6e001d2817a1e71fbe9e3ddda1bb71d1918d492 | softwarelanguageslab/maf | R5RS_sigscheme_takr-3.scm | ; Changes:
* removed : 0
* added : 2
* swaps : 0
* negated predicates : 8
* swapped branches : 8
* calls to i d fun : 7
(letrec ((tak0 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak1 (tak37 (- x 1) y z) (tak11 (- y 1) z x) (tak17 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
z
(tak1 (tak37 (- x 1) y z) (tak11 (- y 1) z x) (tak17 (- z 1) x y)))))))
(tak1 (lambda (x y z)
(if (not (< y x))
(<change>
z
(tak2 (tak74 (- x 1) y z) (tak22 (- y 1) z x) (tak34 (- z 1) x y)))
(<change>
(tak2 (tak74 (- x 1) y z) (tak22 (- y 1) z x) (tak34 (- z 1) x y))
z))))
(tak2 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak3 (tak11 (- x 1) y z) (tak33 (- y 1) z x) (tak51 (- z 1) x y)))))
(tak3 (lambda (x y z)
(if (not (< y x))
z
(tak4 (tak48 (- x 1) y z) (tak44 (- y 1) z x) (tak68 (- z 1) x y)))))
(tak4 (lambda (x y z)
(if (not (< y x))
z
(tak5 (tak85 (- x 1) y z) (tak55 (- y 1) z x) (tak85 (- z 1) x y)))))
(tak5 (lambda (x y z)
(if (not (< y x))
z
(tak6 (tak22 (- x 1) y z) (tak66 (- y 1) z x) (tak2 (- z 1) x y)))))
(tak6 (lambda (x y z)
(if (not (< y x))
z
(tak7 (tak59 (- x 1) y z) (tak77 (- y 1) z x) (tak19 (- z 1) x y)))))
(tak7 (lambda (x y z)
(if (not (< y x))
z
(tak8 (tak96 (- x 1) y z) (tak88 (- y 1) z x) (tak36 (- z 1) x y)))))
(tak8 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak9 (tak33 (- x 1) y z) (tak99 (- y 1) z x) (tak53 (- z 1) x y)))))
(tak9 (lambda (x y z)
(if (not (< y x))
z
(tak10 (tak70 (- x 1) y z) (tak10 (- y 1) z x) (tak70 (- z 1) x y)))))
(tak10 (lambda (x y z)
(if (not (< y x))
z
(tak11 (tak7 (- x 1) y z) (tak21 (- y 1) z x) (tak87 (- z 1) x y)))))
(tak11 (lambda (x y z)
(if (not (< y x))
z
(tak12 (tak44 (- x 1) y z) (tak32 (- y 1) z x) (tak4 (- z 1) x y)))))
(tak12 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak13 (tak81 (- x 1) y z) (tak43 (- y 1) z x) (tak21 (- z 1) x y)))))
(tak13 (lambda (x y z)
(if (not (< y x))
z
(tak14 (tak18 (- x 1) y z) (tak54 (- y 1) z x) (tak38 (- z 1) x y)))))
(tak14 (lambda (x y z)
(if (not (< y x))
z
(tak15 (tak55 (- x 1) y z) (tak65 (- y 1) z x) (tak55 (- z 1) x y)))))
(tak15 (lambda (x y z)
(if (not (< y x))
z
(tak16 (tak92 (- x 1) y z) (tak76 (- y 1) z x) (tak72 (- z 1) x y)))))
(tak16 (lambda (x y z)
(if (not (< y x))
z
(tak17 (tak29 (- x 1) y z) (tak87 (- y 1) z x) (tak89 (- z 1) x y)))))
(tak17 (lambda (x y z)
(if (not (< y x))
z
(tak18 (tak66 (- x 1) y z) (tak98 (- y 1) z x) (tak6 (- z 1) x y)))))
(tak18 (lambda (x y z)
(if (not (< y x))
z
(tak19 (tak3 (- x 1) y z) (tak9 (- y 1) z x) (tak23 (- z 1) x y)))))
(tak19 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak20 (tak40 (- x 1) y z) (tak20 (- y 1) z x) (tak40 (- z 1) x y)))))
(tak20 (lambda (x y z)
(if (not (< y x))
z
(tak21 (tak77 (- x 1) y z) (tak31 (- y 1) z x) (tak57 (- z 1) x y)))))
(tak21 (lambda (x y z)
(if (not (< y x))
(<change>
z
(tak22 (tak14 (- x 1) y z) (tak42 (- y 1) z x) (tak74 (- z 1) x y)))
(<change>
(tak22 (tak14 (- x 1) y z) (tak42 (- y 1) z x) (tak74 (- z 1) x y))
z))))
(tak22 (lambda (x y z)
(if (not (< y x))
z
(tak23 (tak51 (- x 1) y z) (tak53 (- y 1) z x) (tak91 (- z 1) x y)))))
(tak23 (lambda (x y z)
(if (not (< y x))
z
(tak24 (tak88 (- x 1) y z) (tak64 (- y 1) z x) (tak8 (- z 1) x y)))))
(tak24 (lambda (x y z)
(if (not (< y x))
z
(tak25 (tak25 (- x 1) y z) (tak75 (- y 1) z x) (tak25 (- z 1) x y)))))
(tak25 (lambda (x y z)
(if (not (< y x))
z
(tak26 (tak62 (- x 1) y z) (tak86 (- y 1) z x) (tak42 (- z 1) x y)))))
(tak26 (lambda (x y z)
(if (not (< y x))
z
(tak27 (tak99 (- x 1) y z) (tak97 (- y 1) z x) (tak59 (- z 1) x y)))))
(tak27 (lambda (x y z)
(if (not (< y x))
z
(tak28 (tak36 (- x 1) y z) (tak8 (- y 1) z x) (tak76 (- z 1) x y)))))
(tak28 (lambda (x y z)
(if (not (< y x))
z
(tak29 (tak73 (- x 1) y z) (tak19 (- y 1) z x) (tak93 (- z 1) x y)))))
(tak29 (lambda (x y z)
(if (not (< y x))
z
(tak30 (tak10 (- x 1) y z) (tak30 (- y 1) z x) (tak10 (- z 1) x y)))))
(tak30 (lambda (x y z)
(if (not (< y x))
z
(tak31 (tak47 (- x 1) y z) (tak41 (- y 1) z x) (tak27 (- z 1) x y)))))
(tak31 (lambda (x y z)
(if (not (< y x))
z
(tak32 (tak84 (- x 1) y z) (tak52 (- y 1) z x) (tak44 (- z 1) x y)))))
(tak32 (lambda (x y z)
(if (not (< y x))
z
(tak33 (tak21 (- x 1) y z) (tak63 (- y 1) z x) (tak61 (- z 1) x y)))))
(tak33 (lambda (x y z)
(if (not (< y x))
z
(tak34 (tak58 (- x 1) y z) (tak74 (- y 1) z x) (tak78 (- z 1) x y)))))
(tak34 (lambda (x y z)
(if (not (< y x))
z
(tak35 (tak95 (- x 1) y z) (tak85 (- y 1) z x) (tak95 (- z 1) x y)))))
(tak35 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak36 (tak32 (- x 1) y z) (tak96 (- y 1) z x) (tak12 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
(<change>
z
(tak36 (tak32 (- x 1) y z) (tak96 (- y 1) z x) (tak12 (- z 1) x y)))
(<change>
(tak36 (tak32 (- x 1) y z) (tak96 (- y 1) z x) (tak12 (- z 1) x y))
z))))))
(tak36 (lambda (x y z)
(if (not (< y x))
(<change>
z
(tak37 (tak69 (- x 1) y z) (tak7 (- y 1) z x) (tak29 (- z 1) x y)))
(<change>
(tak37 (tak69 (- x 1) y z) (tak7 (- y 1) z x) (tak29 (- z 1) x y))
z))))
(tak37 (lambda (x y z)
(if (not (< y x))
z
(tak38 (tak6 (- x 1) y z) (tak18 (- y 1) z x) (tak46 (- z 1) x y)))))
(tak38 (lambda (x y z)
(if (not (< y x))
z
(tak39 (tak43 (- x 1) y z) (tak29 (- y 1) z x) (tak63 (- z 1) x y)))))
(tak39 (lambda (x y z)
(if (not (< y x))
z
(tak40 (tak80 (- x 1) y z) (tak40 (- y 1) z x) (tak80 (- z 1) x y)))))
(tak40 (lambda (x y z)
(if (not (< y x))
z
(tak41 (tak17 (- x 1) y z) (tak51 (- y 1) z x) (tak97 (- z 1) x y)))))
(tak41 (lambda (x y z)
(if (not (< y x))
(<change>
z
(tak42 (tak54 (- x 1) y z) (tak62 (- y 1) z x) (tak14 (- z 1) x y)))
(<change>
(tak42 (tak54 (- x 1) y z) (tak62 (- y 1) z x) (tak14 (- z 1) x y))
z))))
(tak42 (lambda (x y z)
(if (not (< y x))
z
(tak43 (tak91 (- x 1) y z) (tak73 (- y 1) z x) (tak31 (- z 1) x y)))))
(tak43 (lambda (x y z)
(if (not (< y x))
z
(tak44 (tak28 (- x 1) y z) (tak84 (- y 1) z x) (tak48 (- z 1) x y)))))
(tak44 (lambda (x y z)
(if (not (< y x))
z
(tak45 (tak65 (- x 1) y z) (tak95 (- y 1) z x) (tak65 (- z 1) x y)))))
(tak45 (lambda (x y z)
(if (not (< y x))
z
(tak46 (tak2 (- x 1) y z) (tak6 (- y 1) z x) (tak82 (- z 1) x y)))))
(tak46 (lambda (x y z)
(if (not (< y x))
z
(tak47 (tak39 (- x 1) y z) (tak17 (- y 1) z x) (tak99 (- z 1) x y)))))
(tak47 (lambda (x y z)
(if (not (< y x))
z
(tak48 (tak76 (- x 1) y z) (tak28 (- y 1) z x) (tak16 (- z 1) x y)))))
(tak48 (lambda (x y z)
(if (not (< y x))
z
(tak49 (tak13 (- x 1) y z) (tak39 (- y 1) z x) (tak33 (- z 1) x y)))))
(tak49 (lambda (x y z)
(if (not (< y x))
z
(tak50 (tak50 (- x 1) y z) (tak50 (- y 1) z x) (tak50 (- z 1) x y)))))
(tak50 (lambda (x y z)
(if (not (< y x))
z
(tak51 (tak87 (- x 1) y z) (tak61 (- y 1) z x) (tak67 (- z 1) x y)))))
(tak51 (lambda (x y z)
(if (not (< y x))
z
(tak52 (tak24 (- x 1) y z) (tak72 (- y 1) z x) (tak84 (- z 1) x y)))))
(tak52 (lambda (x y z)
(if (not (< y x))
z
(tak53 (tak61 (- x 1) y z) (tak83 (- y 1) z x) (tak1 (- z 1) x y)))))
(tak53 (lambda (x y z)
(if (not (< y x))
z
(tak54 (tak98 (- x 1) y z) (tak94 (- y 1) z x) (tak18 (- z 1) x y)))))
(tak54 (lambda (x y z)
(if (not (< y x))
z
(tak55 (tak35 (- x 1) y z) (tak5 (- y 1) z x) (tak35 (- z 1) x y)))))
(tak55 (lambda (x y z)
(if (not (< y x))
z
(tak56 (tak72 (- x 1) y z) (tak16 (- y 1) z x) (tak52 (- z 1) x y)))))
(tak56 (lambda (x y z)
(if (not (< y x))
z
(tak57 (tak9 (- x 1) y z) (tak27 (- y 1) z x) (tak69 (- z 1) x y)))))
(tak57 (lambda (x y z)
(if (not (< y x))
z
(tak58 (tak46 (- x 1) y z) (tak38 (- y 1) z x) (tak86 (- z 1) x y)))))
(tak58 (lambda (x y z)
(if (not (< y x))
z
(tak59 (tak83 (- x 1) y z) (tak49 (- y 1) z x) (tak3 (- z 1) x y)))))
(tak59 (lambda (x y z)
(if (not (< y x))
z
(tak60 (tak20 (- x 1) y z) (tak60 (- y 1) z x) (tak20 (- z 1) x y)))))
(tak60 (lambda (x y z)
(if (not (< y x))
z
(tak61 (tak57 (- x 1) y z) (tak71 (- y 1) z x) (tak37 (- z 1) x y)))))
(tak61 (lambda (x y z)
(if (not (< y x))
z
(tak62 (tak94 (- x 1) y z) (tak82 (- y 1) z x) (tak54 (- z 1) x y)))))
(tak62 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak63 (tak31 (- x 1) y z) (tak93 (- y 1) z x) (tak71 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
z
(tak63 (tak31 (- x 1) y z) (tak93 (- y 1) z x) (tak71 (- z 1) x y)))))))
(tak63 (lambda (x y z)
(if (not (< y x))
z
(tak64 (tak68 (- x 1) y z) (tak4 (- y 1) z x) (tak88 (- z 1) x y)))))
(tak64 (lambda (x y z)
(if (not (< y x))
z
(tak65 (tak5 (- x 1) y z) (tak15 (- y 1) z x) (tak5 (- z 1) x y)))))
(tak65 (lambda (x y z)
(if (not (< y x))
(<change>
z
(tak66 (tak42 (- x 1) y z) (tak26 (- y 1) z x) (tak22 (- z 1) x y)))
(<change>
(tak66 (tak42 (- x 1) y z) (tak26 (- y 1) z x) (tak22 (- z 1) x y))
z))))
(tak66 (lambda (x y z)
(if (not (< y x))
z
(tak67 (tak79 (- x 1) y z) (tak37 (- y 1) z x) (tak39 (- z 1) x y)))))
(tak67 (lambda (x y z)
(if (not (< y x))
z
(tak68 (tak16 (- x 1) y z) (tak48 (- y 1) z x) (tak56 (- z 1) x y)))))
(tak68 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak69 (tak53 (- x 1) y z) (tak59 (- y 1) z x) (tak73 (- z 1) x y)))))
(tak69 (lambda (x y z)
(if (not (< y x))
z
(tak70 (tak90 (- x 1) y z) (tak70 (- y 1) z x) (tak90 (- z 1) x y)))))
(tak70 (lambda (x y z)
(if (not (< y x))
z
(tak71 (tak27 (- x 1) y z) (tak81 (- y 1) z x) (tak7 (- z 1) x y)))))
(tak71 (lambda (x y z)
(if (not (< y x))
z
(tak72 (tak64 (- x 1) y z) (tak92 (- y 1) z x) (tak24 (- z 1) x y)))))
(tak72 (lambda (x y z)
(if (not (< y x))
z
(tak73 (tak1 (- x 1) y z) (tak3 (- y 1) z x) (tak41 (- z 1) x y)))))
(tak73 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak74 (tak38 (- x 1) y z) (tak14 (- y 1) z x) (tak58 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
(<change>
z
(tak74 (tak38 (- x 1) y z) (tak14 (- y 1) z x) (tak58 (- z 1) x y)))
(<change>
(tak74 (tak38 (- x 1) y z) (tak14 (- y 1) z x) (tak58 (- z 1) x y))
z))))))
(tak74 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak75 (tak75 (- x 1) y z) (tak25 (- y 1) z x) (tak75 (- z 1) x y)))))
(tak75 (lambda (x y z)
(if (not (< y x))
z
(tak76 (tak12 (- x 1) y z) (tak36 (- y 1) z x) (tak92 (- z 1) x y)))))
(tak76 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak77 (tak49 (- x 1) y z) (tak47 (- y 1) z x) (tak9 (- z 1) x y)))))
(tak77 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak78 (tak86 (- x 1) y z) (tak58 (- y 1) z x) (tak26 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
z
(tak78 (tak86 (- x 1) y z) (tak58 (- y 1) z x) (tak26 (- z 1) x y)))))))
(tak78 (lambda (x y z)
(if (not (< y x))
z
(tak79 (tak23 (- x 1) y z) (tak69 (- y 1) z x) (tak43 (- z 1) x y)))))
(tak79 (lambda (x y z)
(if (not (< y x))
(<change>
z
(tak80 (tak60 (- x 1) y z) (tak80 (- y 1) z x) (tak60 (- z 1) x y)))
(<change>
(tak80 (tak60 (- x 1) y z) (tak80 (- y 1) z x) (tak60 (- z 1) x y))
z))))
(tak80 (lambda (x y z)
(<change>
()
z)
(if (not (< y x))
z
(tak81 (tak97 (- x 1) y z) (tak91 (- y 1) z x) (tak77 (- z 1) x y)))))
(tak81 (lambda (x y z)
(if (not (< y x))
z
(tak82 (tak34 (- x 1) y z) (tak2 (- y 1) z x) (tak94 (- z 1) x y)))))
(tak82 (lambda (x y z)
(if (not (< y x))
z
(tak83 (tak71 (- x 1) y z) (tak13 (- y 1) z x) (tak11 (- z 1) x y)))))
(tak83 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak84 (tak8 (- x 1) y z) (tak24 (- y 1) z x) (tak28 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
z
(tak84 (tak8 (- x 1) y z) (tak24 (- y 1) z x) (tak28 (- z 1) x y)))))))
(tak84 (lambda (x y z)
(if (not (< y x))
z
(tak85 (tak45 (- x 1) y z) (tak35 (- y 1) z x) (tak45 (- z 1) x y)))))
(tak85 (lambda (x y z)
(if (not (< y x))
z
(tak86 (tak82 (- x 1) y z) (tak46 (- y 1) z x) (tak62 (- z 1) x y)))))
(tak86 (lambda (x y z)
(if (not (< y x))
z
(tak87 (tak19 (- x 1) y z) (tak57 (- y 1) z x) (tak79 (- z 1) x y)))))
(tak87 (lambda (x y z)
(if (not (< y x))
z
(tak88 (tak56 (- x 1) y z) (tak68 (- y 1) z x) (tak96 (- z 1) x y)))))
(tak88 (lambda (x y z)
(if (not (< y x))
z
(tak89 (tak93 (- x 1) y z) (tak79 (- y 1) z x) (tak13 (- z 1) x y)))))
(tak89 (lambda (x y z)
(if (not (< y x))
z
(tak90 (tak30 (- x 1) y z) (tak90 (- y 1) z x) (tak30 (- z 1) x y)))))
(tak90 (lambda (x y z)
(if (not (< y x))
z
(tak91 (tak67 (- x 1) y z) (tak1 (- y 1) z x) (tak47 (- z 1) x y)))))
(tak91 (lambda (x y z)
(if (not (< y x))
z
(tak92 (tak4 (- x 1) y z) (tak12 (- y 1) z x) (tak64 (- z 1) x y)))))
(tak92 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak93 (tak41 (- x 1) y z) (tak23 (- y 1) z x) (tak81 (- z 1) x y)))))
(tak93 (lambda (x y z)
(if (not (< y x))
z
(tak94 (tak78 (- x 1) y z) (tak34 (- y 1) z x) (tak98 (- z 1) x y)))))
(tak94 (lambda (x y z)
(if (not (< y x))
z
(tak95 (tak15 (- x 1) y z) (tak45 (- y 1) z x) (tak15 (- z 1) x y)))))
(tak95 (lambda (x y z)
(if (not (< y x))
z
(tak96 (tak52 (- x 1) y z) (tak56 (- y 1) z x) (tak32 (- z 1) x y)))))
(tak96 (lambda (x y z)
(if (not (< y x))
z
(tak97 (tak89 (- x 1) y z) (tak67 (- y 1) z x) (tak49 (- z 1) x y)))))
(tak97 (lambda (x y z)
(<change>
()
-)
(if (not (< y x))
z
(tak98 (tak26 (- x 1) y z) (tak78 (- y 1) z x) (tak66 (- z 1) x y)))))
(tak98 (lambda (x y z)
(if (not (< y x))
z
(tak99 (tak63 (- x 1) y z) (tak89 (- y 1) z x) (tak83 (- z 1) x y)))))
(tak99 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak0 (tak0 (- x 1) y z) (tak0 (- y 1) z x) (tak0 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
z
(tak0 (tak0 (- x 1) y z) (tak0 (- y 1) z x) (tak0 (- z 1) x y))))))))
(tak0 18 12 6)) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_sigscheme_takr-3.scm | scheme | Changes: | * removed : 0
* added : 2
* swaps : 0
* negated predicates : 8
* swapped branches : 8
* calls to i d fun : 7
(letrec ((tak0 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak1 (tak37 (- x 1) y z) (tak11 (- y 1) z x) (tak17 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
z
(tak1 (tak37 (- x 1) y z) (tak11 (- y 1) z x) (tak17 (- z 1) x y)))))))
(tak1 (lambda (x y z)
(if (not (< y x))
(<change>
z
(tak2 (tak74 (- x 1) y z) (tak22 (- y 1) z x) (tak34 (- z 1) x y)))
(<change>
(tak2 (tak74 (- x 1) y z) (tak22 (- y 1) z x) (tak34 (- z 1) x y))
z))))
(tak2 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak3 (tak11 (- x 1) y z) (tak33 (- y 1) z x) (tak51 (- z 1) x y)))))
(tak3 (lambda (x y z)
(if (not (< y x))
z
(tak4 (tak48 (- x 1) y z) (tak44 (- y 1) z x) (tak68 (- z 1) x y)))))
(tak4 (lambda (x y z)
(if (not (< y x))
z
(tak5 (tak85 (- x 1) y z) (tak55 (- y 1) z x) (tak85 (- z 1) x y)))))
(tak5 (lambda (x y z)
(if (not (< y x))
z
(tak6 (tak22 (- x 1) y z) (tak66 (- y 1) z x) (tak2 (- z 1) x y)))))
(tak6 (lambda (x y z)
(if (not (< y x))
z
(tak7 (tak59 (- x 1) y z) (tak77 (- y 1) z x) (tak19 (- z 1) x y)))))
(tak7 (lambda (x y z)
(if (not (< y x))
z
(tak8 (tak96 (- x 1) y z) (tak88 (- y 1) z x) (tak36 (- z 1) x y)))))
(tak8 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak9 (tak33 (- x 1) y z) (tak99 (- y 1) z x) (tak53 (- z 1) x y)))))
(tak9 (lambda (x y z)
(if (not (< y x))
z
(tak10 (tak70 (- x 1) y z) (tak10 (- y 1) z x) (tak70 (- z 1) x y)))))
(tak10 (lambda (x y z)
(if (not (< y x))
z
(tak11 (tak7 (- x 1) y z) (tak21 (- y 1) z x) (tak87 (- z 1) x y)))))
(tak11 (lambda (x y z)
(if (not (< y x))
z
(tak12 (tak44 (- x 1) y z) (tak32 (- y 1) z x) (tak4 (- z 1) x y)))))
(tak12 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak13 (tak81 (- x 1) y z) (tak43 (- y 1) z x) (tak21 (- z 1) x y)))))
(tak13 (lambda (x y z)
(if (not (< y x))
z
(tak14 (tak18 (- x 1) y z) (tak54 (- y 1) z x) (tak38 (- z 1) x y)))))
(tak14 (lambda (x y z)
(if (not (< y x))
z
(tak15 (tak55 (- x 1) y z) (tak65 (- y 1) z x) (tak55 (- z 1) x y)))))
(tak15 (lambda (x y z)
(if (not (< y x))
z
(tak16 (tak92 (- x 1) y z) (tak76 (- y 1) z x) (tak72 (- z 1) x y)))))
(tak16 (lambda (x y z)
(if (not (< y x))
z
(tak17 (tak29 (- x 1) y z) (tak87 (- y 1) z x) (tak89 (- z 1) x y)))))
(tak17 (lambda (x y z)
(if (not (< y x))
z
(tak18 (tak66 (- x 1) y z) (tak98 (- y 1) z x) (tak6 (- z 1) x y)))))
(tak18 (lambda (x y z)
(if (not (< y x))
z
(tak19 (tak3 (- x 1) y z) (tak9 (- y 1) z x) (tak23 (- z 1) x y)))))
(tak19 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak20 (tak40 (- x 1) y z) (tak20 (- y 1) z x) (tak40 (- z 1) x y)))))
(tak20 (lambda (x y z)
(if (not (< y x))
z
(tak21 (tak77 (- x 1) y z) (tak31 (- y 1) z x) (tak57 (- z 1) x y)))))
(tak21 (lambda (x y z)
(if (not (< y x))
(<change>
z
(tak22 (tak14 (- x 1) y z) (tak42 (- y 1) z x) (tak74 (- z 1) x y)))
(<change>
(tak22 (tak14 (- x 1) y z) (tak42 (- y 1) z x) (tak74 (- z 1) x y))
z))))
(tak22 (lambda (x y z)
(if (not (< y x))
z
(tak23 (tak51 (- x 1) y z) (tak53 (- y 1) z x) (tak91 (- z 1) x y)))))
(tak23 (lambda (x y z)
(if (not (< y x))
z
(tak24 (tak88 (- x 1) y z) (tak64 (- y 1) z x) (tak8 (- z 1) x y)))))
(tak24 (lambda (x y z)
(if (not (< y x))
z
(tak25 (tak25 (- x 1) y z) (tak75 (- y 1) z x) (tak25 (- z 1) x y)))))
(tak25 (lambda (x y z)
(if (not (< y x))
z
(tak26 (tak62 (- x 1) y z) (tak86 (- y 1) z x) (tak42 (- z 1) x y)))))
(tak26 (lambda (x y z)
(if (not (< y x))
z
(tak27 (tak99 (- x 1) y z) (tak97 (- y 1) z x) (tak59 (- z 1) x y)))))
(tak27 (lambda (x y z)
(if (not (< y x))
z
(tak28 (tak36 (- x 1) y z) (tak8 (- y 1) z x) (tak76 (- z 1) x y)))))
(tak28 (lambda (x y z)
(if (not (< y x))
z
(tak29 (tak73 (- x 1) y z) (tak19 (- y 1) z x) (tak93 (- z 1) x y)))))
(tak29 (lambda (x y z)
(if (not (< y x))
z
(tak30 (tak10 (- x 1) y z) (tak30 (- y 1) z x) (tak10 (- z 1) x y)))))
(tak30 (lambda (x y z)
(if (not (< y x))
z
(tak31 (tak47 (- x 1) y z) (tak41 (- y 1) z x) (tak27 (- z 1) x y)))))
(tak31 (lambda (x y z)
(if (not (< y x))
z
(tak32 (tak84 (- x 1) y z) (tak52 (- y 1) z x) (tak44 (- z 1) x y)))))
(tak32 (lambda (x y z)
(if (not (< y x))
z
(tak33 (tak21 (- x 1) y z) (tak63 (- y 1) z x) (tak61 (- z 1) x y)))))
(tak33 (lambda (x y z)
(if (not (< y x))
z
(tak34 (tak58 (- x 1) y z) (tak74 (- y 1) z x) (tak78 (- z 1) x y)))))
(tak34 (lambda (x y z)
(if (not (< y x))
z
(tak35 (tak95 (- x 1) y z) (tak85 (- y 1) z x) (tak95 (- z 1) x y)))))
(tak35 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak36 (tak32 (- x 1) y z) (tak96 (- y 1) z x) (tak12 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
(<change>
z
(tak36 (tak32 (- x 1) y z) (tak96 (- y 1) z x) (tak12 (- z 1) x y)))
(<change>
(tak36 (tak32 (- x 1) y z) (tak96 (- y 1) z x) (tak12 (- z 1) x y))
z))))))
(tak36 (lambda (x y z)
(if (not (< y x))
(<change>
z
(tak37 (tak69 (- x 1) y z) (tak7 (- y 1) z x) (tak29 (- z 1) x y)))
(<change>
(tak37 (tak69 (- x 1) y z) (tak7 (- y 1) z x) (tak29 (- z 1) x y))
z))))
(tak37 (lambda (x y z)
(if (not (< y x))
z
(tak38 (tak6 (- x 1) y z) (tak18 (- y 1) z x) (tak46 (- z 1) x y)))))
(tak38 (lambda (x y z)
(if (not (< y x))
z
(tak39 (tak43 (- x 1) y z) (tak29 (- y 1) z x) (tak63 (- z 1) x y)))))
(tak39 (lambda (x y z)
(if (not (< y x))
z
(tak40 (tak80 (- x 1) y z) (tak40 (- y 1) z x) (tak80 (- z 1) x y)))))
(tak40 (lambda (x y z)
(if (not (< y x))
z
(tak41 (tak17 (- x 1) y z) (tak51 (- y 1) z x) (tak97 (- z 1) x y)))))
(tak41 (lambda (x y z)
(if (not (< y x))
(<change>
z
(tak42 (tak54 (- x 1) y z) (tak62 (- y 1) z x) (tak14 (- z 1) x y)))
(<change>
(tak42 (tak54 (- x 1) y z) (tak62 (- y 1) z x) (tak14 (- z 1) x y))
z))))
(tak42 (lambda (x y z)
(if (not (< y x))
z
(tak43 (tak91 (- x 1) y z) (tak73 (- y 1) z x) (tak31 (- z 1) x y)))))
(tak43 (lambda (x y z)
(if (not (< y x))
z
(tak44 (tak28 (- x 1) y z) (tak84 (- y 1) z x) (tak48 (- z 1) x y)))))
(tak44 (lambda (x y z)
(if (not (< y x))
z
(tak45 (tak65 (- x 1) y z) (tak95 (- y 1) z x) (tak65 (- z 1) x y)))))
(tak45 (lambda (x y z)
(if (not (< y x))
z
(tak46 (tak2 (- x 1) y z) (tak6 (- y 1) z x) (tak82 (- z 1) x y)))))
(tak46 (lambda (x y z)
(if (not (< y x))
z
(tak47 (tak39 (- x 1) y z) (tak17 (- y 1) z x) (tak99 (- z 1) x y)))))
(tak47 (lambda (x y z)
(if (not (< y x))
z
(tak48 (tak76 (- x 1) y z) (tak28 (- y 1) z x) (tak16 (- z 1) x y)))))
(tak48 (lambda (x y z)
(if (not (< y x))
z
(tak49 (tak13 (- x 1) y z) (tak39 (- y 1) z x) (tak33 (- z 1) x y)))))
(tak49 (lambda (x y z)
(if (not (< y x))
z
(tak50 (tak50 (- x 1) y z) (tak50 (- y 1) z x) (tak50 (- z 1) x y)))))
(tak50 (lambda (x y z)
(if (not (< y x))
z
(tak51 (tak87 (- x 1) y z) (tak61 (- y 1) z x) (tak67 (- z 1) x y)))))
(tak51 (lambda (x y z)
(if (not (< y x))
z
(tak52 (tak24 (- x 1) y z) (tak72 (- y 1) z x) (tak84 (- z 1) x y)))))
(tak52 (lambda (x y z)
(if (not (< y x))
z
(tak53 (tak61 (- x 1) y z) (tak83 (- y 1) z x) (tak1 (- z 1) x y)))))
(tak53 (lambda (x y z)
(if (not (< y x))
z
(tak54 (tak98 (- x 1) y z) (tak94 (- y 1) z x) (tak18 (- z 1) x y)))))
(tak54 (lambda (x y z)
(if (not (< y x))
z
(tak55 (tak35 (- x 1) y z) (tak5 (- y 1) z x) (tak35 (- z 1) x y)))))
(tak55 (lambda (x y z)
(if (not (< y x))
z
(tak56 (tak72 (- x 1) y z) (tak16 (- y 1) z x) (tak52 (- z 1) x y)))))
(tak56 (lambda (x y z)
(if (not (< y x))
z
(tak57 (tak9 (- x 1) y z) (tak27 (- y 1) z x) (tak69 (- z 1) x y)))))
(tak57 (lambda (x y z)
(if (not (< y x))
z
(tak58 (tak46 (- x 1) y z) (tak38 (- y 1) z x) (tak86 (- z 1) x y)))))
(tak58 (lambda (x y z)
(if (not (< y x))
z
(tak59 (tak83 (- x 1) y z) (tak49 (- y 1) z x) (tak3 (- z 1) x y)))))
(tak59 (lambda (x y z)
(if (not (< y x))
z
(tak60 (tak20 (- x 1) y z) (tak60 (- y 1) z x) (tak20 (- z 1) x y)))))
(tak60 (lambda (x y z)
(if (not (< y x))
z
(tak61 (tak57 (- x 1) y z) (tak71 (- y 1) z x) (tak37 (- z 1) x y)))))
(tak61 (lambda (x y z)
(if (not (< y x))
z
(tak62 (tak94 (- x 1) y z) (tak82 (- y 1) z x) (tak54 (- z 1) x y)))))
(tak62 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak63 (tak31 (- x 1) y z) (tak93 (- y 1) z x) (tak71 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
z
(tak63 (tak31 (- x 1) y z) (tak93 (- y 1) z x) (tak71 (- z 1) x y)))))))
(tak63 (lambda (x y z)
(if (not (< y x))
z
(tak64 (tak68 (- x 1) y z) (tak4 (- y 1) z x) (tak88 (- z 1) x y)))))
(tak64 (lambda (x y z)
(if (not (< y x))
z
(tak65 (tak5 (- x 1) y z) (tak15 (- y 1) z x) (tak5 (- z 1) x y)))))
(tak65 (lambda (x y z)
(if (not (< y x))
(<change>
z
(tak66 (tak42 (- x 1) y z) (tak26 (- y 1) z x) (tak22 (- z 1) x y)))
(<change>
(tak66 (tak42 (- x 1) y z) (tak26 (- y 1) z x) (tak22 (- z 1) x y))
z))))
(tak66 (lambda (x y z)
(if (not (< y x))
z
(tak67 (tak79 (- x 1) y z) (tak37 (- y 1) z x) (tak39 (- z 1) x y)))))
(tak67 (lambda (x y z)
(if (not (< y x))
z
(tak68 (tak16 (- x 1) y z) (tak48 (- y 1) z x) (tak56 (- z 1) x y)))))
(tak68 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak69 (tak53 (- x 1) y z) (tak59 (- y 1) z x) (tak73 (- z 1) x y)))))
(tak69 (lambda (x y z)
(if (not (< y x))
z
(tak70 (tak90 (- x 1) y z) (tak70 (- y 1) z x) (tak90 (- z 1) x y)))))
(tak70 (lambda (x y z)
(if (not (< y x))
z
(tak71 (tak27 (- x 1) y z) (tak81 (- y 1) z x) (tak7 (- z 1) x y)))))
(tak71 (lambda (x y z)
(if (not (< y x))
z
(tak72 (tak64 (- x 1) y z) (tak92 (- y 1) z x) (tak24 (- z 1) x y)))))
(tak72 (lambda (x y z)
(if (not (< y x))
z
(tak73 (tak1 (- x 1) y z) (tak3 (- y 1) z x) (tak41 (- z 1) x y)))))
(tak73 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak74 (tak38 (- x 1) y z) (tak14 (- y 1) z x) (tak58 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
(<change>
z
(tak74 (tak38 (- x 1) y z) (tak14 (- y 1) z x) (tak58 (- z 1) x y)))
(<change>
(tak74 (tak38 (- x 1) y z) (tak14 (- y 1) z x) (tak58 (- z 1) x y))
z))))))
(tak74 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak75 (tak75 (- x 1) y z) (tak25 (- y 1) z x) (tak75 (- z 1) x y)))))
(tak75 (lambda (x y z)
(if (not (< y x))
z
(tak76 (tak12 (- x 1) y z) (tak36 (- y 1) z x) (tak92 (- z 1) x y)))))
(tak76 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak77 (tak49 (- x 1) y z) (tak47 (- y 1) z x) (tak9 (- z 1) x y)))))
(tak77 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak78 (tak86 (- x 1) y z) (tak58 (- y 1) z x) (tak26 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
z
(tak78 (tak86 (- x 1) y z) (tak58 (- y 1) z x) (tak26 (- z 1) x y)))))))
(tak78 (lambda (x y z)
(if (not (< y x))
z
(tak79 (tak23 (- x 1) y z) (tak69 (- y 1) z x) (tak43 (- z 1) x y)))))
(tak79 (lambda (x y z)
(if (not (< y x))
(<change>
z
(tak80 (tak60 (- x 1) y z) (tak80 (- y 1) z x) (tak60 (- z 1) x y)))
(<change>
(tak80 (tak60 (- x 1) y z) (tak80 (- y 1) z x) (tak60 (- z 1) x y))
z))))
(tak80 (lambda (x y z)
(<change>
()
z)
(if (not (< y x))
z
(tak81 (tak97 (- x 1) y z) (tak91 (- y 1) z x) (tak77 (- z 1) x y)))))
(tak81 (lambda (x y z)
(if (not (< y x))
z
(tak82 (tak34 (- x 1) y z) (tak2 (- y 1) z x) (tak94 (- z 1) x y)))))
(tak82 (lambda (x y z)
(if (not (< y x))
z
(tak83 (tak71 (- x 1) y z) (tak13 (- y 1) z x) (tak11 (- z 1) x y)))))
(tak83 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak84 (tak8 (- x 1) y z) (tak24 (- y 1) z x) (tak28 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
z
(tak84 (tak8 (- x 1) y z) (tak24 (- y 1) z x) (tak28 (- z 1) x y)))))))
(tak84 (lambda (x y z)
(if (not (< y x))
z
(tak85 (tak45 (- x 1) y z) (tak35 (- y 1) z x) (tak45 (- z 1) x y)))))
(tak85 (lambda (x y z)
(if (not (< y x))
z
(tak86 (tak82 (- x 1) y z) (tak46 (- y 1) z x) (tak62 (- z 1) x y)))))
(tak86 (lambda (x y z)
(if (not (< y x))
z
(tak87 (tak19 (- x 1) y z) (tak57 (- y 1) z x) (tak79 (- z 1) x y)))))
(tak87 (lambda (x y z)
(if (not (< y x))
z
(tak88 (tak56 (- x 1) y z) (tak68 (- y 1) z x) (tak96 (- z 1) x y)))))
(tak88 (lambda (x y z)
(if (not (< y x))
z
(tak89 (tak93 (- x 1) y z) (tak79 (- y 1) z x) (tak13 (- z 1) x y)))))
(tak89 (lambda (x y z)
(if (not (< y x))
z
(tak90 (tak30 (- x 1) y z) (tak90 (- y 1) z x) (tak30 (- z 1) x y)))))
(tak90 (lambda (x y z)
(if (not (< y x))
z
(tak91 (tak67 (- x 1) y z) (tak1 (- y 1) z x) (tak47 (- z 1) x y)))))
(tak91 (lambda (x y z)
(if (not (< y x))
z
(tak92 (tak4 (- x 1) y z) (tak12 (- y 1) z x) (tak64 (- z 1) x y)))))
(tak92 (lambda (x y z)
(if (<change> (not (< y x)) (not (not (< y x))))
z
(tak93 (tak41 (- x 1) y z) (tak23 (- y 1) z x) (tak81 (- z 1) x y)))))
(tak93 (lambda (x y z)
(if (not (< y x))
z
(tak94 (tak78 (- x 1) y z) (tak34 (- y 1) z x) (tak98 (- z 1) x y)))))
(tak94 (lambda (x y z)
(if (not (< y x))
z
(tak95 (tak15 (- x 1) y z) (tak45 (- y 1) z x) (tak15 (- z 1) x y)))))
(tak95 (lambda (x y z)
(if (not (< y x))
z
(tak96 (tak52 (- x 1) y z) (tak56 (- y 1) z x) (tak32 (- z 1) x y)))))
(tak96 (lambda (x y z)
(if (not (< y x))
z
(tak97 (tak89 (- x 1) y z) (tak67 (- y 1) z x) (tak49 (- z 1) x y)))))
(tak97 (lambda (x y z)
(<change>
()
-)
(if (not (< y x))
z
(tak98 (tak26 (- x 1) y z) (tak78 (- y 1) z x) (tak66 (- z 1) x y)))))
(tak98 (lambda (x y z)
(if (not (< y x))
z
(tak99 (tak63 (- x 1) y z) (tak89 (- y 1) z x) (tak83 (- z 1) x y)))))
(tak99 (lambda (x y z)
(<change>
(if (not (< y x))
z
(tak0 (tak0 (- x 1) y z) (tak0 (- y 1) z x) (tak0 (- z 1) x y)))
((lambda (x) x)
(if (not (< y x))
z
(tak0 (tak0 (- x 1) y z) (tak0 (- y 1) z x) (tak0 (- z 1) x y))))))))
(tak0 18 12 6)) |
faf5bca59bce6f79ad2260197669d9c0344465ff28866470342bef88881348e9 | hedgehogqa/haskell-hedgehog-classes | Category.hs | # LANGUAGE ScopedTypeVariables #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE QuantifiedConstraints #
module Hedgehog.Classes.Category (categoryLaws, commutativeCategoryLaws) where
import Hedgehog
import Hedgehog.Classes.Common
import Control.Category(Category(..))
import Prelude hiding (id, (.))
-- | Tests the following 'Category' laws:
--
-- [__Left Identity__]: @'id' '.' f@ ≡ @f@
[ _ _ Right Identity _ _ ] : @f ' . ' ' id'@ ≡
-- [__Associativity__]: @f '.' (g '.' h)@ ≡ @(f '.' g) '.' h@
categoryLaws :: forall f.
( Category f
, forall x y. (Eq x, Eq y) => Eq (f x y)
, forall x y. (Show x, Show y) => Show (f x y)
) => (forall x y. Gen x -> Gen y -> Gen (f x y)) -> Laws
categoryLaws gen = Laws "Category"
[ ("Left Identity", categoryLeftIdentity gen)
, ("Right Identity", categoryRightIdentity gen)
, ("Associativity", categoryAssociativity gen)
]
-- | Tests the following 'Category' laws:
--
-- [__Commutativity__]: @f '.' g@ ≡ @g '.' f@
commutativeCategoryLaws :: forall f.
( Category f
, forall x y. (Eq x, Eq y) => Eq (f x y)
, forall x y. (Show x, Show y) => Show (f x y)
) => (forall x y. Gen x -> Gen y -> Gen (f x y)) -> Laws
commutativeCategoryLaws gen = Laws "Commutative Category"
[ ("Commutativity", categoryCommutativity gen)
]
categoryRightIdentity :: forall f.
( Category f
, forall x y. (Eq x, Eq y) => Eq (f x y)
, forall x y. (Show x, Show y) => Show (f x y)
) => (forall x y. Gen x -> Gen y -> Gen (f x y)) -> Property
categoryRightIdentity fgen = property $ do
x <- forAll $ fgen genSmallInteger genSmallInteger
(x . id) `heq2` x
categoryLeftIdentity :: forall f.
( Category f
, forall x y. (Eq x, Eq y) => Eq (f x y)
, forall x y. (Show x, Show y) => Show (f x y)
) => (forall x y. Gen x -> Gen y -> Gen (f x y)) -> Property
categoryLeftIdentity fgen = property $ do
x <- forAll $ fgen genSmallInteger genSmallInteger
(id . x) `heq2` x
categoryAssociativity :: forall f.
( Category f
, forall x y. (Eq x, Eq y) => Eq (f x y)
, forall x y. (Show x, Show y) => Show (f x y)
) => (forall x y. Gen x -> Gen y -> Gen (f x y)) -> Property
categoryAssociativity fgen = property $ do
f <- forAll $ fgen genSmallInteger genSmallInteger
g <- forAll $ fgen genSmallInteger genSmallInteger
h <- forAll $ fgen genSmallInteger genSmallInteger
(f . (g . h)) `heq2` ((f . g) . h)
categoryCommutativity :: forall f.
( Category f
, forall x y. (Eq x, Eq y) => Eq (f x y)
, forall x y. (Show x, Show y) => Show (f x y)
) => (forall x y. Gen x -> Gen y -> Gen (f x y)) -> Property
categoryCommutativity fgen = property $ do
f <- forAll $ fgen genSmallInteger genSmallInteger
g <- forAll $ fgen genSmallInteger genSmallInteger
(f . g) `heq2` (g . f)
| null | https://raw.githubusercontent.com/hedgehogqa/haskell-hedgehog-classes/4d97b000e915de8ba590818f551bce7bd862e7d4/src/Hedgehog/Classes/Category.hs | haskell | # LANGUAGE RankNTypes #
| Tests the following 'Category' laws:
[__Left Identity__]: @'id' '.' f@ ≡ @f@
[__Associativity__]: @f '.' (g '.' h)@ ≡ @(f '.' g) '.' h@
| Tests the following 'Category' laws:
[__Commutativity__]: @f '.' g@ ≡ @g '.' f@ | # LANGUAGE ScopedTypeVariables #
# LANGUAGE QuantifiedConstraints #
module Hedgehog.Classes.Category (categoryLaws, commutativeCategoryLaws) where
import Hedgehog
import Hedgehog.Classes.Common
import Control.Category(Category(..))
import Prelude hiding (id, (.))
[ _ _ Right Identity _ _ ] : @f ' . ' ' id'@ ≡
categoryLaws :: forall f.
( Category f
, forall x y. (Eq x, Eq y) => Eq (f x y)
, forall x y. (Show x, Show y) => Show (f x y)
) => (forall x y. Gen x -> Gen y -> Gen (f x y)) -> Laws
categoryLaws gen = Laws "Category"
[ ("Left Identity", categoryLeftIdentity gen)
, ("Right Identity", categoryRightIdentity gen)
, ("Associativity", categoryAssociativity gen)
]
commutativeCategoryLaws :: forall f.
( Category f
, forall x y. (Eq x, Eq y) => Eq (f x y)
, forall x y. (Show x, Show y) => Show (f x y)
) => (forall x y. Gen x -> Gen y -> Gen (f x y)) -> Laws
commutativeCategoryLaws gen = Laws "Commutative Category"
[ ("Commutativity", categoryCommutativity gen)
]
categoryRightIdentity :: forall f.
( Category f
, forall x y. (Eq x, Eq y) => Eq (f x y)
, forall x y. (Show x, Show y) => Show (f x y)
) => (forall x y. Gen x -> Gen y -> Gen (f x y)) -> Property
categoryRightIdentity fgen = property $ do
x <- forAll $ fgen genSmallInteger genSmallInteger
(x . id) `heq2` x
categoryLeftIdentity :: forall f.
( Category f
, forall x y. (Eq x, Eq y) => Eq (f x y)
, forall x y. (Show x, Show y) => Show (f x y)
) => (forall x y. Gen x -> Gen y -> Gen (f x y)) -> Property
categoryLeftIdentity fgen = property $ do
x <- forAll $ fgen genSmallInteger genSmallInteger
(id . x) `heq2` x
categoryAssociativity :: forall f.
( Category f
, forall x y. (Eq x, Eq y) => Eq (f x y)
, forall x y. (Show x, Show y) => Show (f x y)
) => (forall x y. Gen x -> Gen y -> Gen (f x y)) -> Property
categoryAssociativity fgen = property $ do
f <- forAll $ fgen genSmallInteger genSmallInteger
g <- forAll $ fgen genSmallInteger genSmallInteger
h <- forAll $ fgen genSmallInteger genSmallInteger
(f . (g . h)) `heq2` ((f . g) . h)
categoryCommutativity :: forall f.
( Category f
, forall x y. (Eq x, Eq y) => Eq (f x y)
, forall x y. (Show x, Show y) => Show (f x y)
) => (forall x y. Gen x -> Gen y -> Gen (f x y)) -> Property
categoryCommutativity fgen = property $ do
f <- forAll $ fgen genSmallInteger genSmallInteger
g <- forAll $ fgen genSmallInteger genSmallInteger
(f . g) `heq2` (g . f)
|
bca9638471d7621116d09c3763d1604cdae0ecf473809445618519f179c2935b | tel/oak | higher_order.cljs | (ns oak.component.higher-order
"Functions for constructing Components from sub-Components."
(:require
[oak.internal.utils :as util]
[oak.component :as oak]
[oak.dom :as d]
[schema.core :as s]
[oak.schema :as os]))
; -----------------------------------------------------------------------------
; Higher-order components
(defn parallel
"Construct a *static* component by gluing several subcomponents together
without interaction. Parallel components are made of a fixed set of named
subcomponents and have dramatically simplified wiring. Use parallel
components whenever you do not need custom state management behavior.
By default, a static component renders its subcomponents in a div in
arbitrary order. Provide a :view-compositor function to choose how to render
the subviews more specifically. It has a signature like (view-compositor
subviews) where `subviews` is a map with the same keys as your static
components containing ReactElements corresponding to each subcomponent.
By default, all events generated by a static component are simply routed in
parallel back to the originating subcomponents. Provide a
:routing-transform function to choose how events are routed more
specifically. It has a signature like (routing-transform target event
continue) where `target` is a key in your subcomponent map, `action` is the
event headed for that subcomponent, and `continue` is a callback of two
arguments, the target for the action and the action itself.
Any other options are forwarded on to `make`."
[subcomponent-map
& {:keys [view-compositor routing-transform]
:or {view-compositor (fn [views] (apply d/div {} (vals views)))
routing-transform (fn [target action cont] (cont target action))}
:as options}]
(let [core-design
{:model
(util/map-vals oak/model subcomponent-map)
:action
(apply os/cond-pair
(util/map-vals oak/action subcomponent-map))
:step
(fn static-step [[target action] model]
(routing-transform
target action
(fn [target action]
(update
model target
(oak/step
(get subcomponent-map target)
action)))))
:query
(fn static-query [model q]
(util/map-kvs
(fn [target subc] (oak/query subc (get model target) q))
subcomponent-map))
:view
(fn static-view [{:keys [model result]} submit]
(let [subviews (util/map-kvs
(fn [target subc]
(subc
(get model target)
(get result target)
(fn [ev] (submit [target ev]))))
subcomponent-map)]
(view-compositor subviews)))}]
; Let the remaining options override
(oak/make*
(merge core-design
(-> options
(dissoc :view-compositor)
(dissoc :routing-transform)))))) | null | https://raw.githubusercontent.com/tel/oak/12227273ba5fbc27bc0c5379017ee8902992670d/src/oak/component/higher_order.cljs | clojure | -----------------------------------------------------------------------------
Higher-order components
Let the remaining options override | (ns oak.component.higher-order
"Functions for constructing Components from sub-Components."
(:require
[oak.internal.utils :as util]
[oak.component :as oak]
[oak.dom :as d]
[schema.core :as s]
[oak.schema :as os]))
(defn parallel
"Construct a *static* component by gluing several subcomponents together
without interaction. Parallel components are made of a fixed set of named
subcomponents and have dramatically simplified wiring. Use parallel
components whenever you do not need custom state management behavior.
By default, a static component renders its subcomponents in a div in
arbitrary order. Provide a :view-compositor function to choose how to render
the subviews more specifically. It has a signature like (view-compositor
subviews) where `subviews` is a map with the same keys as your static
components containing ReactElements corresponding to each subcomponent.
By default, all events generated by a static component are simply routed in
parallel back to the originating subcomponents. Provide a
:routing-transform function to choose how events are routed more
specifically. It has a signature like (routing-transform target event
continue) where `target` is a key in your subcomponent map, `action` is the
event headed for that subcomponent, and `continue` is a callback of two
arguments, the target for the action and the action itself.
Any other options are forwarded on to `make`."
[subcomponent-map
& {:keys [view-compositor routing-transform]
:or {view-compositor (fn [views] (apply d/div {} (vals views)))
routing-transform (fn [target action cont] (cont target action))}
:as options}]
(let [core-design
{:model
(util/map-vals oak/model subcomponent-map)
:action
(apply os/cond-pair
(util/map-vals oak/action subcomponent-map))
:step
(fn static-step [[target action] model]
(routing-transform
target action
(fn [target action]
(update
model target
(oak/step
(get subcomponent-map target)
action)))))
:query
(fn static-query [model q]
(util/map-kvs
(fn [target subc] (oak/query subc (get model target) q))
subcomponent-map))
:view
(fn static-view [{:keys [model result]} submit]
(let [subviews (util/map-kvs
(fn [target subc]
(subc
(get model target)
(get result target)
(fn [ev] (submit [target ev]))))
subcomponent-map)]
(view-compositor subviews)))}]
(oak/make*
(merge core-design
(-> options
(dissoc :view-compositor)
(dissoc :routing-transform)))))) |
32f617205144f969fb395da4441c27f8a1acf112694f8b6e314c2a32f1caa4bd | circleci/circleci.test | cider.clj | (ns circleci.test.report.cider
"CIDER-compatible test reporter."
(:require [circleci.test.report :refer [TestReporter]]
[cider.nrepl.middleware.test :as cider]))
(deftype CIDERTestReporter []
TestReporter
(default [this m]
(cider/report m))
(pass [this m]
(cider/report m))
(fail [this m]
(cider/report m))
(error [this m]
(cider/report m))
(summary [this m]
(cider/report m))
(begin-test-ns [this m]
(cider/report m))
(end-test-ns [this m]
(cider/report m))
(begin-test-var [this m]
(cider/report m))
(end-test-var [this m]
(cider/report m)))
(defn reporter [_config]
(->CIDERTestReporter))
| null | https://raw.githubusercontent.com/circleci/circleci.test/eb2e44fe94e430648c852f7f736419dc70a4e5a1/src/circleci/test/report/cider.clj | clojure | (ns circleci.test.report.cider
"CIDER-compatible test reporter."
(:require [circleci.test.report :refer [TestReporter]]
[cider.nrepl.middleware.test :as cider]))
(deftype CIDERTestReporter []
TestReporter
(default [this m]
(cider/report m))
(pass [this m]
(cider/report m))
(fail [this m]
(cider/report m))
(error [this m]
(cider/report m))
(summary [this m]
(cider/report m))
(begin-test-ns [this m]
(cider/report m))
(end-test-ns [this m]
(cider/report m))
(begin-test-var [this m]
(cider/report m))
(end-test-var [this m]
(cider/report m)))
(defn reporter [_config]
(->CIDERTestReporter))
| |
586e0581acf95cec1ce6e174eba407308ebb9b39433a38a118e9a845bcfffeaa | ryukzak/nitta | ProcessIntegrity.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE PartialTypeSignatures #
# LANGUAGE TypeFamilies #
|
Module : NITTA.Model . ProcessIntegrity
Description : Checking the target process integrity
Copyright : ( c ) , , 2022
License : :
Stability : experimental
Module : NITTA.Model.ProcessIntegrity
Description : Checking the target process integrity
Copyright : (c) Artyom Kostyuchik, Aleksandr Penskoi, 2022
License : BSD3
Maintainer :
Stability : experimental
-}
module NITTA.Model.ProcessIntegrity (
ProcessIntegrity (checkProcessIntegrity),
isProcessIntegrity,
) where
import Data.Either
import Data.List qualified as L
import Data.Map.Strict qualified as M
import Data.Maybe
import Data.Set qualified as S
import Data.String.Utils qualified as S
import NITTA.Model.ProcessorUnits
import NITTA.Utils
class ProcessIntegrity u where
checkProcessIntegrity :: u -> Either String ()
isProcessIntegrity u = isRight $ checkProcessIntegrity u
instance (ProcessorUnit (pu v x t) v x t) => ProcessIntegrity (pu v x t) where
checkProcessIntegrity pu =
collectChecks
[ checkVerticalRelations (up2down pu) (pid2intermediate pu) (pid2endpoint pu) "intermediate not related to endpoint"
, checkVerticalRelations (down2up pu) (pid2endpoint pu) (pid2intermediate pu) "endpoint not related to intermediate"
, checkVerticalRelations (up2down pu) (pid2endpoint pu) (pid2instruction pu) "endpoint not related to instruction"
, checkVerticalRelations (down2up pu) (pid2instruction pu) (pid2endpoint pu) "instruction not related to endpoint"
]
checkVerticalRelations f dom codom errmsg =
collectChecks
$ map
( \x ->
let ys = M.findWithDefault S.empty x f
in if any (`M.member` codom) $ S.elems ys
then Right ()
else Left $ errmsg <> ": " <> show (dom M.! x)
)
$ M.keys dom
TODO : # 205 Divider : missing vertical relation between Do instruction and Endpoint
skipIntegrityErrors = ["instruction not related to endpoint: Instruction: Do"]
collectChecks checks = case lefts checks of
[] -> Right ()
errs -> case filter (`L.notElem` skipIntegrityErrors) errs of
[] -> Right ()
errs' -> Left $ S.join "; " errs'
relationsMap pairs = M.fromList $ map merge $ L.groupBy (\a b -> fst a == fst b) $ L.sortOn fst pairs
where
merge xs@((a, _) : _) = (a, S.fromList $ map snd xs)
merge _ = error "internal error"
up2down pu = relationsMap $ mapMaybe get $ relations $ process pu
where
get Vertical{vUp, vDown} = Just (vUp, vDown)
get _ = Nothing
down2up pu = relationsMap $ mapMaybe get $ relations $ process pu
where
get Vertical{vUp, vDown} = Just (vDown, vUp)
get _ = Nothing
pid2intermediate pu = M.fromList $ mapMaybe get $ steps $ process pu
where
get s@Step{pID}
| Just f <- getIntermediate s = Just (pID, f)
| otherwise = Nothing
pid2endpoint pu = M.fromList $ mapMaybe get $ steps $ process pu
where
get s@Step{pID}
| Just ep <- getEndpoint s = Just (pID, ep)
| otherwise = Nothing
pid2instruction pu = M.fromList $ mapMaybe get $ steps $ process pu
where
get s@Step{pID}
| Just instr <- getInstruction s = Just (pID, instr)
| otherwise = Nothing
| null | https://raw.githubusercontent.com/ryukzak/nitta/6d5cab0465ff5bcccfe419b8d8553266c530f7b7/src/NITTA/Model/ProcessIntegrity.hs | haskell | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE PartialTypeSignatures #
# LANGUAGE TypeFamilies #
|
Module : NITTA.Model . ProcessIntegrity
Description : Checking the target process integrity
Copyright : ( c ) , , 2022
License : :
Stability : experimental
Module : NITTA.Model.ProcessIntegrity
Description : Checking the target process integrity
Copyright : (c) Artyom Kostyuchik, Aleksandr Penskoi, 2022
License : BSD3
Maintainer :
Stability : experimental
-}
module NITTA.Model.ProcessIntegrity (
ProcessIntegrity (checkProcessIntegrity),
isProcessIntegrity,
) where
import Data.Either
import Data.List qualified as L
import Data.Map.Strict qualified as M
import Data.Maybe
import Data.Set qualified as S
import Data.String.Utils qualified as S
import NITTA.Model.ProcessorUnits
import NITTA.Utils
class ProcessIntegrity u where
checkProcessIntegrity :: u -> Either String ()
isProcessIntegrity u = isRight $ checkProcessIntegrity u
instance (ProcessorUnit (pu v x t) v x t) => ProcessIntegrity (pu v x t) where
checkProcessIntegrity pu =
collectChecks
[ checkVerticalRelations (up2down pu) (pid2intermediate pu) (pid2endpoint pu) "intermediate not related to endpoint"
, checkVerticalRelations (down2up pu) (pid2endpoint pu) (pid2intermediate pu) "endpoint not related to intermediate"
, checkVerticalRelations (up2down pu) (pid2endpoint pu) (pid2instruction pu) "endpoint not related to instruction"
, checkVerticalRelations (down2up pu) (pid2instruction pu) (pid2endpoint pu) "instruction not related to endpoint"
]
checkVerticalRelations f dom codom errmsg =
collectChecks
$ map
( \x ->
let ys = M.findWithDefault S.empty x f
in if any (`M.member` codom) $ S.elems ys
then Right ()
else Left $ errmsg <> ": " <> show (dom M.! x)
)
$ M.keys dom
TODO : # 205 Divider : missing vertical relation between Do instruction and Endpoint
skipIntegrityErrors = ["instruction not related to endpoint: Instruction: Do"]
collectChecks checks = case lefts checks of
[] -> Right ()
errs -> case filter (`L.notElem` skipIntegrityErrors) errs of
[] -> Right ()
errs' -> Left $ S.join "; " errs'
relationsMap pairs = M.fromList $ map merge $ L.groupBy (\a b -> fst a == fst b) $ L.sortOn fst pairs
where
merge xs@((a, _) : _) = (a, S.fromList $ map snd xs)
merge _ = error "internal error"
up2down pu = relationsMap $ mapMaybe get $ relations $ process pu
where
get Vertical{vUp, vDown} = Just (vUp, vDown)
get _ = Nothing
down2up pu = relationsMap $ mapMaybe get $ relations $ process pu
where
get Vertical{vUp, vDown} = Just (vDown, vUp)
get _ = Nothing
pid2intermediate pu = M.fromList $ mapMaybe get $ steps $ process pu
where
get s@Step{pID}
| Just f <- getIntermediate s = Just (pID, f)
| otherwise = Nothing
pid2endpoint pu = M.fromList $ mapMaybe get $ steps $ process pu
where
get s@Step{pID}
| Just ep <- getEndpoint s = Just (pID, ep)
| otherwise = Nothing
pid2instruction pu = M.fromList $ mapMaybe get $ steps $ process pu
where
get s@Step{pID}
| Just instr <- getInstruction s = Just (pID, instr)
| otherwise = Nothing
| |
540e892460a8b58977a025f9a93e4935a209ea4afc0629941d3f39bb83d91af5 | alesaccoia/festival_flinger | cmu_us_slt_phoneset.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;;
Carnegie Mellon University ; ; ;
and and ; ; ;
Copyright ( c ) 1998 - 2000 ; ; ;
All Rights Reserved . ; ; ;
;;; ;;;
;;; Permission is hereby granted, free of charge, to use and distribute ;;;
;;; this software and its documentation without restriction, including ;;;
;;; without limitation the rights to use, copy, modify, merge, publish, ;;;
;;; distribute, sublicense, and/or sell copies of this work, and to ;;;
;;; permit persons to whom this work is furnished to do so, subject to ;;;
;;; the following conditions: ;;;
1 . The code must retain the above copyright notice , this list of ; ; ;
;;; conditions and the following disclaimer. ;;;
2 . Any modifications must be clearly marked as such . ; ; ;
3 . Original authors ' names are not deleted . ; ; ;
4 . The authors ' names are not used to endorse or promote products ; ; ;
;;; derived from this software without specific prior written ;;;
;;; permission. ;;;
;;; ;;;
CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK ; ; ;
;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE ; ; ;
;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , IN ; ; ;
;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
;;; THIS SOFTWARE. ;;;
;;; ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Phonset for US English
;;; uses festival/lib/radio_phones.scm
;;;
(require 'radio_phones)
(define (cmu_us_slt::select_phoneset)
"(cmu_us_slt::select_phoneset)
Set up phone set for US English."
(Parameter.set 'PhoneSet 'radio)
(PhoneSet.select 'radio)
)
(define (cmu_us_slt::reset_phoneset)
"(cmu_us_slt::reset_phoneset)
Reset phone set for US English."
t
)
(provide 'cmu_us_slt_phoneset)
| null | https://raw.githubusercontent.com/alesaccoia/festival_flinger/87345aad3a3230751a8ff479f74ba1676217accd/lib/voices/us/cmu_us_slt_cg/festvox/cmu_us_slt_phoneset.scm | scheme |
;;;
; ;
; ;
; ;
; ;
;;;
Permission is hereby granted, free of charge, to use and distribute ;;;
this software and its documentation without restriction, including ;;;
without limitation the rights to use, copy, modify, merge, publish, ;;;
distribute, sublicense, and/or sell copies of this work, and to ;;;
permit persons to whom this work is furnished to do so, subject to ;;;
the following conditions: ;;;
; ;
conditions and the following disclaimer. ;;;
; ;
; ;
; ;
derived from this software without specific prior written ;;;
permission. ;;;
;;;
; ;
DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
; ;
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
; ;
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
THIS SOFTWARE. ;;;
;;;
uses festival/lib/radio_phones.scm
| Phonset for US English
(require 'radio_phones)
(define (cmu_us_slt::select_phoneset)
"(cmu_us_slt::select_phoneset)
Set up phone set for US English."
(Parameter.set 'PhoneSet 'radio)
(PhoneSet.select 'radio)
)
(define (cmu_us_slt::reset_phoneset)
"(cmu_us_slt::reset_phoneset)
Reset phone set for US English."
t
)
(provide 'cmu_us_slt_phoneset)
|
bd6bd4230c7e7754c86003543970739cdbe764f96c80c441eeb2cc41065342a6 | hakaru-dev/hakaru | Pretty.hs | # LANGUAGE OverloadedStrings
, , GADTs
, CPP
, RecordWildCards
#
, DataKinds
, GADTs
, CPP
, RecordWildCards
#-}
module Main where
import Language.Hakaru.Pretty.Concrete
import Language.Hakaru.Syntax.AST.Transforms
import Language.Hakaru.Syntax.Transform (Transform(..)
,someTransformations)
import Language.Hakaru.Syntax.IClasses (Some2(..))
import Language.Hakaru.Syntax.TypeCheck
import Language.Hakaru.Command
import qualified Data.Text as T
import qualified Data.Text.Utf8 as IO
import System.IO (stderr)
import Data.Monoid
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Applicative(..), (<$>), (<*>))
#endif
import qualified Options.Applicative as O
data Options = Options
{ printType :: Bool
, program :: FilePath
, toExpand :: [Some2 Transform]
}
options :: O.Parser Options
options = Options
<$> O.switch
( O.short 't' <>
O.long "print-type" <>
O.help "Annotate the program with its type." )
<*> O.strArgument
( O.metavar "PROGRAM" <>
O.help "Filename containing program to be pretty printed, or \"-\" to read from input." )
<*> O.option O.auto
( O.short 'e' <>
O.long "to-expand" <>
O.value [Some2 Expect, Some2 Observe] <>
O.help "Transformations to be expanded; default [Expect, Observe]" )
parseOpts :: IO Options
parseOpts = O.execParser $ O.info (O.helper <*> options)
(O.fullDesc <> O.progDesc "Parse, typecheck, and pretty print a Hakaru program")
main :: IO ()
main = parseOpts >>= runPretty
runPretty :: Options -> IO ()
runPretty Options{..} = readFromFile' program >>= parseAndInfer' >>= \prog ->
case prog of
Left err -> IO.hPutStrLn stderr err
Right (TypedAST typ ast) -> IO.putStrLn . T.pack $
let et = expandTransformationsWith'
(someTransformations toExpand haskellTransformations)
concreteProgram = show . pretty . et $ ast
withType t x = concat [ "(", x, ")"
, "\n.\n"
, show (prettyType 12 t)
] in
if printType then
withType typ concreteProgram
else concreteProgram
| null | https://raw.githubusercontent.com/hakaru-dev/hakaru/94157c89ea136c3b654a85cce51f19351245a490/commands/Pretty.hs | haskell | # LANGUAGE OverloadedStrings
, , GADTs
, CPP
, RecordWildCards
#
, DataKinds
, GADTs
, CPP
, RecordWildCards
#-}
module Main where
import Language.Hakaru.Pretty.Concrete
import Language.Hakaru.Syntax.AST.Transforms
import Language.Hakaru.Syntax.Transform (Transform(..)
,someTransformations)
import Language.Hakaru.Syntax.IClasses (Some2(..))
import Language.Hakaru.Syntax.TypeCheck
import Language.Hakaru.Command
import qualified Data.Text as T
import qualified Data.Text.Utf8 as IO
import System.IO (stderr)
import Data.Monoid
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Applicative(..), (<$>), (<*>))
#endif
import qualified Options.Applicative as O
data Options = Options
{ printType :: Bool
, program :: FilePath
, toExpand :: [Some2 Transform]
}
options :: O.Parser Options
options = Options
<$> O.switch
( O.short 't' <>
O.long "print-type" <>
O.help "Annotate the program with its type." )
<*> O.strArgument
( O.metavar "PROGRAM" <>
O.help "Filename containing program to be pretty printed, or \"-\" to read from input." )
<*> O.option O.auto
( O.short 'e' <>
O.long "to-expand" <>
O.value [Some2 Expect, Some2 Observe] <>
O.help "Transformations to be expanded; default [Expect, Observe]" )
parseOpts :: IO Options
parseOpts = O.execParser $ O.info (O.helper <*> options)
(O.fullDesc <> O.progDesc "Parse, typecheck, and pretty print a Hakaru program")
main :: IO ()
main = parseOpts >>= runPretty
runPretty :: Options -> IO ()
runPretty Options{..} = readFromFile' program >>= parseAndInfer' >>= \prog ->
case prog of
Left err -> IO.hPutStrLn stderr err
Right (TypedAST typ ast) -> IO.putStrLn . T.pack $
let et = expandTransformationsWith'
(someTransformations toExpand haskellTransformations)
concreteProgram = show . pretty . et $ ast
withType t x = concat [ "(", x, ")"
, "\n.\n"
, show (prettyType 12 t)
] in
if printType then
withType typ concreteProgram
else concreteProgram
| |
7596a41c7a6b215cb8faa291f143738a9f7c8b0b1f90c925ba66226e88ca134f | w3ntao/sicp-solution | 3-30.rkt | #lang racket
(require (combine-in (only-in "../ToolBox/IntegratedCircuit/wire.rkt"
make-wire
set-signal!
get-signal
add-action!)
(only-in "../ToolBox/IntegratedCircuit/gate.rkt"
full-adder)
(only-in "../ToolBox/AbstractionOfData/table.rkt"
make-table
insert!
lookup)
(only-in "../ToolBox/IntegratedCircuit/agenda.rkt"
make-agenda
current-time
first-agenda-item
empty-agenda?
remove-first-agenda-item!)))
; num stands for bit length
(define (ripple-carry-adder table-A table-B table-S num agenda)
(define (A n)
(lookup n table-A))
(define (B n)
(lookup n table-B))
(define (S n)
(lookup n table-S))
(define (ripple-carry-adder-unit n C-in)
(cond ((< n 0)
C-in)
(else
(let ((C-out (make-wire)))
(begin (full-adder (A n) (B n) C-in (S n) C-out agenda)
(ripple-carry-adder-unit (- n 1)
C-out))))))
(let ((C-0 (make-wire)))
(set-signal! C-0 0)
(ripple-carry-adder-unit (- num 1) C-0)))
(define (make-circuit n)
(let ((table (make-table)))
(define (make-circuit-iter num)
(begin
(insert! num (make-wire) table)
(when (> num 0)
(make-circuit-iter (- num 1)))))
(begin
(make-circuit-iter (- n 1))
table)))
; display n bits circuit
(define (display-circuit circuit n)
(define (display-circuit-unit num)
(display (get-signal (lookup num circuit)))
(display " ")
(when (< num (- n 1))
(display-circuit-unit (+ num 1))))
(display-circuit-unit 0))
(define (propagate agenda)
(if (empty-agenda? agenda)
'done
(let ((first-item (first-agenda-item agenda)))
(first-item)
(remove-first-agenda-item! agenda)
(propagate agenda))))
(define (probe name wire agenda)
(add-action! wire
(lambda ()
(newline)
(display name)
(display " ")
(display (current-time agenda))
(display " New-value = ")
(display (get-signal wire)))))
(define circuit-0 (make-circuit 2))
(display-circuit circuit-0 2)
(newline)
(define circuit-1 (make-circuit 2))
(display-circuit circuit-1 2)
(newline)
(define result (make-circuit 2))
(newline)
(define the-agenda (make-agenda))
(probe 'first-bit (lookup 0 result) the-agenda)
(probe 'second-bit (lookup 1 result) the-agenda)
(ripple-carry-adder circuit-0 circuit-1 result 2 the-agenda)
(set-signal! (lookup 0 circuit-0) 1)
(display-circuit circuit-0 2)
(newline)
(propagate the-agenda)
(set-signal! (lookup 1 circuit-0) 1)
(propagate the-agenda)
(newline)
(display-circuit result 1)
| null | https://raw.githubusercontent.com/w3ntao/sicp-solution/00be3a7b4da50bb266f8a2db521a24e9f8c156be/chap-3/3-30.rkt | racket | num stands for bit length
display n bits circuit | #lang racket
(require (combine-in (only-in "../ToolBox/IntegratedCircuit/wire.rkt"
make-wire
set-signal!
get-signal
add-action!)
(only-in "../ToolBox/IntegratedCircuit/gate.rkt"
full-adder)
(only-in "../ToolBox/AbstractionOfData/table.rkt"
make-table
insert!
lookup)
(only-in "../ToolBox/IntegratedCircuit/agenda.rkt"
make-agenda
current-time
first-agenda-item
empty-agenda?
remove-first-agenda-item!)))
(define (ripple-carry-adder table-A table-B table-S num agenda)
(define (A n)
(lookup n table-A))
(define (B n)
(lookup n table-B))
(define (S n)
(lookup n table-S))
(define (ripple-carry-adder-unit n C-in)
(cond ((< n 0)
C-in)
(else
(let ((C-out (make-wire)))
(begin (full-adder (A n) (B n) C-in (S n) C-out agenda)
(ripple-carry-adder-unit (- n 1)
C-out))))))
(let ((C-0 (make-wire)))
(set-signal! C-0 0)
(ripple-carry-adder-unit (- num 1) C-0)))
(define (make-circuit n)
(let ((table (make-table)))
(define (make-circuit-iter num)
(begin
(insert! num (make-wire) table)
(when (> num 0)
(make-circuit-iter (- num 1)))))
(begin
(make-circuit-iter (- n 1))
table)))
(define (display-circuit circuit n)
(define (display-circuit-unit num)
(display (get-signal (lookup num circuit)))
(display " ")
(when (< num (- n 1))
(display-circuit-unit (+ num 1))))
(display-circuit-unit 0))
(define (propagate agenda)
(if (empty-agenda? agenda)
'done
(let ((first-item (first-agenda-item agenda)))
(first-item)
(remove-first-agenda-item! agenda)
(propagate agenda))))
(define (probe name wire agenda)
(add-action! wire
(lambda ()
(newline)
(display name)
(display " ")
(display (current-time agenda))
(display " New-value = ")
(display (get-signal wire)))))
(define circuit-0 (make-circuit 2))
(display-circuit circuit-0 2)
(newline)
(define circuit-1 (make-circuit 2))
(display-circuit circuit-1 2)
(newline)
(define result (make-circuit 2))
(newline)
(define the-agenda (make-agenda))
(probe 'first-bit (lookup 0 result) the-agenda)
(probe 'second-bit (lookup 1 result) the-agenda)
(ripple-carry-adder circuit-0 circuit-1 result 2 the-agenda)
(set-signal! (lookup 0 circuit-0) 1)
(display-circuit circuit-0 2)
(newline)
(propagate the-agenda)
(set-signal! (lookup 1 circuit-0) 1)
(propagate the-agenda)
(newline)
(display-circuit result 1)
|
a45a179bbf62f9cff5cff9c50729fd8339f5eac7a505d85b10da823045bd6d41 | Toxaris/pts | Properties.hs | module PTS.Syntax.Substitution.Properties where
import Data.Set
import Test.Property
import PTS.Syntax
import PTS.Syntax.Arbitrary
substAvoidsCapture t x t' =
x `member` freevars t ==>
delete x (freevars t) `union` freevars t' == freevars (subst t x t')
| null | https://raw.githubusercontent.com/Toxaris/pts/1700024f47bc9d28528b68fc815d2421f5d25b84/src-test/PTS/Syntax/Substitution/Properties.hs | haskell | module PTS.Syntax.Substitution.Properties where
import Data.Set
import Test.Property
import PTS.Syntax
import PTS.Syntax.Arbitrary
substAvoidsCapture t x t' =
x `member` freevars t ==>
delete x (freevars t) `union` freevars t' == freevars (subst t x t')
| |
2dd73336212f8c7c0a927b25ceeb2b622c14f8ef519074c20f61fcd98995c796 | may-liu/qtalk | http_create_muc.erl | %% Feel free to use, reuse and abuse the code in this file.
-module(http_create_muc).
-export([init/3]).
-export([handle/2]).
-export([terminate/3]).
-export([create_muc/1]).
-include("ejabberd.hrl").
-include("logger.hrl").
-include("http_req.hrl").
-include("jlib.hrl").
init(_Transport, Req, []) ->
{ok, Req, undefined}.
handle(Req, State) ->
{Method, _ } = cowboy_req:method(Req),
case Method of
<<"GET">> ->
{ok, Req1} = echo(<<"No Get Method!">>,Req),
{ok, Req1, State};
<<"POST">> ->
HasBody = cowboy_req:has_body(Req),
{ok, Req2} = post_echo(Method, HasBody, Req),
{ok, Req2, State};
_ ->
{ok,Req3} = echo(undefined, Req),
{ok, Req3, State}
end.
post_echo(<<"POST">>,true,Req) ->
{ok, PBody, _} = cowboy_req:body(Req),
Header = cowboy_req:get(headers,Req),
Body =
case catch proplists:get_value(<<"content-encoding">>,Header) of
<<"gzip">> ->
zlib:gunzip(PBody);
_ ->
PBody
end,
Req1 = Req#http_req{resp_compress = true},
case rfc4627:decode(Body) of
{ok,{obj,Args},[]} ->
Res = create_muc(Args),
cowboy_req:reply(200, [{<<"content-type">>, <<"text/json; charset=utf-8">>}], Res, Req1);
_ ->
cowboy_req:reply(200, [{<<"content-type">>, <<"text/json; charset=utf-8">>}],
http_utils:gen_result(false, <<"-1">>,<<"Json format error.">>,<<"">>), Req)
end;
post_echo(<<"POST">>, false, Req) ->
cowboy_req:reply(400, [], http_utils:gen_result(false, <<"-1">>,<<"Missing Post body.">>,<<"">>), Req);
post_echo(_, _, Req) ->
cowboy_req:reply(405, Req).
echo(undefined, Req) ->
cowboy_req:reply(400, [], http_utils:gen_result(false, <<"-1">>,<<"Missing Post body.">>,<<"">>), Req);
echo(Echo, Req) ->
cowboy_req:reply(200, [
{<<"content-type">>, <<"text/plain; charset=utf-8">>}
], http_utils:gen_result(true, <<"0">>,Echo,<<"">>), Req).
terminate(_Reason, _Req, _State) ->
ok.
create_muc(Args) ->
Servers = ejabberd_config:get_myhosts(),
LServer = lists:nth(1,Servers),
create_muc(LServer,Args).
create_muc(Server,Args) ->
Muc_name = http_muc_session:get_value("muc_name",Args,<<"">>),
Muc_id = http_muc_session:get_value("muc_id",Args,<<"">>),
Muc_owner = http_muc_session:get_value("muc_owner",Args,<<"">>),
Domain = http_muc_session:get_value("muc_domain",Args,<<"">>),
Desc = http_muc_session:get_value("muc_desc",Args,<<"">>),
case http_muc_session:check_muc_exist(Server,Muc_id) of
false ->
% Packet = http_muc_session:make_muc_presence(),
Packet = http_muc_session:make_create_muc_iq(),
case jlib:make_jid(Muc_id,Domain,<<"">>) of
error ->
http_utils:gen_result(false, <<"-1">>,<<"">>,<<"error">>);
To_owner ->
% Resources =
% case ejabberd_sm:get_user_resources(Muc_owner, Server) of
% [] ->
% [<<"">>];
% Rs ->
% Rs
% end,
% R = lists:nth(1,Resources),
Owner = jlib:make_jid(Muc_owner,Server,<<"">>),
catch ejabberd_router:route(Owner,To_owner, Packet),
catch http_muc_session : update_user_presence_a(Server , , Muc_id , Domain ) ,
% IQ_Packet = http_muc_session:make_invite_iq(U),
catch ejabberd_router : route(Invite_Jid , Muc_jid , IQ_Packet )
catch odbc_queries:insert_muc_vcard_info(Server,str:concat(Muc_id,str:concat(<<"@">>,Domain)),Muc_name,Desc,<<"">>,<<"">>,<<"1">>),
% http_muc_session:update_pg_muc_register(Server,Muc_id,[Muc_owner]),
Persistent_packet = http_muc_session:make_muc_persistent(),
catch ejabberd_router:route(jlib:make_jid(Muc_owner,Server,<<"">>),jlib:jid_replace_resource(To_owner,<<"">>), Persistent_packet)
case Resources of
% [<<"">>] ->
catch http_muc_session : delete_unavailable_user(Server , Muc_id , Domain , ) ;
% _ ->
% ok
% end
end,
http_utils:gen_result(true, <<"0">>,<<"">>,<<"sucess">>);
_ ->
http_utils:gen_result(true, <<"3">>,<<"">>,<<"failed">>)
end.
| null | https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/src/http_create_muc.erl | erlang | Feel free to use, reuse and abuse the code in this file.
Packet = http_muc_session:make_muc_presence(),
Resources =
case ejabberd_sm:get_user_resources(Muc_owner, Server) of
[] ->
[<<"">>];
Rs ->
Rs
end,
R = lists:nth(1,Resources),
IQ_Packet = http_muc_session:make_invite_iq(U),
http_muc_session:update_pg_muc_register(Server,Muc_id,[Muc_owner]),
[<<"">>] ->
_ ->
ok
end | -module(http_create_muc).
-export([init/3]).
-export([handle/2]).
-export([terminate/3]).
-export([create_muc/1]).
-include("ejabberd.hrl").
-include("logger.hrl").
-include("http_req.hrl").
-include("jlib.hrl").
init(_Transport, Req, []) ->
{ok, Req, undefined}.
handle(Req, State) ->
{Method, _ } = cowboy_req:method(Req),
case Method of
<<"GET">> ->
{ok, Req1} = echo(<<"No Get Method!">>,Req),
{ok, Req1, State};
<<"POST">> ->
HasBody = cowboy_req:has_body(Req),
{ok, Req2} = post_echo(Method, HasBody, Req),
{ok, Req2, State};
_ ->
{ok,Req3} = echo(undefined, Req),
{ok, Req3, State}
end.
post_echo(<<"POST">>,true,Req) ->
{ok, PBody, _} = cowboy_req:body(Req),
Header = cowboy_req:get(headers,Req),
Body =
case catch proplists:get_value(<<"content-encoding">>,Header) of
<<"gzip">> ->
zlib:gunzip(PBody);
_ ->
PBody
end,
Req1 = Req#http_req{resp_compress = true},
case rfc4627:decode(Body) of
{ok,{obj,Args},[]} ->
Res = create_muc(Args),
cowboy_req:reply(200, [{<<"content-type">>, <<"text/json; charset=utf-8">>}], Res, Req1);
_ ->
cowboy_req:reply(200, [{<<"content-type">>, <<"text/json; charset=utf-8">>}],
http_utils:gen_result(false, <<"-1">>,<<"Json format error.">>,<<"">>), Req)
end;
post_echo(<<"POST">>, false, Req) ->
cowboy_req:reply(400, [], http_utils:gen_result(false, <<"-1">>,<<"Missing Post body.">>,<<"">>), Req);
post_echo(_, _, Req) ->
cowboy_req:reply(405, Req).
echo(undefined, Req) ->
cowboy_req:reply(400, [], http_utils:gen_result(false, <<"-1">>,<<"Missing Post body.">>,<<"">>), Req);
echo(Echo, Req) ->
cowboy_req:reply(200, [
{<<"content-type">>, <<"text/plain; charset=utf-8">>}
], http_utils:gen_result(true, <<"0">>,Echo,<<"">>), Req).
terminate(_Reason, _Req, _State) ->
ok.
create_muc(Args) ->
Servers = ejabberd_config:get_myhosts(),
LServer = lists:nth(1,Servers),
create_muc(LServer,Args).
create_muc(Server,Args) ->
Muc_name = http_muc_session:get_value("muc_name",Args,<<"">>),
Muc_id = http_muc_session:get_value("muc_id",Args,<<"">>),
Muc_owner = http_muc_session:get_value("muc_owner",Args,<<"">>),
Domain = http_muc_session:get_value("muc_domain",Args,<<"">>),
Desc = http_muc_session:get_value("muc_desc",Args,<<"">>),
case http_muc_session:check_muc_exist(Server,Muc_id) of
false ->
Packet = http_muc_session:make_create_muc_iq(),
case jlib:make_jid(Muc_id,Domain,<<"">>) of
error ->
http_utils:gen_result(false, <<"-1">>,<<"">>,<<"error">>);
To_owner ->
Owner = jlib:make_jid(Muc_owner,Server,<<"">>),
catch ejabberd_router:route(Owner,To_owner, Packet),
catch http_muc_session : update_user_presence_a(Server , , Muc_id , Domain ) ,
catch ejabberd_router : route(Invite_Jid , Muc_jid , IQ_Packet )
catch odbc_queries:insert_muc_vcard_info(Server,str:concat(Muc_id,str:concat(<<"@">>,Domain)),Muc_name,Desc,<<"">>,<<"">>,<<"1">>),
Persistent_packet = http_muc_session:make_muc_persistent(),
catch ejabberd_router:route(jlib:make_jid(Muc_owner,Server,<<"">>),jlib:jid_replace_resource(To_owner,<<"">>), Persistent_packet)
case Resources of
catch http_muc_session : delete_unavailable_user(Server , Muc_id , Domain , ) ;
end,
http_utils:gen_result(true, <<"0">>,<<"">>,<<"sucess">>);
_ ->
http_utils:gen_result(true, <<"3">>,<<"">>,<<"failed">>)
end.
|
aa6446b03d6538f916a16c0d2c26cd3b2d198d9e8f4eb4b3506b6bf75f036d79 | haskell-suite/haskell-names | Infix.hs | module Infix where
infixr 3 $$$
($$$) x y = x y
| null | https://raw.githubusercontent.com/haskell-suite/haskell-names/795d717541484dbe456342a510ac8e712e1f16e4/tests/annotations/Infix.hs | haskell | module Infix where
infixr 3 $$$
($$$) x y = x y
| |
02771076d8a13aa7cd29136b68f80e89e0db624c28f613584c862f252254bdb9 | zcaudate/hara | diff_test.clj | (ns hara.data.base.seq.diff-test
(:use hara.test)
(:require [hara.data.base.seq.diff :refer :all]))
^{:refer hara.data.base.seq.diff/diff :added "3.0"}
(fact "creates a diff of two sequences"
(diff [1 2 3 4 5]
[1 2 :a 4 5])
=> [2 [[:- 2 1] [:+ 2 [:a]]]]
(diff [1 2 3 4 5]
[1 :a 3 2 5])
=> [4 [[:- 1 1]
[:+ 1 [:a]]
[:- 3 1]
[:+ 3 [2]]]])
^{:refer hara.data.base.seq.diff/patch :added "3.0"}
(fact "uses a diff to reconcile two sequences"
(patch [1 2 3 4 5]
[4 [[:- 1 1]
[:+ 1 [:a]]
[:- 3 1]
[:+ 3 [2]]]])
=> [1 :a 3 2 5])
| null | https://raw.githubusercontent.com/zcaudate/hara/481316c1f5c2aeba5be6e01ae673dffc46a63ec9/test/hara/data/base/seq/diff_test.clj | clojure | (ns hara.data.base.seq.diff-test
(:use hara.test)
(:require [hara.data.base.seq.diff :refer :all]))
^{:refer hara.data.base.seq.diff/diff :added "3.0"}
(fact "creates a diff of two sequences"
(diff [1 2 3 4 5]
[1 2 :a 4 5])
=> [2 [[:- 2 1] [:+ 2 [:a]]]]
(diff [1 2 3 4 5]
[1 :a 3 2 5])
=> [4 [[:- 1 1]
[:+ 1 [:a]]
[:- 3 1]
[:+ 3 [2]]]])
^{:refer hara.data.base.seq.diff/patch :added "3.0"}
(fact "uses a diff to reconcile two sequences"
(patch [1 2 3 4 5]
[4 [[:- 1 1]
[:+ 1 [:a]]
[:- 3 1]
[:+ 3 [2]]]])
=> [1 :a 3 2 5])
| |
2df8e53a7faa02d65f457e0f017eb3fa7447d26a1602aa1ea37f187c32fae693 | luminus-framework/guestbook | layout.clj | (ns guestbook.layout
(:require [selmer.parser :as parser]
[selmer.filters :as filters]
[markdown.core :refer [md-to-html-string]]
[ring.util.http-response :refer [content-type ok]]
[ring.util.anti-forgery :refer [anti-forgery-field]]
[ring.middleware.anti-forgery :refer [*anti-forgery-token*]]))
(declare ^:dynamic *app-context*)
(parser/set-resource-path! (clojure.java.io/resource "templates"))
(parser/add-tag! :csrf-field (fn [_ _] (anti-forgery-field)))
(filters/add-filter! :markdown (fn [content] [:safe (md-to-html-string content)]))
(defn render
"renders the HTML template located relative to resources/templates"
[template & [params]]
(content-type
(ok
(parser/render-file
template
(assoc params
:page template
:csrf-token *anti-forgery-token*
:servlet-context *app-context*)))
"text/html; charset=utf-8"))
(defn error-page
"error-details should be a map containing the following keys:
:status - error status
:title - error title (optional)
:message - detailed error message (optional)
returns a response map with the error page as the body
and the status specified by the status key"
[error-details]
{:status (:status error-details)
:headers {"Content-Type" "text/html; charset=utf-8"}
:body (parser/render-file "error.html" error-details)})
| null | https://raw.githubusercontent.com/luminus-framework/guestbook/c0e4c05cd6b1a59602c7699266d11f56adbec197/src/clj/guestbook/layout.clj | clojure | (ns guestbook.layout
(:require [selmer.parser :as parser]
[selmer.filters :as filters]
[markdown.core :refer [md-to-html-string]]
[ring.util.http-response :refer [content-type ok]]
[ring.util.anti-forgery :refer [anti-forgery-field]]
[ring.middleware.anti-forgery :refer [*anti-forgery-token*]]))
(declare ^:dynamic *app-context*)
(parser/set-resource-path! (clojure.java.io/resource "templates"))
(parser/add-tag! :csrf-field (fn [_ _] (anti-forgery-field)))
(filters/add-filter! :markdown (fn [content] [:safe (md-to-html-string content)]))
(defn render
"renders the HTML template located relative to resources/templates"
[template & [params]]
(content-type
(ok
(parser/render-file
template
(assoc params
:page template
:csrf-token *anti-forgery-token*
:servlet-context *app-context*)))
"text/html; charset=utf-8"))
(defn error-page
"error-details should be a map containing the following keys:
:status - error status
:title - error title (optional)
:message - detailed error message (optional)
returns a response map with the error page as the body
and the status specified by the status key"
[error-details]
{:status (:status error-details)
:headers {"Content-Type" "text/html; charset=utf-8"}
:body (parser/render-file "error.html" error-details)})
| |
bb652d4c0892210bc50494ea4c588bbfa2df2b8dccd42dd1189edd185b97aa7f | blajzer/dib | Copy.hs | Copyright ( c ) 2010 - 2018
-- See LICENSE for license information.
| A trivial builder that copies a directory tree from one location to another .
module Dib.Builders.Copy (
makeCopyTarget
) where
import Dib.Gatherers
import Dib.Types
import qualified Data.Text as T
import qualified System.Console.ANSI as ANSI
import qualified System.Directory as D
import System.FilePath as P
copyFunc :: SrcTransform -> IO StageResult
copyFunc (OneToOne source target) = do
let unpackedTarget = T.unpack target
let unpackedSource = T.unpack source
D.createDirectoryIfMissing True $ takeDirectory unpackedTarget
ANSI.setSGR [ANSI.SetColor ANSI.Foreground ANSI.Vivid ANSI.White]
putStr "Copying: "
ANSI.setSGR [ANSI.Reset]
putStrLn $ unpackedSource ++ " -> " ++ unpackedTarget
D.copyFile unpackedSource unpackedTarget
return $ Right (OneToOne target "")
copyFunc _ = return $ Left "Unexpected SrcTransform"
remapFile :: String -> String -> SrcTransform -> SrcTransform
remapFile src dest (OneToOne source _) = OneToOne source $ T.pack $ dest </> makeRelative src (T.unpack source)
remapFile _ _ _ = error "Unhandled SrcTransform"
-- | The 'makeCopyTarget' function makes a target that copies a directory tree.
-- It takes a name, a source directory, destination directory, and gather filter.
makeCopyTarget :: T.Text -> T.Text -> T.Text -> FilterFunc -> [T.Text] -> Target
makeCopyTarget name src dest filterFunc extraDeps =
let stage = Stage "copy" (map $ remapFile (T.unpack src) (T.unpack dest)) return extraDeps copyFunc
in Target name (const 0) [] [stage] [makeFileTreeGatherer src filterFunc]
| null | https://raw.githubusercontent.com/blajzer/dib/750253c972668bb0d849239f94b96050bae74f2a/src/Dib/Builders/Copy.hs | haskell | See LICENSE for license information.
| The 'makeCopyTarget' function makes a target that copies a directory tree.
It takes a name, a source directory, destination directory, and gather filter. | Copyright ( c ) 2010 - 2018
| A trivial builder that copies a directory tree from one location to another .
module Dib.Builders.Copy (
makeCopyTarget
) where
import Dib.Gatherers
import Dib.Types
import qualified Data.Text as T
import qualified System.Console.ANSI as ANSI
import qualified System.Directory as D
import System.FilePath as P
copyFunc :: SrcTransform -> IO StageResult
copyFunc (OneToOne source target) = do
let unpackedTarget = T.unpack target
let unpackedSource = T.unpack source
D.createDirectoryIfMissing True $ takeDirectory unpackedTarget
ANSI.setSGR [ANSI.SetColor ANSI.Foreground ANSI.Vivid ANSI.White]
putStr "Copying: "
ANSI.setSGR [ANSI.Reset]
putStrLn $ unpackedSource ++ " -> " ++ unpackedTarget
D.copyFile unpackedSource unpackedTarget
return $ Right (OneToOne target "")
copyFunc _ = return $ Left "Unexpected SrcTransform"
remapFile :: String -> String -> SrcTransform -> SrcTransform
remapFile src dest (OneToOne source _) = OneToOne source $ T.pack $ dest </> makeRelative src (T.unpack source)
remapFile _ _ _ = error "Unhandled SrcTransform"
makeCopyTarget :: T.Text -> T.Text -> T.Text -> FilterFunc -> [T.Text] -> Target
makeCopyTarget name src dest filterFunc extraDeps =
let stage = Stage "copy" (map $ remapFile (T.unpack src) (T.unpack dest)) return extraDeps copyFunc
in Target name (const 0) [] [stage] [makeFileTreeGatherer src filterFunc]
|
c6cf9848e3a5959542de8eabc6e4157dd9777c929837320f17aea5b34c1f6ddf | lispnik/iup | teapot.lisp | (in-package #:iup-examples.teapot)
(defun teapot ()
(iup:with-iup ()
(iup-gl:open)
(let* ((canvas (iup-gl:canvas))
(dialog (iup:dialog
canvas
:title "IupGLCanvas"
:rastersize "800x600"
:margin "5x5"
:gap "5")))
(iup-gl:make-current canvas)
(gl:load-identity)
(gl:translate 0 0 -5)
(gl:rotate 30 1 1 0)
(gl:light :light0 :position '(0 1 1 0))
(gl:light :light0 :diffuse '(0.2 0.4 0.6 0))
(gl:clear :color-buffer :depth-buffer)
(gl:color 1 1 1)
(gl:front-face :cw)
(glut:init)
(glut:solid-teapot 1.3)
(gl:front-face :ccw)
(gl:flush)
(iup-gl:swap-buffers canvas)
(iup:show dialog)
(iup:main-loop))))
#+nil
(sb-int:with-float-traps-masked
(:divide-by-zero :invalid)
(teapot))
| null | https://raw.githubusercontent.com/lispnik/iup/f8e5f090bae47bf8f91ac6fed41ec3bc01061186/examples/incomplete/teapot.lisp | lisp | (in-package #:iup-examples.teapot)
(defun teapot ()
(iup:with-iup ()
(iup-gl:open)
(let* ((canvas (iup-gl:canvas))
(dialog (iup:dialog
canvas
:title "IupGLCanvas"
:rastersize "800x600"
:margin "5x5"
:gap "5")))
(iup-gl:make-current canvas)
(gl:load-identity)
(gl:translate 0 0 -5)
(gl:rotate 30 1 1 0)
(gl:light :light0 :position '(0 1 1 0))
(gl:light :light0 :diffuse '(0.2 0.4 0.6 0))
(gl:clear :color-buffer :depth-buffer)
(gl:color 1 1 1)
(gl:front-face :cw)
(glut:init)
(glut:solid-teapot 1.3)
(gl:front-face :ccw)
(gl:flush)
(iup-gl:swap-buffers canvas)
(iup:show dialog)
(iup:main-loop))))
#+nil
(sb-int:with-float-traps-masked
(:divide-by-zero :invalid)
(teapot))
| |
35f817fe22ada5e07d34ff8e8474d52752ad62e200b2c5043dd1fba31ca7c536 | jepsen-io/knossos | core.clj | (ns knossos.core
(:require [knossos.op :as op]
[knossos.competition :as competition]))
; For backwards compatibility
(def op op/op)
(def invoke-op op/invoke)
(def ok-op op/ok)
(def fail-op op/fail)
(def invoke? op/invoke?)
(def ok? op/ok?)
(def fail? op/fail?)
(defn analysis
"Alias for competition/analysis"
([model history]
(analysis model history {}))
([model history opts]
(competition/analysis model history opts)))
| null | https://raw.githubusercontent.com/jepsen-io/knossos/1cb706f979c1712add47f0519d9e1dcb85635635/src/knossos/core.clj | clojure | For backwards compatibility | (ns knossos.core
(:require [knossos.op :as op]
[knossos.competition :as competition]))
(def op op/op)
(def invoke-op op/invoke)
(def ok-op op/ok)
(def fail-op op/fail)
(def invoke? op/invoke?)
(def ok? op/ok?)
(def fail? op/fail?)
(defn analysis
"Alias for competition/analysis"
([model history]
(analysis model history {}))
([model history opts]
(competition/analysis model history opts)))
|
e25cc82013917e4338c1c87151eb7adc5be324d1cf95525c6e0b94a8b6addaef | emqx/mria | mria_rlog_tests.erl | -module(mria_rlog_tests).
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
shuffle_test() ->
?FORALL(L, list(),
?assertEqual(lists:sort(L), list:sort(mria_lib:shuffle(L)))).
| null | https://raw.githubusercontent.com/emqx/mria/de47b8177306c42d89d6a1cd89192cee72a50bfd/test/mria_rlog_tests.erl | erlang | -module(mria_rlog_tests).
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
shuffle_test() ->
?FORALL(L, list(),
?assertEqual(lists:sort(L), list:sort(mria_lib:shuffle(L)))).
| |
91698a33c7c025bbf7aba79991321d4fd854479345954f3918e96daaf8521d93 | rd--/hsc3 | s_get.help.hs | Sound.Sc3.Lang.Help.viewServerHelp "/s_get"
| null | https://raw.githubusercontent.com/rd--/hsc3/024d45b6b5166e5cd3f0142fbf65aeb6ef642d46/Help/Server/s_get.help.hs | haskell | Sound.Sc3.Lang.Help.viewServerHelp "/s_get"
| |
5481d2ae2f4b721df5bc54dd99c07e20f578ab046e85c5046e08352c2ee66ea6 | ghcjs/ghcjs | Main.hs |
From : < >
To : partain
Subject : A puzzle for you
Date : Mon , 28 Oct 91 17:02:19 GMT
I 'm struggling with the following code fragment at the moment :
From: Paul Sanders <>
To: partain
Subject: A puzzle for you
Date: Mon, 28 Oct 91 17:02:19 GMT
I'm struggling with the following code fragment at the moment:
-}
1.3
1.3
conv_list :: (Ix a, Ix b) => [a] -> [b] -> [[c]] -> Array (a,b) c -> Array (a,b) c
conv_list [] _ _ ar = ar
conv_list _ _ [] ar = ar
conv_list (r:rs) cls (rt:rts) ar
= conv_list rs cls rts ar'
where ar' = conv_elems r cls rt ar
conv_elems :: (Ix a, Ix b) => a -> [b] -> [c] -> Array (a,b) c -> Array (a,b) c
conv_elems row [] _ ar = ar
conv_elems _ _ [] ar = ar
conv_elems row (col:cls) (rt:rts) ar
= conv_elems row cls rts ar'
where ar' = ar // [((row,col), rt)]
ar :: Array (Int, Int) Int
ar = conv_list [(1::Int)..(3::Int)] [(1::Int)..(3::Int)] ar_list init_ar
where init_ar = array (((1::Int),(1::Int)),((3::Int),(3::Int))) []
WDP
ar_list = [[1,2,3],
[6,7,8],
[10,12,15]]
main = putStrLn (show ar)
What it tries to do is turn a list of lists into a 2 - d array in an incremental
fashion using 2 nested for - loops . It compiles okay on the prototype compiler
but gives a segmentation fault when it executes . I know I can define in the
array in one go ( and I have done ) but , for my piece of mind , I want to get this
way working properly .
Is it a bug in the prototype or is there a glaringly obvious error in my code
which I 've been stupid to spot ? ? ? ?
Hoping its the latter ,
.
What it tries to do is turn a list of lists into a 2-d array in an incremental
fashion using 2 nested for-loops. It compiles okay on the prototype compiler
but gives a segmentation fault when it executes. I know I can define in the
array in one go (and I have done) but, for my piece of mind, I want to get this
way working properly.
Is it a bug in the prototype or is there a glaringly obvious error in my code
which I've been stupid to spot ????
Hoping its the latter,
Paul.
-}
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/programs/sanders_array/Main.hs | haskell |
From : < >
To : partain
Subject : A puzzle for you
Date : Mon , 28 Oct 91 17:02:19 GMT
I 'm struggling with the following code fragment at the moment :
From: Paul Sanders <>
To: partain
Subject: A puzzle for you
Date: Mon, 28 Oct 91 17:02:19 GMT
I'm struggling with the following code fragment at the moment:
-}
1.3
1.3
conv_list :: (Ix a, Ix b) => [a] -> [b] -> [[c]] -> Array (a,b) c -> Array (a,b) c
conv_list [] _ _ ar = ar
conv_list _ _ [] ar = ar
conv_list (r:rs) cls (rt:rts) ar
= conv_list rs cls rts ar'
where ar' = conv_elems r cls rt ar
conv_elems :: (Ix a, Ix b) => a -> [b] -> [c] -> Array (a,b) c -> Array (a,b) c
conv_elems row [] _ ar = ar
conv_elems _ _ [] ar = ar
conv_elems row (col:cls) (rt:rts) ar
= conv_elems row cls rts ar'
where ar' = ar // [((row,col), rt)]
ar :: Array (Int, Int) Int
ar = conv_list [(1::Int)..(3::Int)] [(1::Int)..(3::Int)] ar_list init_ar
where init_ar = array (((1::Int),(1::Int)),((3::Int),(3::Int))) []
WDP
ar_list = [[1,2,3],
[6,7,8],
[10,12,15]]
main = putStrLn (show ar)
What it tries to do is turn a list of lists into a 2 - d array in an incremental
fashion using 2 nested for - loops . It compiles okay on the prototype compiler
but gives a segmentation fault when it executes . I know I can define in the
array in one go ( and I have done ) but , for my piece of mind , I want to get this
way working properly .
Is it a bug in the prototype or is there a glaringly obvious error in my code
which I 've been stupid to spot ? ? ? ?
Hoping its the latter ,
.
What it tries to do is turn a list of lists into a 2-d array in an incremental
fashion using 2 nested for-loops. It compiles okay on the prototype compiler
but gives a segmentation fault when it executes. I know I can define in the
array in one go (and I have done) but, for my piece of mind, I want to get this
way working properly.
Is it a bug in the prototype or is there a glaringly obvious error in my code
which I've been stupid to spot ????
Hoping its the latter,
Paul.
-}
| |
257915a98904631e8a9a3615a6c7e57e83c036c2bae13f0326b87a8cb2919690 | Eduap-com/WordMat | dprepji.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " )
;;; Using Lisp CMU Common Lisp snapshot-2013-11 (20E Unicode)
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format single-float))
(in-package "ODEPACK")
(defun dprepji (neq y yh nyh ewt rtem savr s wm iwm res jac adda)
(declare (type (f2cl-lib:integer4) nyh)
(type (array double-float (*)) wm s savr rtem ewt yh y)
(type (array f2cl-lib:integer4 (*)) iwm neq))
(let ()
(symbol-macrolet ((el0 (aref (dls001-part-0 *dls001-common-block*) 210))
(h (aref (dls001-part-0 *dls001-common-block*) 211))
(tn (aref (dls001-part-0 *dls001-common-block*) 216))
(ierpj (aref (dls001-part-1 *dls001-common-block*) 13))
(jcur (aref (dls001-part-1 *dls001-common-block*) 15))
(miter (aref (dls001-part-1 *dls001-common-block*) 26))
(n (aref (dls001-part-1 *dls001-common-block*) 31))
(nfe (aref (dls001-part-1 *dls001-common-block*) 34))
(nje (aref (dls001-part-1 *dls001-common-block*) 35)))
(f2cl-lib:with-multi-array-data
((neq f2cl-lib:integer4 neq-%data% neq-%offset%)
(iwm f2cl-lib:integer4 iwm-%data% iwm-%offset%)
(y double-float y-%data% y-%offset%)
(yh double-float yh-%data% yh-%offset%)
(ewt double-float ewt-%data% ewt-%offset%)
(rtem double-float rtem-%data% rtem-%offset%)
(savr double-float savr-%data% savr-%offset%)
(s double-float s-%data% s-%offset%)
(wm double-float wm-%data% wm-%offset%))
(prog ((mu 0) (ml3 0) (ml 0) (meband 0) (meb1 0) (mband 0) (mba 0)
(lenp 0) (jj 0) (j1 0) (j 0) (ires 0) (ii 0) (ier 0) (i2 0)
(i1 0) (i 0) (yjj 0.0d0) (yj 0.0d0) (yi 0.0d0) (srur 0.0d0)
(r 0.0d0) (hl0 0.0d0) (fac 0.0d0) (con 0.0d0))
(declare (type (double-float) con fac hl0 r srur yi yj yjj)
(type (f2cl-lib:integer4) i i1 i2 ier ii ires j j1 jj lenp
mba mband meb1 meband ml ml3 mu))
(setf nje (f2cl-lib:int-add nje 1))
(setf hl0 (* h el0))
(setf ierpj 0)
(setf jcur 1)
(f2cl-lib:computed-goto
(label100 label200 label300 label400 label500)
miter)
label100
(setf ires 1)
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s savr ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
(setf lenp (f2cl-lib:int-mul n n))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i lenp) nil)
(tagbody
label110
(setf (f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i 2))
((1 *))
wm-%offset%)
0.0d0)))
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7)
(funcall jac
neq
tn
y
s
0
0
(f2cl-lib:array-slice wm-%data%
double-float
(3)
((1 *))
wm-%offset%)
n)
(declare (ignore var-0 var-2 var-3 var-4 var-5 var-6))
(when var-1
(setf tn var-1))
(when var-7
(setf n var-7)))
(setf con (- hl0))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i lenp) nil)
(tagbody
label120
(setf (f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i 2))
((1 *))
wm-%offset%)
(*
(f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i 2))
((1 *))
wm-%offset%)
con))))
(go label240)
label200
(setf ires -1)
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s savr ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
(setf srur (f2cl-lib:fref wm-%data% (1) ((1 *)) wm-%offset%))
(setf j1 2)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf yj (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%))
(setf r
(max (* srur (abs yj))
(/ 0.01d0
(f2cl-lib:fref ewt-%data%
(j)
((1 *))
ewt-%offset%))))
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%) r))
(setf fac (/ (- hl0) r))
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s rtem ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label220
(setf (f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i j1))
((1 *))
wm-%offset%)
(*
(-
(f2cl-lib:fref rtem-%data%
(i)
((1 *))
rtem-%offset%)
(f2cl-lib:fref savr-%data%
(i)
((1 *))
savr-%offset%))
fac))))
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%) yj)
(setf j1 (f2cl-lib:int-add j1 n))
label230))
(setf ires 1)
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s savr ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
label240
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 var-6)
(funcall adda
neq
tn
y
0
0
(f2cl-lib:array-slice wm-%data%
double-float
(3)
((1 *))
wm-%offset%)
n)
(declare (ignore var-0 var-2 var-3 var-4 var-5))
(when var-1
(setf tn var-1))
(when var-6
(setf n var-6)))
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4)
(dgefa
(f2cl-lib:array-slice wm-%data%
double-float
(3)
((1 *))
wm-%offset%)
n n
(f2cl-lib:array-slice iwm-%data%
f2cl-lib:integer4
(21)
((1 *))
iwm-%offset%)
ier)
(declare (ignore var-0 var-1 var-2 var-3))
(setf ier var-4))
(if (/= ier 0) (setf ierpj 1))
(go end_label)
label300
(go end_label)
label400
(setf ires 1)
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s savr ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
(setf ml (f2cl-lib:fref iwm-%data% (1) ((1 *)) iwm-%offset%))
(setf mu (f2cl-lib:fref iwm-%data% (2) ((1 *)) iwm-%offset%))
(setf ml3 (f2cl-lib:int-add ml 3))
(setf mband (f2cl-lib:int-add ml mu 1))
(setf meband (f2cl-lib:int-add mband ml))
(setf lenp (f2cl-lib:int-mul meband n))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i lenp) nil)
(tagbody
label410
(setf (f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i 2))
((1 *))
wm-%offset%)
0.0d0)))
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7)
(funcall jac
neq
tn
y
s
ml
mu
(f2cl-lib:array-slice wm-%data%
double-float
(ml3)
((1 *))
wm-%offset%)
meband)
(declare (ignore var-0 var-2 var-3 var-6))
(when var-1
(setf tn var-1))
(when var-4
(setf ml var-4))
(when var-5
(setf mu var-5))
(when var-7
(setf meband var-7)))
(setf con (- hl0))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i lenp) nil)
(tagbody
label420
(setf (f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i 2))
((1 *))
wm-%offset%)
(*
(f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i 2))
((1 *))
wm-%offset%)
con))))
(go label570)
label500
(setf ires -1)
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s savr ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
(setf ml (f2cl-lib:fref iwm-%data% (1) ((1 *)) iwm-%offset%))
(setf mu (f2cl-lib:fref iwm-%data% (2) ((1 *)) iwm-%offset%))
(setf ml3 (f2cl-lib:int-add ml 3))
(setf mband (f2cl-lib:int-add ml mu 1))
(setf mba
(min (the f2cl-lib:integer4 mband)
(the f2cl-lib:integer4 n)))
(setf meband (f2cl-lib:int-add mband ml))
(setf meb1 (f2cl-lib:int-sub meband 1))
(setf srur (f2cl-lib:fref wm-%data% (1) ((1 *)) wm-%offset%))
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j mba) nil)
(tagbody
(f2cl-lib:fdo (i j (f2cl-lib:int-add i mband))
((> i n) nil)
(tagbody
(setf yi (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%))
(setf r
(max (* srur (abs yi))
(/ 0.01d0
(f2cl-lib:fref ewt-%data%
(i)
((1 *))
ewt-%offset%))))
label530
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
r))))
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s rtem ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
(f2cl-lib:fdo (jj j (f2cl-lib:int-add jj mband))
((> jj n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (jj) ((1 *)) y-%offset%)
(f2cl-lib:fref yh-%data%
(jj 1)
((1 nyh) (1 *))
yh-%offset%))
(setf yjj (f2cl-lib:fref y-%data% (jj) ((1 *)) y-%offset%))
(setf r
(max (* srur (abs yjj))
(/ 0.01d0
(f2cl-lib:fref ewt-%data%
(jj)
((1 *))
ewt-%offset%))))
(setf fac (/ (- hl0) r))
(setf i1
(max (the f2cl-lib:integer4 (f2cl-lib:int-sub jj mu))
(the f2cl-lib:integer4 1)))
(setf i2
(min (the f2cl-lib:integer4 (f2cl-lib:int-add jj ml))
(the f2cl-lib:integer4 n)))
(setf ii
(f2cl-lib:int-add
(f2cl-lib:int-sub (f2cl-lib:int-mul jj meb1) ml)
2))
(f2cl-lib:fdo (i i1 (f2cl-lib:int-add i 1))
((> i i2) nil)
(tagbody
label540
(setf (f2cl-lib:fref wm-%data%
((f2cl-lib:int-add ii i))
((1 *))
wm-%offset%)
(*
(-
(f2cl-lib:fref rtem-%data%
(i)
((1 *))
rtem-%offset%)
(f2cl-lib:fref savr-%data%
(i)
((1 *))
savr-%offset%))
fac))))
label550))
label560))
(setf ires 1)
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s savr ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
label570
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 var-6)
(funcall adda
neq
tn
y
ml
mu
(f2cl-lib:array-slice wm-%data%
double-float
(ml3)
((1 *))
wm-%offset%)
meband)
(declare (ignore var-0 var-2 var-5))
(when var-1
(setf tn var-1))
(when var-3
(setf ml var-3))
(when var-4
(setf mu var-4))
(when var-6
(setf meband var-6)))
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 var-6)
(dgbfa
(f2cl-lib:array-slice wm-%data%
double-float
(3)
((1 *))
wm-%offset%)
meband n ml mu
(f2cl-lib:array-slice iwm-%data%
f2cl-lib:integer4
(21)
((1 *))
iwm-%offset%)
ier)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-5))
(setf ier var-6))
(if (/= ier 0) (setf ierpj 1))
(go end_label)
label600
(setf ierpj ires)
(go end_label)
end_label
(return
(values nil nil nil nil nil nil nil nil nil nil nil nil nil)))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dprepji
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((array fortran-to-lisp::integer4 (*))
(array double-float (*)) (array double-float (*))
(fortran-to-lisp::integer4) (array double-float (*))
(array double-float (*)) (array double-float (*))
(array double-float (*)) (array double-float (*))
(array fortran-to-lisp::integer4 (*)) t t t)
:return-values '(nil nil nil nil nil nil nil nil nil nil nil nil
nil)
:calls '(fortran-to-lisp::dgbfa fortran-to-lisp::dgefa))))
| null | https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/share/odepack/src/dprepji.lisp | lisp | Compiled by f2cl version:
Using Lisp CMU Common Lisp snapshot-2013-11 (20E Unicode)
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format single-float)) | ( " f2cl1.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " )
(in-package "ODEPACK")
(defun dprepji (neq y yh nyh ewt rtem savr s wm iwm res jac adda)
(declare (type (f2cl-lib:integer4) nyh)
(type (array double-float (*)) wm s savr rtem ewt yh y)
(type (array f2cl-lib:integer4 (*)) iwm neq))
(let ()
(symbol-macrolet ((el0 (aref (dls001-part-0 *dls001-common-block*) 210))
(h (aref (dls001-part-0 *dls001-common-block*) 211))
(tn (aref (dls001-part-0 *dls001-common-block*) 216))
(ierpj (aref (dls001-part-1 *dls001-common-block*) 13))
(jcur (aref (dls001-part-1 *dls001-common-block*) 15))
(miter (aref (dls001-part-1 *dls001-common-block*) 26))
(n (aref (dls001-part-1 *dls001-common-block*) 31))
(nfe (aref (dls001-part-1 *dls001-common-block*) 34))
(nje (aref (dls001-part-1 *dls001-common-block*) 35)))
(f2cl-lib:with-multi-array-data
((neq f2cl-lib:integer4 neq-%data% neq-%offset%)
(iwm f2cl-lib:integer4 iwm-%data% iwm-%offset%)
(y double-float y-%data% y-%offset%)
(yh double-float yh-%data% yh-%offset%)
(ewt double-float ewt-%data% ewt-%offset%)
(rtem double-float rtem-%data% rtem-%offset%)
(savr double-float savr-%data% savr-%offset%)
(s double-float s-%data% s-%offset%)
(wm double-float wm-%data% wm-%offset%))
(prog ((mu 0) (ml3 0) (ml 0) (meband 0) (meb1 0) (mband 0) (mba 0)
(lenp 0) (jj 0) (j1 0) (j 0) (ires 0) (ii 0) (ier 0) (i2 0)
(i1 0) (i 0) (yjj 0.0d0) (yj 0.0d0) (yi 0.0d0) (srur 0.0d0)
(r 0.0d0) (hl0 0.0d0) (fac 0.0d0) (con 0.0d0))
(declare (type (double-float) con fac hl0 r srur yi yj yjj)
(type (f2cl-lib:integer4) i i1 i2 ier ii ires j j1 jj lenp
mba mband meb1 meband ml ml3 mu))
(setf nje (f2cl-lib:int-add nje 1))
(setf hl0 (* h el0))
(setf ierpj 0)
(setf jcur 1)
(f2cl-lib:computed-goto
(label100 label200 label300 label400 label500)
miter)
label100
(setf ires 1)
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s savr ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
(setf lenp (f2cl-lib:int-mul n n))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i lenp) nil)
(tagbody
label110
(setf (f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i 2))
((1 *))
wm-%offset%)
0.0d0)))
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7)
(funcall jac
neq
tn
y
s
0
0
(f2cl-lib:array-slice wm-%data%
double-float
(3)
((1 *))
wm-%offset%)
n)
(declare (ignore var-0 var-2 var-3 var-4 var-5 var-6))
(when var-1
(setf tn var-1))
(when var-7
(setf n var-7)))
(setf con (- hl0))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i lenp) nil)
(tagbody
label120
(setf (f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i 2))
((1 *))
wm-%offset%)
(*
(f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i 2))
((1 *))
wm-%offset%)
con))))
(go label240)
label200
(setf ires -1)
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s savr ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
(setf srur (f2cl-lib:fref wm-%data% (1) ((1 *)) wm-%offset%))
(setf j1 2)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf yj (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%))
(setf r
(max (* srur (abs yj))
(/ 0.01d0
(f2cl-lib:fref ewt-%data%
(j)
((1 *))
ewt-%offset%))))
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%) r))
(setf fac (/ (- hl0) r))
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s rtem ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label220
(setf (f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i j1))
((1 *))
wm-%offset%)
(*
(-
(f2cl-lib:fref rtem-%data%
(i)
((1 *))
rtem-%offset%)
(f2cl-lib:fref savr-%data%
(i)
((1 *))
savr-%offset%))
fac))))
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%) yj)
(setf j1 (f2cl-lib:int-add j1 n))
label230))
(setf ires 1)
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s savr ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
label240
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 var-6)
(funcall adda
neq
tn
y
0
0
(f2cl-lib:array-slice wm-%data%
double-float
(3)
((1 *))
wm-%offset%)
n)
(declare (ignore var-0 var-2 var-3 var-4 var-5))
(when var-1
(setf tn var-1))
(when var-6
(setf n var-6)))
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4)
(dgefa
(f2cl-lib:array-slice wm-%data%
double-float
(3)
((1 *))
wm-%offset%)
n n
(f2cl-lib:array-slice iwm-%data%
f2cl-lib:integer4
(21)
((1 *))
iwm-%offset%)
ier)
(declare (ignore var-0 var-1 var-2 var-3))
(setf ier var-4))
(if (/= ier 0) (setf ierpj 1))
(go end_label)
label300
(go end_label)
label400
(setf ires 1)
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s savr ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
(setf ml (f2cl-lib:fref iwm-%data% (1) ((1 *)) iwm-%offset%))
(setf mu (f2cl-lib:fref iwm-%data% (2) ((1 *)) iwm-%offset%))
(setf ml3 (f2cl-lib:int-add ml 3))
(setf mband (f2cl-lib:int-add ml mu 1))
(setf meband (f2cl-lib:int-add mband ml))
(setf lenp (f2cl-lib:int-mul meband n))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i lenp) nil)
(tagbody
label410
(setf (f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i 2))
((1 *))
wm-%offset%)
0.0d0)))
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7)
(funcall jac
neq
tn
y
s
ml
mu
(f2cl-lib:array-slice wm-%data%
double-float
(ml3)
((1 *))
wm-%offset%)
meband)
(declare (ignore var-0 var-2 var-3 var-6))
(when var-1
(setf tn var-1))
(when var-4
(setf ml var-4))
(when var-5
(setf mu var-5))
(when var-7
(setf meband var-7)))
(setf con (- hl0))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i lenp) nil)
(tagbody
label420
(setf (f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i 2))
((1 *))
wm-%offset%)
(*
(f2cl-lib:fref wm-%data%
((f2cl-lib:int-add i 2))
((1 *))
wm-%offset%)
con))))
(go label570)
label500
(setf ires -1)
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s savr ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
(setf ml (f2cl-lib:fref iwm-%data% (1) ((1 *)) iwm-%offset%))
(setf mu (f2cl-lib:fref iwm-%data% (2) ((1 *)) iwm-%offset%))
(setf ml3 (f2cl-lib:int-add ml 3))
(setf mband (f2cl-lib:int-add ml mu 1))
(setf mba
(min (the f2cl-lib:integer4 mband)
(the f2cl-lib:integer4 n)))
(setf meband (f2cl-lib:int-add mband ml))
(setf meb1 (f2cl-lib:int-sub meband 1))
(setf srur (f2cl-lib:fref wm-%data% (1) ((1 *)) wm-%offset%))
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j mba) nil)
(tagbody
(f2cl-lib:fdo (i j (f2cl-lib:int-add i mband))
((> i n) nil)
(tagbody
(setf yi (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%))
(setf r
(max (* srur (abs yi))
(/ 0.01d0
(f2cl-lib:fref ewt-%data%
(i)
((1 *))
ewt-%offset%))))
label530
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
r))))
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s rtem ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
(f2cl-lib:fdo (jj j (f2cl-lib:int-add jj mband))
((> jj n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (jj) ((1 *)) y-%offset%)
(f2cl-lib:fref yh-%data%
(jj 1)
((1 nyh) (1 *))
yh-%offset%))
(setf yjj (f2cl-lib:fref y-%data% (jj) ((1 *)) y-%offset%))
(setf r
(max (* srur (abs yjj))
(/ 0.01d0
(f2cl-lib:fref ewt-%data%
(jj)
((1 *))
ewt-%offset%))))
(setf fac (/ (- hl0) r))
(setf i1
(max (the f2cl-lib:integer4 (f2cl-lib:int-sub jj mu))
(the f2cl-lib:integer4 1)))
(setf i2
(min (the f2cl-lib:integer4 (f2cl-lib:int-add jj ml))
(the f2cl-lib:integer4 n)))
(setf ii
(f2cl-lib:int-add
(f2cl-lib:int-sub (f2cl-lib:int-mul jj meb1) ml)
2))
(f2cl-lib:fdo (i i1 (f2cl-lib:int-add i 1))
((> i i2) nil)
(tagbody
label540
(setf (f2cl-lib:fref wm-%data%
((f2cl-lib:int-add ii i))
((1 *))
wm-%offset%)
(*
(-
(f2cl-lib:fref rtem-%data%
(i)
((1 *))
rtem-%offset%)
(f2cl-lib:fref savr-%data%
(i)
((1 *))
savr-%offset%))
fac))))
label550))
label560))
(setf ires 1)
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(funcall res neq tn y s savr ires)
(declare (ignore var-0 var-2 var-3 var-4))
(when var-1
(setf tn var-1))
(when var-5
(setf ires var-5)))
(setf nfe (f2cl-lib:int-add nfe 1))
(if (> ires 1) (go label600))
label570
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 var-6)
(funcall adda
neq
tn
y
ml
mu
(f2cl-lib:array-slice wm-%data%
double-float
(ml3)
((1 *))
wm-%offset%)
meband)
(declare (ignore var-0 var-2 var-5))
(when var-1
(setf tn var-1))
(when var-3
(setf ml var-3))
(when var-4
(setf mu var-4))
(when var-6
(setf meband var-6)))
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 var-6)
(dgbfa
(f2cl-lib:array-slice wm-%data%
double-float
(3)
((1 *))
wm-%offset%)
meband n ml mu
(f2cl-lib:array-slice iwm-%data%
f2cl-lib:integer4
(21)
((1 *))
iwm-%offset%)
ier)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-5))
(setf ier var-6))
(if (/= ier 0) (setf ierpj 1))
(go end_label)
label600
(setf ierpj ires)
(go end_label)
end_label
(return
(values nil nil nil nil nil nil nil nil nil nil nil nil nil)))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dprepji
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((array fortran-to-lisp::integer4 (*))
(array double-float (*)) (array double-float (*))
(fortran-to-lisp::integer4) (array double-float (*))
(array double-float (*)) (array double-float (*))
(array double-float (*)) (array double-float (*))
(array fortran-to-lisp::integer4 (*)) t t t)
:return-values '(nil nil nil nil nil nil nil nil nil nil nil nil
nil)
:calls '(fortran-to-lisp::dgbfa fortran-to-lisp::dgefa))))
|
638b241d1a93f038319506838e91715ae44a3374c7e5c5f71eb569e5551a818b | ar-nelson/schemepunk | nieper-rbtree.scm | Copyright ( C ) ( 2016 ) . All Rights Reserved .
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
files ( the " Software " ) , to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software , and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;; Concrete data types
(define (make-item key value) (vector key value))
(define (item-key item) (vector-ref item 0))
(define (item-value item) (vector-ref item 1))
(define (node color left item right) (vector color left item right))
(define (color node) (vector-ref node 0))
(define (left node) (vector-ref node 1))
(define (item node) (vector-ref node 2))
(define (right node) (vector-ref node 3))
(define (key node) (item-key (item node)))
(define (value node) (item-value (item node)))
(define (red left item right) (node 'red left item right))
(define black
(case-lambda
(() (black #f #f #f))
((left item right) (node 'black left item right))))
(define white
(case-lambda
(() (white #f #f #f))
((left item right) (node 'white left item right))))
(define (red? node) (eq? (color node) 'red))
(define (black? node) (eq? (color node) 'black))
(define (white? node) (eq? (color node) 'white))
;;; Tree matcher macros
(define-syntax tree-match
(syntax-rules ()
((tree-match tree (pattern . expression*) ...)
(compile-patterns (expression* ...) tree () (pattern ...)))))
(define-syntax compile-patterns
(syntax-rules ()
((compile-patterns (expression* ...) tree (clauses ...) ())
(call-with-current-continuation
(lambda (return)
(or (and-let* clauses
(call-with-values
(lambda () . expression*)
return))
...
(error "tree does not match any pattern" tree)))))
((compile-patterns e tree clauses* (pattern . pattern*))
(compile-pattern tree pattern
(add-pattern e tree clauses* pattern*)))))
(define-syntax add-pattern
(syntax-rules ()
((add-pattern e tree (clauses ...) pattern* new-clauses)
(compile-patterns e tree (clauses ... new-clauses) pattern*))))
(define-syntax compile-pattern
does n't like _ , so replace it with _ _ . - Adam
(syntax-rules (__ and red? black? white? ? node red black white)
((compile-pattern tree (red? x) (k ...))
(k ... (((red? tree)) (x tree))))
((compile-pattern tree (black? x) (k ...))
(k ... (((black? tree)) (x tree))))
((compile-pattern tree (white? x) (k ...))
(k ... (((white? tree)) (x tree))))
((compile-pattern tree (black) (k ...))
(k ... (((black? tree)) ((not (item tree))))))
((compile-pattern tree (white) (k ...))
(k ... (((white? tree)) ((not (item tree))))))
((compile-pattern tree (and pt ...) k*)
(compile-subpatterns () ((t pt) ...)
(compile-and-pattern tree t k*)))
((compile-pattern tree (node pc pa px pb) k*)
(compile-subpatterns () ((c pc) (a pa) (x px) (b pb))
(compile-node-pattern tree c a x b k*)))
((compile-pattern tree (red pa px pb) k*)
(compile-subpatterns () ((a pa) (x px) (b pb))
(compile-color-pattern red? tree a x b k*)))
((compile-pattern tree (black pa px pb) k*)
(compile-subpatterns () ((a pa) (x px) (b pb))
(compile-color-pattern black? tree a x b k*)))
((compile-pattern tree (white pa px pb) k*)
(compile-subpatterns () ((a pa) (x px) (b pb))
(compile-color-pattern white? tree a x b k*)))
((compile-pattern tree __ (k ...))
(k ... ()))
((compile-pattern tree x (k ...))
(k ... ((x tree))))))
(define-syntax compile-and-pattern
(syntax-rules ()
((compile-and-pattern tree t (k ...) clauses)
(k ... ((t tree) . clauses)))))
(define-syntax compile-node-pattern
(syntax-rules ()
((compile-node-pattern tree c a x b (k ...) clauses)
(k ... (((item tree))
(c (color tree))
(a (left tree))
(x (item tree))
(b (right tree)) . clauses)))))
(define-syntax compile-color-pattern
(syntax-rules ()
((compile-color-pattern pred? tree a x b (k ...) clauses)
(k ... (((item tree))
((pred? tree))
(a (left tree))
(x (item tree))
(b (right tree)) . clauses)))))
(define-syntax compile-subpatterns
(syntax-rules ()
((compile-subpatterns clauses () (k ...))
(k ... clauses))
((compile-subpatterns clauses ((tree pattern) . rest) k*)
(compile-pattern tree pattern (add-subpattern clauses rest k*)))))
(define-syntax add-subpattern
(syntax-rules ()
((add-subpattern (clause ...) rest k* clauses)
(compile-subpatterns (clause ... . clauses) rest k*))))
;;; Tree recolouring procedures
(define (blacken tree)
(tree-match tree
((red a x b)
(black a x b))
(t t)))
(define (redden tree)
(tree-match tree
((black (black? a) x (black? b))
(red a x b))
(t t)))
(define (white->black tree)
(tree-match tree
((white)
(black))
((white a x b)
(black a x b))))
;;; Exported identifiers
(define (make-tree) (black))
(define (tree-fold proc seed tree)
(let loop ((acc seed) (tree tree))
(tree-match tree
((black)
acc)
((node __ a x b)
(let*
((acc (loop acc a))
(acc (proc (item-key x) (item-value x) acc))
(acc (loop acc b)))
acc)))))
(define (tree-fold/reverse proc seed tree)
(let loop ((acc seed) (tree tree))
(tree-match tree
((black)
acc)
((node __ a x b)
(let*
((acc (loop acc b))
(acc (proc (item-key x) (item-value x) acc))
(acc (loop acc a)))
acc)))))
(define (tree-for-each proc tree)
(tree-fold (lambda (key value acc)
(proc key value))
#f tree))
(define (tree-generator tree)
(make-coroutine-generator
(lambda (yield)
(tree-for-each (lambda item (yield item)) tree))))
(define (identity obj) obj)
(define (tree-search comparator tree obj failure success)
(receive (tree ret op)
(let search ((tree (redden tree)))
(tree-match tree
((black)
(failure
;; insert
(lambda (new-key new-value ret)
(values (red (black) (make-item new-key new-value) (black))
ret
balance))
;; ignore
(lambda (ret)
(values (black) ret identity))))
((and t (node c a x b))
(let ((key (item-key x)))
(comparator-if<=> comparator obj key
(receive (a ret op) (search a)
(values (op (node c a x b)) ret op))
(success
key
(item-value x)
;; update
(lambda (new-key new-value ret)
(values (node c a (make-item new-key new-value) b)
ret
identity))
;; remove
(lambda (ret)
(values
(tree-match t
((red (black) x (black))
(black))
((black (red a x b) __ (black))
(black a x b))
((black (black) __ (black))
(white))
(__
(receive (x b) (min+delete b)
(rotate (node c a x b)))))
ret
rotate)))
(receive (b ret op) (search b)
(values (op (node c a x b)) ret op)))))))
(values (blacken tree) ret)))
(define (tree-key-successor comparator tree obj failure)
(let loop ((return failure) (tree tree))
(tree-match tree
((black)
(return))
((node __ a x b)
(let ((key (item-key x)))
(comparator-if<=> comparator key obj
(loop return b)
(loop return b)
(loop (lambda () key) a)))))))
(define (tree-key-predecessor comparator tree obj failure)
(let loop ((return failure) (tree tree))
(tree-match tree
((black)
(return))
((node __ a x b)
(let ((key (item-key x)))
(comparator-if<=> comparator key obj
(loop (lambda () key) b)
(loop return a)
(loop return a)))))))
(define (tree-map proc tree)
(let loop ((tree tree))
(tree-match tree
((black)
(black))
((node c a x b)
(receive (key value)
(proc (item-key x) (item-value x))
(node c (loop a) (make-item key value) (loop b)))))))
(define (tree-catenate tree1 pivot-key pivot-value tree2)
(let ((pivot (make-item pivot-key pivot-value))
(height1 (black-height tree1))
(height2 (black-height tree2)))
(cond
((= height1 height2)
(black tree1 pivot tree2))
((< height1 height2)
(blacken
(let loop ((tree tree2) (depth (- height2 height1)))
(if (zero? depth)
(balance (red tree1 pivot tree))
(balance
(node (color tree) (loop (left tree) (- depth 1)) (item tree) (right tree)))))))
(else
(blacken
(let loop ((tree tree1) (depth (- height1 height2)))
(if (zero? depth)
(balance (red tree pivot tree2))
(balance
(node (color tree) (left tree) (item tree) (loop (right tree) (- depth 1)))))))))))
(define (tree-split comparator tree obj)
(let loop ((tree1 (black))
(tree2 (black))
(pivot1 #f)
(pivot2 #f)
(tree tree))
(tree-match tree
((black)
(let ((tree1 (catenate-left tree1 pivot1 (black)))
(tree2 (catenate-right (black) pivot2 tree2)))
(values tree1 tree1 (black) tree2 tree2)))
((node __ a x b)
(comparator-if<=> comparator obj (item-key x)
(loop tree1
(catenate-right (blacken b) pivot2 tree2)
pivot1
x
(blacken a))
(let* ((tree1 (catenate-left tree1 pivot1 (blacken a)))
(tree1+ (catenate-left tree1 x (black)))
(tree2 (catenate-right (blacken b) pivot2 tree2))
(tree2+ (catenate-right (black) x tree2)))
(values tree1
tree1+
(black (black) x (black))
tree2+
tree2))
(loop (catenate-left tree1 pivot1 (blacken a))
tree2
x
pivot2
(blacken b)))))))
(define (catenate-left tree1 item tree2)
(if item
(tree-catenate tree1 (item-key item) (item-value item) tree2)
tree2))
(define (catenate-right tree1 item tree2)
(if item
(tree-catenate tree1 (item-key item) (item-value item) tree2)
tree1))
(define (black-height tree)
(let loop ((tree tree))
(tree-match tree
((black)
0)
((node red a x b)
(loop b))
((node black a x b)
(+ 1 (loop b))))))
(define (left-tree tree depth)
(let loop ((parent #f) (tree tree) (depth depth))
(if (zero? depth)
(values parent tree)
(loop tree (left tree) (- depth 1)))))
(define (right-tree tree depth)
(let loop ((parent #f) (tree tree) (depth depth))
(if (zero? depth)
(values parent tree)
(loop tree (right tree) (- depth 1)))))
;;; Helper procedures for deleting and balancing
(define (min+delete tree)
(tree-match tree
((red (black) x (black))
(values x (black)))
((black (black) x (black))
(values x (white)))
((black (black) x (red a y b))
(values x (black a y b)))
((node c a x b)
(receive (v a) (min+delete a)
(values v (rotate (node c a x b)))))))
(define (balance tree)
(tree-match tree
((black (red (red a x b) y c) z d)
(red (black a x b) y (black c z d)))
((black (red a x (red b y c)) z d)
(red (black a x b) y (black c z d)))
((black a x (red (red b y c) z d))
(red (black a x b) y (black c z d)))
((black a x (red b y (red c z d)))
(red (black a x b) y (black c z d)))
((white (red a x (red b y c)) z d)
(black (black a x b) y (black c z d)))
((white a x (red (red b y c) z d))
(black (black a x b) y (black c z d)))
(t t)))
(define (rotate tree)
(tree-match tree
((red (white? a+x+b) y (black c z d))
(balance (black (red (white->black a+x+b) y c) z d)))
((red (black a x b) y (white? c+z+d))
(balance (black a x (red b y (white->black c+z+d)))))
((black (white? a+x+b) y (black c z d))
(balance (white (red (white->black a+x+b) y c) z d)))
((black (black a x b) y (white? c+z+d))
(balance (white a x (red b y (white->black c+z+d)))))
((black (white? a+w+b) x (red (black c y d) z e))
(black (balance (black (red (white->black a+w+b) x c) y d)) z e))
((black (red a w (black b x c)) y (white? d+z+e))
(black a w (balance (black b x (red c y (white->black d+z+e))))))
(t t)))
| null | https://raw.githubusercontent.com/ar-nelson/schemepunk/e2840d3c445933528aaf0a36ec72b053ec5016ce/tests/old-mapping/nieper-rbtree.scm | scheme | Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
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.
Concrete data types
Tree matcher macros
Tree recolouring procedures
Exported identifiers
insert
ignore
update
remove
Helper procedures for deleting and balancing | Copyright ( C ) ( 2016 ) . All Rights Reserved .
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
(define (make-item key value) (vector key value))
(define (item-key item) (vector-ref item 0))
(define (item-value item) (vector-ref item 1))
(define (node color left item right) (vector color left item right))
(define (color node) (vector-ref node 0))
(define (left node) (vector-ref node 1))
(define (item node) (vector-ref node 2))
(define (right node) (vector-ref node 3))
(define (key node) (item-key (item node)))
(define (value node) (item-value (item node)))
(define (red left item right) (node 'red left item right))
(define black
(case-lambda
(() (black #f #f #f))
((left item right) (node 'black left item right))))
(define white
(case-lambda
(() (white #f #f #f))
((left item right) (node 'white left item right))))
(define (red? node) (eq? (color node) 'red))
(define (black? node) (eq? (color node) 'black))
(define (white? node) (eq? (color node) 'white))
(define-syntax tree-match
(syntax-rules ()
((tree-match tree (pattern . expression*) ...)
(compile-patterns (expression* ...) tree () (pattern ...)))))
(define-syntax compile-patterns
(syntax-rules ()
((compile-patterns (expression* ...) tree (clauses ...) ())
(call-with-current-continuation
(lambda (return)
(or (and-let* clauses
(call-with-values
(lambda () . expression*)
return))
...
(error "tree does not match any pattern" tree)))))
((compile-patterns e tree clauses* (pattern . pattern*))
(compile-pattern tree pattern
(add-pattern e tree clauses* pattern*)))))
(define-syntax add-pattern
(syntax-rules ()
((add-pattern e tree (clauses ...) pattern* new-clauses)
(compile-patterns e tree (clauses ... new-clauses) pattern*))))
(define-syntax compile-pattern
does n't like _ , so replace it with _ _ . - Adam
(syntax-rules (__ and red? black? white? ? node red black white)
((compile-pattern tree (red? x) (k ...))
(k ... (((red? tree)) (x tree))))
((compile-pattern tree (black? x) (k ...))
(k ... (((black? tree)) (x tree))))
((compile-pattern tree (white? x) (k ...))
(k ... (((white? tree)) (x tree))))
((compile-pattern tree (black) (k ...))
(k ... (((black? tree)) ((not (item tree))))))
((compile-pattern tree (white) (k ...))
(k ... (((white? tree)) ((not (item tree))))))
((compile-pattern tree (and pt ...) k*)
(compile-subpatterns () ((t pt) ...)
(compile-and-pattern tree t k*)))
((compile-pattern tree (node pc pa px pb) k*)
(compile-subpatterns () ((c pc) (a pa) (x px) (b pb))
(compile-node-pattern tree c a x b k*)))
((compile-pattern tree (red pa px pb) k*)
(compile-subpatterns () ((a pa) (x px) (b pb))
(compile-color-pattern red? tree a x b k*)))
((compile-pattern tree (black pa px pb) k*)
(compile-subpatterns () ((a pa) (x px) (b pb))
(compile-color-pattern black? tree a x b k*)))
((compile-pattern tree (white pa px pb) k*)
(compile-subpatterns () ((a pa) (x px) (b pb))
(compile-color-pattern white? tree a x b k*)))
((compile-pattern tree __ (k ...))
(k ... ()))
((compile-pattern tree x (k ...))
(k ... ((x tree))))))
(define-syntax compile-and-pattern
(syntax-rules ()
((compile-and-pattern tree t (k ...) clauses)
(k ... ((t tree) . clauses)))))
(define-syntax compile-node-pattern
(syntax-rules ()
((compile-node-pattern tree c a x b (k ...) clauses)
(k ... (((item tree))
(c (color tree))
(a (left tree))
(x (item tree))
(b (right tree)) . clauses)))))
(define-syntax compile-color-pattern
(syntax-rules ()
((compile-color-pattern pred? tree a x b (k ...) clauses)
(k ... (((item tree))
((pred? tree))
(a (left tree))
(x (item tree))
(b (right tree)) . clauses)))))
(define-syntax compile-subpatterns
(syntax-rules ()
((compile-subpatterns clauses () (k ...))
(k ... clauses))
((compile-subpatterns clauses ((tree pattern) . rest) k*)
(compile-pattern tree pattern (add-subpattern clauses rest k*)))))
(define-syntax add-subpattern
(syntax-rules ()
((add-subpattern (clause ...) rest k* clauses)
(compile-subpatterns (clause ... . clauses) rest k*))))
(define (blacken tree)
(tree-match tree
((red a x b)
(black a x b))
(t t)))
(define (redden tree)
(tree-match tree
((black (black? a) x (black? b))
(red a x b))
(t t)))
(define (white->black tree)
(tree-match tree
((white)
(black))
((white a x b)
(black a x b))))
(define (make-tree) (black))
(define (tree-fold proc seed tree)
(let loop ((acc seed) (tree tree))
(tree-match tree
((black)
acc)
((node __ a x b)
(let*
((acc (loop acc a))
(acc (proc (item-key x) (item-value x) acc))
(acc (loop acc b)))
acc)))))
(define (tree-fold/reverse proc seed tree)
(let loop ((acc seed) (tree tree))
(tree-match tree
((black)
acc)
((node __ a x b)
(let*
((acc (loop acc b))
(acc (proc (item-key x) (item-value x) acc))
(acc (loop acc a)))
acc)))))
(define (tree-for-each proc tree)
(tree-fold (lambda (key value acc)
(proc key value))
#f tree))
(define (tree-generator tree)
(make-coroutine-generator
(lambda (yield)
(tree-for-each (lambda item (yield item)) tree))))
(define (identity obj) obj)
(define (tree-search comparator tree obj failure success)
(receive (tree ret op)
(let search ((tree (redden tree)))
(tree-match tree
((black)
(failure
(lambda (new-key new-value ret)
(values (red (black) (make-item new-key new-value) (black))
ret
balance))
(lambda (ret)
(values (black) ret identity))))
((and t (node c a x b))
(let ((key (item-key x)))
(comparator-if<=> comparator obj key
(receive (a ret op) (search a)
(values (op (node c a x b)) ret op))
(success
key
(item-value x)
(lambda (new-key new-value ret)
(values (node c a (make-item new-key new-value) b)
ret
identity))
(lambda (ret)
(values
(tree-match t
((red (black) x (black))
(black))
((black (red a x b) __ (black))
(black a x b))
((black (black) __ (black))
(white))
(__
(receive (x b) (min+delete b)
(rotate (node c a x b)))))
ret
rotate)))
(receive (b ret op) (search b)
(values (op (node c a x b)) ret op)))))))
(values (blacken tree) ret)))
(define (tree-key-successor comparator tree obj failure)
(let loop ((return failure) (tree tree))
(tree-match tree
((black)
(return))
((node __ a x b)
(let ((key (item-key x)))
(comparator-if<=> comparator key obj
(loop return b)
(loop return b)
(loop (lambda () key) a)))))))
(define (tree-key-predecessor comparator tree obj failure)
(let loop ((return failure) (tree tree))
(tree-match tree
((black)
(return))
((node __ a x b)
(let ((key (item-key x)))
(comparator-if<=> comparator key obj
(loop (lambda () key) b)
(loop return a)
(loop return a)))))))
(define (tree-map proc tree)
(let loop ((tree tree))
(tree-match tree
((black)
(black))
((node c a x b)
(receive (key value)
(proc (item-key x) (item-value x))
(node c (loop a) (make-item key value) (loop b)))))))
(define (tree-catenate tree1 pivot-key pivot-value tree2)
(let ((pivot (make-item pivot-key pivot-value))
(height1 (black-height tree1))
(height2 (black-height tree2)))
(cond
((= height1 height2)
(black tree1 pivot tree2))
((< height1 height2)
(blacken
(let loop ((tree tree2) (depth (- height2 height1)))
(if (zero? depth)
(balance (red tree1 pivot tree))
(balance
(node (color tree) (loop (left tree) (- depth 1)) (item tree) (right tree)))))))
(else
(blacken
(let loop ((tree tree1) (depth (- height1 height2)))
(if (zero? depth)
(balance (red tree pivot tree2))
(balance
(node (color tree) (left tree) (item tree) (loop (right tree) (- depth 1)))))))))))
(define (tree-split comparator tree obj)
(let loop ((tree1 (black))
(tree2 (black))
(pivot1 #f)
(pivot2 #f)
(tree tree))
(tree-match tree
((black)
(let ((tree1 (catenate-left tree1 pivot1 (black)))
(tree2 (catenate-right (black) pivot2 tree2)))
(values tree1 tree1 (black) tree2 tree2)))
((node __ a x b)
(comparator-if<=> comparator obj (item-key x)
(loop tree1
(catenate-right (blacken b) pivot2 tree2)
pivot1
x
(blacken a))
(let* ((tree1 (catenate-left tree1 pivot1 (blacken a)))
(tree1+ (catenate-left tree1 x (black)))
(tree2 (catenate-right (blacken b) pivot2 tree2))
(tree2+ (catenate-right (black) x tree2)))
(values tree1
tree1+
(black (black) x (black))
tree2+
tree2))
(loop (catenate-left tree1 pivot1 (blacken a))
tree2
x
pivot2
(blacken b)))))))
(define (catenate-left tree1 item tree2)
(if item
(tree-catenate tree1 (item-key item) (item-value item) tree2)
tree2))
(define (catenate-right tree1 item tree2)
(if item
(tree-catenate tree1 (item-key item) (item-value item) tree2)
tree1))
(define (black-height tree)
(let loop ((tree tree))
(tree-match tree
((black)
0)
((node red a x b)
(loop b))
((node black a x b)
(+ 1 (loop b))))))
(define (left-tree tree depth)
(let loop ((parent #f) (tree tree) (depth depth))
(if (zero? depth)
(values parent tree)
(loop tree (left tree) (- depth 1)))))
(define (right-tree tree depth)
(let loop ((parent #f) (tree tree) (depth depth))
(if (zero? depth)
(values parent tree)
(loop tree (right tree) (- depth 1)))))
(define (min+delete tree)
(tree-match tree
((red (black) x (black))
(values x (black)))
((black (black) x (black))
(values x (white)))
((black (black) x (red a y b))
(values x (black a y b)))
((node c a x b)
(receive (v a) (min+delete a)
(values v (rotate (node c a x b)))))))
(define (balance tree)
(tree-match tree
((black (red (red a x b) y c) z d)
(red (black a x b) y (black c z d)))
((black (red a x (red b y c)) z d)
(red (black a x b) y (black c z d)))
((black a x (red (red b y c) z d))
(red (black a x b) y (black c z d)))
((black a x (red b y (red c z d)))
(red (black a x b) y (black c z d)))
((white (red a x (red b y c)) z d)
(black (black a x b) y (black c z d)))
((white a x (red (red b y c) z d))
(black (black a x b) y (black c z d)))
(t t)))
(define (rotate tree)
(tree-match tree
((red (white? a+x+b) y (black c z d))
(balance (black (red (white->black a+x+b) y c) z d)))
((red (black a x b) y (white? c+z+d))
(balance (black a x (red b y (white->black c+z+d)))))
((black (white? a+x+b) y (black c z d))
(balance (white (red (white->black a+x+b) y c) z d)))
((black (black a x b) y (white? c+z+d))
(balance (white a x (red b y (white->black c+z+d)))))
((black (white? a+w+b) x (red (black c y d) z e))
(black (balance (black (red (white->black a+w+b) x c) y d)) z e))
((black (red a w (black b x c)) y (white? d+z+e))
(black a w (balance (black b x (red c y (white->black d+z+e))))))
(t t)))
|
2fc2164a8b260c8207dcf426565182ea42bb96fa44102cb930f7eee4dd4fcb4b | bvaugon/ocapic | string.mli | (**************************************************************************)
(* *)
(* 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 GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
* String operations .
A string is an immutable data structure that contains a
fixed - length sequence of ( single - byte ) characters . Each character
can be accessed in constant time through its index .
Given a string [ s ] of length [ l ] , we can access each of the [ l ]
characters of [ s ] via its index in the sequence . Indexes start at
[ 0 ] , and we will call an index valid in [ s ] if it falls within the
range [ [ 0 ... l-1 ] ] ( inclusive ) . A position is the point between two
characters or at the beginning or end of the string . We call a
position valid in [ s ] if it falls within the range [ [ 0 ... l ] ]
( inclusive ) . Note that the character at index [ n ] is between
positions [ n ] and [ n+1 ] .
Two parameters [ start ] and [ len ] are said to designate a valid
substring of [ s ] if [ len > = 0 ] and [ start ] and [ start+len ] are
valid positions in [ s ] .
OCaml strings used to be modifiable in place , for instance via the
{ ! String.set } and { ! String.blit } functions described below . This
usage is deprecated and only possible when the compiler is put in
" unsafe - string " mode by giving the [ -unsafe - string ] command - line
option ( which is currently the default for reasons of backward
compatibility ) . This is done by making the types [ string ] and
[ bytes ] ( see module { ! Bytes } ) interchangeable so that functions
expecting byte sequences can also accept strings as arguments and
modify them .
All new code should avoid this feature and be compiled with the
[ -safe - string ] command - line option to enforce the separation between
the types [ string ] and [ bytes ] .
A string is an immutable data structure that contains a
fixed-length sequence of (single-byte) characters. Each character
can be accessed in constant time through its index.
Given a string [s] of length [l], we can access each of the [l]
characters of [s] via its index in the sequence. Indexes start at
[0], and we will call an index valid in [s] if it falls within the
range [[0...l-1]] (inclusive). A position is the point between two
characters or at the beginning or end of the string. We call a
position valid in [s] if it falls within the range [[0...l]]
(inclusive). Note that the character at index [n] is between
positions [n] and [n+1].
Two parameters [start] and [len] are said to designate a valid
substring of [s] if [len >= 0] and [start] and [start+len] are
valid positions in [s].
OCaml strings used to be modifiable in place, for instance via the
{!String.set} and {!String.blit} functions described below. This
usage is deprecated and only possible when the compiler is put in
"unsafe-string" mode by giving the [-unsafe-string] command-line
option (which is currently the default for reasons of backward
compatibility). This is done by making the types [string] and
[bytes] (see module {!Bytes}) interchangeable so that functions
expecting byte sequences can also accept strings as arguments and
modify them.
All new code should avoid this feature and be compiled with the
[-safe-string] command-line option to enforce the separation between
the types [string] and [bytes].
*)
external length : string -> int = "%string_length"
(** Return the length (number of characters) of the given string. *)
external get : string -> int -> char = "%string_safe_get"
* [ String.get s n ] returns the character at index [ n ] in string [ s ] .
You can also write [ s.[n ] ] instead of [ String.get s n ] .
Raise [ Invalid_argument ] if [ n ] not a valid index in [ s ] .
You can also write [s.[n]] instead of [String.get s n].
Raise [Invalid_argument] if [n] not a valid index in [s]. *)
external set : bytes -> int -> char -> unit = "%string_safe_set"
[@@ocaml.deprecated "Use Bytes.set instead."]
(** [String.set s n c] modifies byte sequence [s] in place,
replacing the byte at index [n] with [c].
You can also write [s.[n] <- c] instead of [String.set s n c].
Raise [Invalid_argument] if [n] is not a valid index in [s].
@deprecated This is a deprecated alias of {!Bytes.set}.[ ] *)
external create : int -> bytes = "caml_create_string"
[@@ocaml.deprecated "Use Bytes.create instead."]
* [ String.create n ] returns a fresh byte sequence of length [ n ] .
The sequence is uninitialized and contains arbitrary bytes .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > ] { ! } .
@deprecated This is a deprecated alias of { ! Bytes.create } . [ ]
The sequence is uninitialized and contains arbitrary bytes.
Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}.
@deprecated This is a deprecated alias of {!Bytes.create}.[ ] *)
val make : int -> char -> string
* [ String.make n c ] returns a fresh string of length [ n ] ,
filled with the character [ c ] .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > ] { ! } .
filled with the character [c].
Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. *)
val init : int -> (int -> char) -> string
* [ String.init n f ] returns a string of length [ n ] , with character
[ i ] initialized to the result of [ f i ] ( called in increasing
index order ) .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > ] { ! } .
@since 4.02.0
[i] initialized to the result of [f i] (called in increasing
index order).
Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}.
@since 4.02.0
*)
val copy : string -> string [@@ocaml.deprecated]
(** Return a copy of the given string.
@deprecated Because strings are immutable, it doesn't make much
sense to make identical copies of them. *)
val sub : string -> int -> int -> string
* [ String.sub s start len ] returns a fresh string of length [ len ] ,
containing the substring of [ s ] that starts at position [ start ] and
has length [ len ] .
Raise [ Invalid_argument ] if [ start ] and [ len ] do not
designate a valid substring of [ s ] .
containing the substring of [s] that starts at position [start] and
has length [len].
Raise [Invalid_argument] if [start] and [len] do not
designate a valid substring of [s]. *)
val fill : bytes -> int -> int -> char -> unit
[@@ocaml.deprecated "Use Bytes.fill instead."]
* [ String.fill s start len c ] modifies byte sequence [ s ] in place ,
replacing [ len ] bytes with [ c ] , starting at [ start ] .
Raise [ Invalid_argument ] if [ start ] and [ len ] do not
designate a valid range of [ s ] .
@deprecated This is a deprecated alias of { ! Bytes.fill } . [ ]
replacing [len] bytes with [c], starting at [start].
Raise [Invalid_argument] if [start] and [len] do not
designate a valid range of [s].
@deprecated This is a deprecated alias of {!Bytes.fill}.[ ] *)
val blit : string -> int -> bytes -> int -> int -> unit
(** Same as {!Bytes.blit_string}. *)
val concat : string -> string list -> string
* [ String.concat sep sl ] concatenates the list of strings [ sl ] ,
inserting the separator string [ sep ] between each .
Raise [ Invalid_argument ] if the result is longer than
{ ! } bytes .
inserting the separator string [sep] between each.
Raise [Invalid_argument] if the result is longer than
{!Sys.max_string_length} bytes. *)
val iter : (char -> unit) -> string -> unit
(** [String.iter f s] applies function [f] in turn to all
the characters of [s]. It is equivalent to
[f s.[0]; f s.[1]; ...; f s.[String.length s - 1]; ()]. *)
val iteri : (int -> char -> unit) -> string -> unit
* Same as { ! String.iter } , but the
function is applied to the index of the element as first argument
( counting from 0 ) , and the character itself as second argument .
@since 4.00.0
function is applied to the index of the element as first argument
(counting from 0), and the character itself as second argument.
@since 4.00.0 *)
val map : (char -> char) -> string -> string
* [ String.map f s ] applies function [ f ] in turn to all the
characters of [ s ] ( in increasing index order ) and stores the
results in a new string that is returned .
@since 4.00.0
characters of [s] (in increasing index order) and stores the
results in a new string that is returned.
@since 4.00.0 *)
val mapi : (int -> char -> char) -> string -> string
* [ String.mapi f s ] calls [ f ] with each character of [ s ] and its
index ( in increasing index order ) and stores the results in a new
string that is returned .
@since 4.02.0
index (in increasing index order) and stores the results in a new
string that is returned.
@since 4.02.0 *)
val trim : string -> string
* Return a copy of the argument , without leading and trailing
whitespace . The characters regarded as whitespace are : [ ' ' ] ,
[ ' \012 ' ] , [ ' \n ' ] , [ ' \r ' ] , and [ ' \t ' ] . If there is neither leading nor
trailing whitespace character in the argument , return the original
string itself , not a copy .
@since 4.00.0
whitespace. The characters regarded as whitespace are: [' '],
['\012'], ['\n'], ['\r'], and ['\t']. If there is neither leading nor
trailing whitespace character in the argument, return the original
string itself, not a copy.
@since 4.00.0 *)
val escaped : string -> string
* Return a copy of the argument , with special characters
represented by escape sequences , following the lexical
conventions of OCaml .
All characters outside the ASCII printable range ( 32 .. 126 ) are
escaped , as well as backslash and double - quote .
If there is no special character in the argument that needs
escaping , return the original string itself , not a copy .
Raise [ Invalid_argument ] if the result is longer than
{ ! } bytes .
The function { ! Scanf.unescaped } is a left inverse of [ escaped ] ,
i.e. [ Scanf.unescaped ( escaped s ) = s ] for any string [ s ] ( unless
[ escape s ] fails ) .
represented by escape sequences, following the lexical
conventions of OCaml.
All characters outside the ASCII printable range (32..126) are
escaped, as well as backslash and double-quote.
If there is no special character in the argument that needs
escaping, return the original string itself, not a copy.
Raise [Invalid_argument] if the result is longer than
{!Sys.max_string_length} bytes.
The function {!Scanf.unescaped} is a left inverse of [escaped],
i.e. [Scanf.unescaped (escaped s) = s] for any string [s] (unless
[escape s] fails). *)
val index : string -> char -> int
* [ String.index s c ] returns the index of the first
occurrence of character [ c ] in string [ s ] .
Raise [ Not_found ] if [ c ] does not occur in [ s ] .
occurrence of character [c] in string [s].
Raise [Not_found] if [c] does not occur in [s]. *)
val rindex : string -> char -> int
(** [String.rindex s c] returns the index of the last
occurrence of character [c] in string [s].
Raise [Not_found] if [c] does not occur in [s]. *)
val index_from : string -> int -> char -> int
* [ String.index_from s i c ] returns the index of the
first occurrence of character [ c ] in string [ s ] after position [ i ] .
[ String.index s c ] is equivalent to [ String.index_from s 0 c ] .
Raise [ Invalid_argument ] if [ i ] is not a valid position in [ s ] .
Raise [ Not_found ] if [ c ] does not occur in [ s ] after position [ i ] .
first occurrence of character [c] in string [s] after position [i].
[String.index s c] is equivalent to [String.index_from s 0 c].
Raise [Invalid_argument] if [i] is not a valid position in [s].
Raise [Not_found] if [c] does not occur in [s] after position [i]. *)
val rindex_from : string -> int -> char -> int
* [ String.rindex_from s i c ] returns the index of the
last occurrence of character [ c ] in string [ s ] before position [ i+1 ] .
[ String.rindex s c ] is equivalent to
[ String.rindex_from s ( String.length s - 1 ) c ] .
Raise [ Invalid_argument ] if [ i+1 ] is not a valid position in [ s ] .
Raise [ Not_found ] if [ c ] does not occur in [ s ] before position [ i+1 ] .
last occurrence of character [c] in string [s] before position [i+1].
[String.rindex s c] is equivalent to
[String.rindex_from s (String.length s - 1) c].
Raise [Invalid_argument] if [i+1] is not a valid position in [s].
Raise [Not_found] if [c] does not occur in [s] before position [i+1]. *)
val contains : string -> char -> bool
* [ String.contains s c ] tests if character [ c ]
appears in the string [ s ] .
appears in the string [s]. *)
val contains_from : string -> int -> char -> bool
* [ String.contains_from s start c ] tests if character [ c ]
appears in [ s ] after position [ start ] .
[ String.contains s c ] is equivalent to
[ String.contains_from s 0 c ] .
Raise [ Invalid_argument ] if [ start ] is not a valid position in [ s ] .
appears in [s] after position [start].
[String.contains s c] is equivalent to
[String.contains_from s 0 c].
Raise [Invalid_argument] if [start] is not a valid position in [s]. *)
val rcontains_from : string -> int -> char -> bool
(** [String.rcontains_from s stop c] tests if character [c]
appears in [s] before position [stop+1].
Raise [Invalid_argument] if [stop < 0] or [stop+1] is not a valid
position in [s]. *)
val uppercase : string -> string
[@@ocaml.deprecated "Use String.uppercase_ascii instead."]
(** Return a copy of the argument, with all lowercase letters
translated to uppercase, including accented letters of the ISO
Latin-1 (8859-1) character set.
@deprecated Functions operating on Latin-1 character set are deprecated. *)
val lowercase : string -> string
[@@ocaml.deprecated "Use String.lowercase_ascii instead."]
(** Return a copy of the argument, with all uppercase letters
translated to lowercase, including accented letters of the ISO
Latin-1 (8859-1) character set.
@deprecated Functions operating on Latin-1 character set are deprecated. *)
val capitalize : string -> string
[@@ocaml.deprecated "Use String.capitalize_ascii instead."]
* Return a copy of the argument , with the first character set to uppercase ,
using the ISO Latin-1 ( 8859 - 1 ) character set ..
@deprecated Functions operating on Latin-1 character set are deprecated .
using the ISO Latin-1 (8859-1) character set..
@deprecated Functions operating on Latin-1 character set are deprecated. *)
val uncapitalize : string -> string
[@@ocaml.deprecated "Use String.uncapitalize_ascii instead."]
* Return a copy of the argument , with the first character set to lowercase ,
using the ISO Latin-1 ( 8859 - 1 ) character set ..
@deprecated Functions operating on Latin-1 character set are deprecated .
using the ISO Latin-1 (8859-1) character set..
@deprecated Functions operating on Latin-1 character set are deprecated. *)
val uppercase_ascii : string -> string
* Return a copy of the argument , with all lowercase letters
translated to uppercase , using the US - ASCII character set .
@since 4.03.0
translated to uppercase, using the US-ASCII character set.
@since 4.03.0 *)
val lowercase_ascii : string -> string
* Return a copy of the argument , with all uppercase letters
translated to lowercase , using the US - ASCII character set .
@since 4.03.0
translated to lowercase, using the US-ASCII character set.
@since 4.03.0 *)
val capitalize_ascii : string -> string
* Return a copy of the argument , with the first character set to uppercase ,
using the US - ASCII character set .
@since 4.03.0
using the US-ASCII character set.
@since 4.03.0 *)
val uncapitalize_ascii : string -> string
* Return a copy of the argument , with the first character set to lowercase ,
using the US - ASCII character set .
@since 4.03.0
using the US-ASCII character set.
@since 4.03.0 *)
type t = string
(** An alias for the type of strings. *)
val compare: t -> t -> int
(** The comparison function for strings, with the same specification as
{!Pervasives.compare}. Along with the type [t], this function [compare]
allows the module [String] to be passed as argument to the functors
{!Set.Make} and {!Map.Make}. *)
val equal: t -> t -> bool
* The equal function for strings .
@since 4.03.0
@since 4.03.0 *)
(**/**)
(* The following is for system use only. Do not call directly. *)
external unsafe_get : string -> int -> char = "%string_unsafe_get"
external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set"
[@@ocaml.deprecated]
external unsafe_blit :
string -> int -> bytes -> int -> int -> unit
= "caml_blit_string" [@@noalloc]
external unsafe_fill :
bytes -> int -> int -> char -> unit = "caml_fill_string" [@@noalloc]
[@@ocaml.deprecated]
| null | https://raw.githubusercontent.com/bvaugon/ocapic/a14cd9ec3f5022aeb5fe2264d595d7e8f1ddf58a/lib/string.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Return the length (number of characters) of the given string.
* [String.set s n c] modifies byte sequence [s] in place,
replacing the byte at index [n] with [c].
You can also write [s.[n] <- c] instead of [String.set s n c].
Raise [Invalid_argument] if [n] is not a valid index in [s].
@deprecated This is a deprecated alias of {!Bytes.set}.[ ]
* Return a copy of the given string.
@deprecated Because strings are immutable, it doesn't make much
sense to make identical copies of them.
* Same as {!Bytes.blit_string}.
* [String.iter f s] applies function [f] in turn to all
the characters of [s]. It is equivalent to
[f s.[0]; f s.[1]; ...; f s.[String.length s - 1]; ()].
* [String.rindex s c] returns the index of the last
occurrence of character [c] in string [s].
Raise [Not_found] if [c] does not occur in [s].
* [String.rcontains_from s stop c] tests if character [c]
appears in [s] before position [stop+1].
Raise [Invalid_argument] if [stop < 0] or [stop+1] is not a valid
position in [s].
* Return a copy of the argument, with all lowercase letters
translated to uppercase, including accented letters of the ISO
Latin-1 (8859-1) character set.
@deprecated Functions operating on Latin-1 character set are deprecated.
* Return a copy of the argument, with all uppercase letters
translated to lowercase, including accented letters of the ISO
Latin-1 (8859-1) character set.
@deprecated Functions operating on Latin-1 character set are deprecated.
* An alias for the type of strings.
* The comparison function for strings, with the same specification as
{!Pervasives.compare}. Along with the type [t], this function [compare]
allows the module [String] to be passed as argument to the functors
{!Set.Make} and {!Map.Make}.
*/*
The following is for system use only. Do not call directly. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
* String operations .
A string is an immutable data structure that contains a
fixed - length sequence of ( single - byte ) characters . Each character
can be accessed in constant time through its index .
Given a string [ s ] of length [ l ] , we can access each of the [ l ]
characters of [ s ] via its index in the sequence . Indexes start at
[ 0 ] , and we will call an index valid in [ s ] if it falls within the
range [ [ 0 ... l-1 ] ] ( inclusive ) . A position is the point between two
characters or at the beginning or end of the string . We call a
position valid in [ s ] if it falls within the range [ [ 0 ... l ] ]
( inclusive ) . Note that the character at index [ n ] is between
positions [ n ] and [ n+1 ] .
Two parameters [ start ] and [ len ] are said to designate a valid
substring of [ s ] if [ len > = 0 ] and [ start ] and [ start+len ] are
valid positions in [ s ] .
OCaml strings used to be modifiable in place , for instance via the
{ ! String.set } and { ! String.blit } functions described below . This
usage is deprecated and only possible when the compiler is put in
" unsafe - string " mode by giving the [ -unsafe - string ] command - line
option ( which is currently the default for reasons of backward
compatibility ) . This is done by making the types [ string ] and
[ bytes ] ( see module { ! Bytes } ) interchangeable so that functions
expecting byte sequences can also accept strings as arguments and
modify them .
All new code should avoid this feature and be compiled with the
[ -safe - string ] command - line option to enforce the separation between
the types [ string ] and [ bytes ] .
A string is an immutable data structure that contains a
fixed-length sequence of (single-byte) characters. Each character
can be accessed in constant time through its index.
Given a string [s] of length [l], we can access each of the [l]
characters of [s] via its index in the sequence. Indexes start at
[0], and we will call an index valid in [s] if it falls within the
range [[0...l-1]] (inclusive). A position is the point between two
characters or at the beginning or end of the string. We call a
position valid in [s] if it falls within the range [[0...l]]
(inclusive). Note that the character at index [n] is between
positions [n] and [n+1].
Two parameters [start] and [len] are said to designate a valid
substring of [s] if [len >= 0] and [start] and [start+len] are
valid positions in [s].
OCaml strings used to be modifiable in place, for instance via the
{!String.set} and {!String.blit} functions described below. This
usage is deprecated and only possible when the compiler is put in
"unsafe-string" mode by giving the [-unsafe-string] command-line
option (which is currently the default for reasons of backward
compatibility). This is done by making the types [string] and
[bytes] (see module {!Bytes}) interchangeable so that functions
expecting byte sequences can also accept strings as arguments and
modify them.
All new code should avoid this feature and be compiled with the
[-safe-string] command-line option to enforce the separation between
the types [string] and [bytes].
*)
external length : string -> int = "%string_length"
external get : string -> int -> char = "%string_safe_get"
* [ String.get s n ] returns the character at index [ n ] in string [ s ] .
You can also write [ s.[n ] ] instead of [ String.get s n ] .
Raise [ Invalid_argument ] if [ n ] not a valid index in [ s ] .
You can also write [s.[n]] instead of [String.get s n].
Raise [Invalid_argument] if [n] not a valid index in [s]. *)
external set : bytes -> int -> char -> unit = "%string_safe_set"
[@@ocaml.deprecated "Use Bytes.set instead."]
external create : int -> bytes = "caml_create_string"
[@@ocaml.deprecated "Use Bytes.create instead."]
* [ String.create n ] returns a fresh byte sequence of length [ n ] .
The sequence is uninitialized and contains arbitrary bytes .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > ] { ! } .
@deprecated This is a deprecated alias of { ! Bytes.create } . [ ]
The sequence is uninitialized and contains arbitrary bytes.
Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}.
@deprecated This is a deprecated alias of {!Bytes.create}.[ ] *)
val make : int -> char -> string
* [ String.make n c ] returns a fresh string of length [ n ] ,
filled with the character [ c ] .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > ] { ! } .
filled with the character [c].
Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. *)
val init : int -> (int -> char) -> string
* [ String.init n f ] returns a string of length [ n ] , with character
[ i ] initialized to the result of [ f i ] ( called in increasing
index order ) .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > ] { ! } .
@since 4.02.0
[i] initialized to the result of [f i] (called in increasing
index order).
Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}.
@since 4.02.0
*)
val copy : string -> string [@@ocaml.deprecated]
val sub : string -> int -> int -> string
* [ String.sub s start len ] returns a fresh string of length [ len ] ,
containing the substring of [ s ] that starts at position [ start ] and
has length [ len ] .
Raise [ Invalid_argument ] if [ start ] and [ len ] do not
designate a valid substring of [ s ] .
containing the substring of [s] that starts at position [start] and
has length [len].
Raise [Invalid_argument] if [start] and [len] do not
designate a valid substring of [s]. *)
val fill : bytes -> int -> int -> char -> unit
[@@ocaml.deprecated "Use Bytes.fill instead."]
* [ String.fill s start len c ] modifies byte sequence [ s ] in place ,
replacing [ len ] bytes with [ c ] , starting at [ start ] .
Raise [ Invalid_argument ] if [ start ] and [ len ] do not
designate a valid range of [ s ] .
@deprecated This is a deprecated alias of { ! Bytes.fill } . [ ]
replacing [len] bytes with [c], starting at [start].
Raise [Invalid_argument] if [start] and [len] do not
designate a valid range of [s].
@deprecated This is a deprecated alias of {!Bytes.fill}.[ ] *)
val blit : string -> int -> bytes -> int -> int -> unit
val concat : string -> string list -> string
* [ String.concat sep sl ] concatenates the list of strings [ sl ] ,
inserting the separator string [ sep ] between each .
Raise [ Invalid_argument ] if the result is longer than
{ ! } bytes .
inserting the separator string [sep] between each.
Raise [Invalid_argument] if the result is longer than
{!Sys.max_string_length} bytes. *)
val iter : (char -> unit) -> string -> unit
val iteri : (int -> char -> unit) -> string -> unit
* Same as { ! String.iter } , but the
function is applied to the index of the element as first argument
( counting from 0 ) , and the character itself as second argument .
@since 4.00.0
function is applied to the index of the element as first argument
(counting from 0), and the character itself as second argument.
@since 4.00.0 *)
val map : (char -> char) -> string -> string
* [ String.map f s ] applies function [ f ] in turn to all the
characters of [ s ] ( in increasing index order ) and stores the
results in a new string that is returned .
@since 4.00.0
characters of [s] (in increasing index order) and stores the
results in a new string that is returned.
@since 4.00.0 *)
val mapi : (int -> char -> char) -> string -> string
* [ String.mapi f s ] calls [ f ] with each character of [ s ] and its
index ( in increasing index order ) and stores the results in a new
string that is returned .
@since 4.02.0
index (in increasing index order) and stores the results in a new
string that is returned.
@since 4.02.0 *)
val trim : string -> string
* Return a copy of the argument , without leading and trailing
whitespace . The characters regarded as whitespace are : [ ' ' ] ,
[ ' \012 ' ] , [ ' \n ' ] , [ ' \r ' ] , and [ ' \t ' ] . If there is neither leading nor
trailing whitespace character in the argument , return the original
string itself , not a copy .
@since 4.00.0
whitespace. The characters regarded as whitespace are: [' '],
['\012'], ['\n'], ['\r'], and ['\t']. If there is neither leading nor
trailing whitespace character in the argument, return the original
string itself, not a copy.
@since 4.00.0 *)
val escaped : string -> string
* Return a copy of the argument , with special characters
represented by escape sequences , following the lexical
conventions of OCaml .
All characters outside the ASCII printable range ( 32 .. 126 ) are
escaped , as well as backslash and double - quote .
If there is no special character in the argument that needs
escaping , return the original string itself , not a copy .
Raise [ Invalid_argument ] if the result is longer than
{ ! } bytes .
The function { ! Scanf.unescaped } is a left inverse of [ escaped ] ,
i.e. [ Scanf.unescaped ( escaped s ) = s ] for any string [ s ] ( unless
[ escape s ] fails ) .
represented by escape sequences, following the lexical
conventions of OCaml.
All characters outside the ASCII printable range (32..126) are
escaped, as well as backslash and double-quote.
If there is no special character in the argument that needs
escaping, return the original string itself, not a copy.
Raise [Invalid_argument] if the result is longer than
{!Sys.max_string_length} bytes.
The function {!Scanf.unescaped} is a left inverse of [escaped],
i.e. [Scanf.unescaped (escaped s) = s] for any string [s] (unless
[escape s] fails). *)
val index : string -> char -> int
* [ String.index s c ] returns the index of the first
occurrence of character [ c ] in string [ s ] .
Raise [ Not_found ] if [ c ] does not occur in [ s ] .
occurrence of character [c] in string [s].
Raise [Not_found] if [c] does not occur in [s]. *)
val rindex : string -> char -> int
val index_from : string -> int -> char -> int
* [ String.index_from s i c ] returns the index of the
first occurrence of character [ c ] in string [ s ] after position [ i ] .
[ String.index s c ] is equivalent to [ String.index_from s 0 c ] .
Raise [ Invalid_argument ] if [ i ] is not a valid position in [ s ] .
Raise [ Not_found ] if [ c ] does not occur in [ s ] after position [ i ] .
first occurrence of character [c] in string [s] after position [i].
[String.index s c] is equivalent to [String.index_from s 0 c].
Raise [Invalid_argument] if [i] is not a valid position in [s].
Raise [Not_found] if [c] does not occur in [s] after position [i]. *)
val rindex_from : string -> int -> char -> int
* [ String.rindex_from s i c ] returns the index of the
last occurrence of character [ c ] in string [ s ] before position [ i+1 ] .
[ String.rindex s c ] is equivalent to
[ String.rindex_from s ( String.length s - 1 ) c ] .
Raise [ Invalid_argument ] if [ i+1 ] is not a valid position in [ s ] .
Raise [ Not_found ] if [ c ] does not occur in [ s ] before position [ i+1 ] .
last occurrence of character [c] in string [s] before position [i+1].
[String.rindex s c] is equivalent to
[String.rindex_from s (String.length s - 1) c].
Raise [Invalid_argument] if [i+1] is not a valid position in [s].
Raise [Not_found] if [c] does not occur in [s] before position [i+1]. *)
val contains : string -> char -> bool
* [ String.contains s c ] tests if character [ c ]
appears in the string [ s ] .
appears in the string [s]. *)
val contains_from : string -> int -> char -> bool
* [ String.contains_from s start c ] tests if character [ c ]
appears in [ s ] after position [ start ] .
[ String.contains s c ] is equivalent to
[ String.contains_from s 0 c ] .
Raise [ Invalid_argument ] if [ start ] is not a valid position in [ s ] .
appears in [s] after position [start].
[String.contains s c] is equivalent to
[String.contains_from s 0 c].
Raise [Invalid_argument] if [start] is not a valid position in [s]. *)
val rcontains_from : string -> int -> char -> bool
val uppercase : string -> string
[@@ocaml.deprecated "Use String.uppercase_ascii instead."]
val lowercase : string -> string
[@@ocaml.deprecated "Use String.lowercase_ascii instead."]
val capitalize : string -> string
[@@ocaml.deprecated "Use String.capitalize_ascii instead."]
* Return a copy of the argument , with the first character set to uppercase ,
using the ISO Latin-1 ( 8859 - 1 ) character set ..
@deprecated Functions operating on Latin-1 character set are deprecated .
using the ISO Latin-1 (8859-1) character set..
@deprecated Functions operating on Latin-1 character set are deprecated. *)
val uncapitalize : string -> string
[@@ocaml.deprecated "Use String.uncapitalize_ascii instead."]
* Return a copy of the argument , with the first character set to lowercase ,
using the ISO Latin-1 ( 8859 - 1 ) character set ..
@deprecated Functions operating on Latin-1 character set are deprecated .
using the ISO Latin-1 (8859-1) character set..
@deprecated Functions operating on Latin-1 character set are deprecated. *)
val uppercase_ascii : string -> string
* Return a copy of the argument , with all lowercase letters
translated to uppercase , using the US - ASCII character set .
@since 4.03.0
translated to uppercase, using the US-ASCII character set.
@since 4.03.0 *)
val lowercase_ascii : string -> string
* Return a copy of the argument , with all uppercase letters
translated to lowercase , using the US - ASCII character set .
@since 4.03.0
translated to lowercase, using the US-ASCII character set.
@since 4.03.0 *)
val capitalize_ascii : string -> string
* Return a copy of the argument , with the first character set to uppercase ,
using the US - ASCII character set .
@since 4.03.0
using the US-ASCII character set.
@since 4.03.0 *)
val uncapitalize_ascii : string -> string
* Return a copy of the argument , with the first character set to lowercase ,
using the US - ASCII character set .
@since 4.03.0
using the US-ASCII character set.
@since 4.03.0 *)
type t = string
val compare: t -> t -> int
val equal: t -> t -> bool
* The equal function for strings .
@since 4.03.0
@since 4.03.0 *)
external unsafe_get : string -> int -> char = "%string_unsafe_get"
external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set"
[@@ocaml.deprecated]
external unsafe_blit :
string -> int -> bytes -> int -> int -> unit
= "caml_blit_string" [@@noalloc]
external unsafe_fill :
bytes -> int -> int -> char -> unit = "caml_fill_string" [@@noalloc]
[@@ocaml.deprecated]
|
cb21f8c2a89d9b96d2db4051f5a518df3a2ccb3633d09388ed300229c4519b37 | picnic/RelationExtraction | reltacs.ml | (****************************************************************************)
RelationExtraction - Extraction of inductive relations for Coq
(* *)
(* This program is free software: you can redistribute it and/or modify *)
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
(* (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
You should have received a copy of the GNU General Public License
(* along with this program. If not, see </>. *)
(* *)
Copyright 2012 CNAM - ENSIIE
< >
< >
< >
(****************************************************************************)
open Term
open Pattern
open Names
open Libnames
open Nametab
open Util
open Pp
open Declarations
open Pred
open Proof_scheme
open Coq_stuff
let debug_print_goals = false
let debug_print_tacs = false
(****************)
(* Proofs stuff *)
(****************)
(* A pattern to search in the proof goal. *)
type 'a goal_finder = identifier option -> constr -> 'a option
goal_iterator :
bool - > bool - > bool - > ' a goal_finder - > constr - > int - > ( int * ' a )
goal_iterator browses the goal and try to identify one part of the product
with f and return the f result and the position of the product part in the
goal .
The three boolean flags indicate if goal_iterator must call f on foralls ,
, and premisses .
bool -> bool -> bool -> 'a goal_finder -> constr -> int -> (int * 'a)
goal_iterator browses the goal and try to identify one part of the product
with f and return the f result and the position of the product part in the
goal.
The three boolean flags indicate if goal_iterator must call f on foralls,
letins, and premisses.
*)
(* TODO: check that forall term = type ? *)
let goal_iterator fa li pr f goal start =
let rec rec_it i term = match kind_of_term term with
| Prod (Name n, c, c_next) when (fa || pr) && i >= start &&
string_of_id n <> "H" (* H is rec hyp name *) ->
begin match f (Some n) c with
| Some res -> i, res
| None -> rec_it (i+1) c_next end
| Prod (Anonymous, c, c_next) when pr && i >= start ->
begin match f None c with
| Some res -> i, res
| None -> rec_it (i+1) c_next end
| Prod (_, _, c_next) -> rec_it (i+1) c_next
| LetIn (Name n, c, _, c_next) when li && i >= start ->
begin match f (Some n) c with
| Some res -> i, res
| None -> rec_it (i+1) c_next end
| LetIn (_, _, _, c_next) -> rec_it (i+1) c_next
| _ -> raise Not_found in
rec_it 1 goal
(* Hypothesis number in a goal. *)
let get_hyp_num goal =
let rec rec_ghn i term = match kind_of_term term with
| Prod (_, _, c_next) -> rec_ghn (i+1) c_next
| LetIn (_, _, _, c_next) -> rec_ghn (i+1) c_next
| _ -> i in
rec_ghn 0 goal
type hyp_finder = constr option -> constr -> constr
(* How to find a coq constr. It is either the constr itself or a place to find
it in an hypothesis. *)
type coq_constr_loc =
| CoqConstr of constr
| LocInHyp of string * hyp_finder
A coq tactic .
type tac_atom =
| INTRO of string
| INTROS of string list
| INTROSUNTIL of int (* intros until i *)
| REVERT of string list
| SYMMETRY of string
| SUBST of string
| APPLY of string
| APPLYIN of string * string
| EAPPLY of string
| APPLYPROP of string (* spec constr name *)
| APPLYPROPIN of string (* spec constr name *) * string
| APPLYIND of string (* fun name *)
| CHANGEV of string * string * coq_constr_loc
(* CHANGEV (h, v, c) : change v with c if h is v = c *)
| CHANGEC of string * coq_constr_loc * coq_constr_loc
CHANGEC ( h , cp , c ) : change cp with c if h is cp = c
| ASSERTEQUAL of string * string * coq_constr_loc * types
ASSERTEQUAL ( h , v , c , t ) : assert ( h : v = c ) if c has type t
| AUTO
(* Pretty printers. *)
let rec concat_list l sep = match l with
| [] -> ""
| [a] -> a
| a::tl -> a ^ sep ^ (concat_list tl sep)
let pp_coq_constr_loc ccl = match ccl with
| CoqConstr _ -> "[constr]"
| LocInHyp (h, _) -> "[in hyp: " ^ h ^ "]"
let pp_tac_atom ta = match ta with
| INTRO s -> "INTRO " ^ s
| INTROS sl -> "INTROS " ^ concat_list sl " "
| INTROSUNTIL i -> "INTROSUNTIL" ^ string_of_int i
| REVERT sl -> "REVERT " ^ concat_list sl " "
| SYMMETRY s -> "SYMMETRY " ^ s
| SUBST s -> "SUBST " ^ s
| APPLY s -> "APPLY " ^ s
| APPLYIN (s, h) -> "APPLY " ^ s ^ " IN " ^ h
| EAPPLY s -> "EAPPLY " ^ s
| APPLYPROP s -> "APPLYPROP " ^ s
| APPLYPROPIN (s, h) -> "APPLYPROP " ^ s ^ " IN " ^ h
| APPLYIND s -> "APPLYIND " ^ s
| CHANGEV (h, v, c) ->
"CHANGEV " ^ h ^ ": " ^ v ^ " -> " ^ pp_coq_constr_loc c
| CHANGEC (h, c1, c2) ->
"CHANGEC " ^ h ^ ": " ^ pp_coq_constr_loc c1 ^ " -> " ^ pp_coq_constr_loc c2
| ASSERTEQUAL (h, v, c, _) ->
"ASSERTEQUAL " ^ h ^ ": " ^ v ^ " = " ^ pp_coq_constr_loc c
| AUTO -> "AUTO"
let pp_tac_atom_list tal = concat_list (List.map pp_tac_atom tal) " ; "
(* Tactics, to be applied at each step of the proof. *)
type tac_info = {
ti_before_intros : tac_atom list;
ti_after_intros : tac_atom list;
ti_normal : tac_atom list;
ti_after_prop : tac_atom list;
}
let pp_tac_info ti =
"BI: " ^ pp_tac_atom_list ti.ti_before_intros ^ "\n" ^
"AI: " ^ pp_tac_atom_list ti.ti_after_intros ^ "\n" ^
"NN: " ^ pp_tac_atom_list ti.ti_normal ^ "\n" ^
"AP: " ^ pp_tac_atom_list ti.ti_after_prop ^ "\n"
A set of tactics to be applied in order to prove a subgoal .
type tacts =
| Prop_tacs of tac_info list * string
| Tac_list of tac_atom list
let pp_tacts tacts = match tacts with
| Prop_tacs (til, s) -> "Prop tacs (" ^ s ^ "):\n" ^
concat_list (List.map pp_tac_info til) "\n"
| Tac_list tal -> "List tacs:\n" ^ pp_tac_atom_list tal
(* The result returned by a prover. *)
type prover_result = {
pres_intros : string list;
pres_tacts : tacts;
}
let pp_prover_result pr =
"Prover result:\nIntros: " ^ concat_list pr.pres_intros " " ^
"\n" ^ pp_tacts pr.pres_tacts
(* The type of a prover. *)
type scheme_prover = {
prov_intro :
((htyp, henv) extract_env * ident) -> (htyp fix_term) proof_scheme -> tacts;
prov_branch : ((htyp, henv) extract_env * ident) ->
(htyp fix_term) ps_branch -> constr -> prover_result;
prov_concl :
((htyp, henv) extract_env * ident) -> (htyp fix_term) proof_scheme -> tacts;
}
Coq usefull functions .
let get_goal =
let goal = ref (mkRel 1) in
let tac = ( fun goal_s ->
goal := Goal.V82.concl (Evd.sig_sig goal_s) (Evd.sig_it goal_s);
Tacticals.tclIDTAC goal_s ) in
fun () -> (Pfedit.by tac; !goal)
(* return type : named_declaration list =
(identifier * constr option * types) list *)
let get_hyps =
let hyps = ref ([]) in
let tac = ( fun goal_s ->
hyps := Environ.named_context_of_val
(Goal.V82.hyps (Evd.sig_sig goal_s) (Evd.sig_it goal_s));
Tacticals.tclIDTAC goal_s ) in
fun () -> (Pfedit.by tac; !hyps)
let get_evarmap =
let evm = ref (Evd.empty) in
let tac = ( fun goal_s ->
evm := Evd.sig_sig goal_s;
Tacticals.tclIDTAC goal_s ) in
fun () -> (Pfedit.by tac; !evm)
let pat_from_constr constr =
let evm = get_evarmap () in
snd (pattern_of_constr evm constr)
let get_proof_from_tac (env, id) prover branch =
let term = get_goal () in
prover (env, id) branch term
let rec get_hyp_by_name hn hyps = match hyps with
| [] -> raise Not_found
| (id, topt, t)::hyps_tl -> if string_of_id id = hn then topt, t else
get_hyp_by_name hn hyps_tl
let constr_of_constr_loc cstr_loc = match cstr_loc with
| CoqConstr cstr -> cstr
| LocInHyp (hn, hyp_finder) -> let h_cstr_opt, h_cstr =
get_hyp_by_name hn (get_hyps ()) in
hyp_finder h_cstr_opt h_cstr
Makes real Coq tactics and applies them .
let rec build_tac_atom ta = match ta with
| INTRO str ->
if debug_print_tacs then Printf.eprintf "intro %s.\n" str
else ();
Tactics.intro_using (id_of_string str)
| INTROS strl ->
if debug_print_tacs then Printf.eprintf "intros %s.\n" (concat_list strl " ")
else ();
Tactics.intros_using (List.map id_of_string strl)
| INTROSUNTIL i ->
if debug_print_tacs then Printf.eprintf "intros until %d.\n" i
else ();
Tactics.intros_until_n_wored i
| REVERT (strl) ->
if debug_print_tacs && List.length strl > 0 then
Printf.eprintf "revert %s.\n" (concat_list strl " ")
else ();
Tactics.revert (List.map id_of_string strl)
| SYMMETRY str ->
if debug_print_tacs then Printf.eprintf "symmetry in %s.\n" str
else ();
Tactics.symmetry_in (id_of_string str)
| SUBST str ->
if debug_print_tacs then Printf.eprintf "subst %s.\n" str
else ();
Equality.subst [id_of_string str]
| APPLY str -> let cstr = find_coq_constr_s str in
if debug_print_tacs then Printf.eprintf "apply %s.\n" str
else ();
Tactics.apply cstr
| APPLYIN (str, h) -> let cstr = find_coq_constr_s str in
if debug_print_tacs then Printf.eprintf "apply %s in %s.\n" str h
else ();
Tactics.simple_apply_in (id_of_string h) cstr
| EAPPLY str -> let cstr = find_coq_constr_s str in
if debug_print_tacs then Printf.eprintf "eapply %s.\n" str
else ();
Tactics.eapply cstr
| APPLYPROP str -> let cstr = find_coq_constr_s str in
if debug_print_tacs then Printf.eprintf "apply %s; try assumption.\n" str
else ();
Tacticals.tclTHEN (Tactics.apply cstr)
(Tacticals.tclTRY Tactics.assumption)
| APPLYPROPIN (str, h) -> let cstr = find_coq_constr_s str in
if debug_print_tacs then
Printf.eprintf "apply %s in %s; try assumption.\n" str h
else ();
Tacticals.tclTHEN (Tactics.simple_apply_in (id_of_string h) cstr)
(Tacticals.tclTRY Tactics.assumption)
| APPLYIND str -> let ind_scheme = str ^ "_ind" in
build_tac_atom (APPLY ind_scheme)
| CHANGEC (h, cstr_pat, cloc) ->
let cstr_pat = constr_of_constr_loc cstr_pat in
let cstr = constr_of_constr_loc cloc in
let hyps_ids = List.map (fun (id, _, _) -> id) (get_hyps ()) in
let orig_hyp_id = id_of_string h in
let tac = Equality.replace cstr_pat cstr in
let t = List.fold_right (fun hid tac ->
if orig_hyp_id = hid then tac else
Tacticals.tclTHEN (Equality.replace_in hid cstr_pat cstr) tac
) hyps_ids tac in
let s = "replace (" ^ (pp_coq_constr cstr_pat) ^ ") with (" ^
(pp_coq_constr cstr) ^ ") in *" in
if debug_print_tacs then Printf.eprintf "%s.\n" s
else ();
t
| CHANGEV (h, v, cloc) ->
let cstr_pat = mkVar (id_of_string v) in
build_tac_atom (CHANGEC (h, CoqConstr cstr_pat, cloc))
| ASSERTEQUAL (h, v, cloc, t) ->
let cstr = constr_of_constr_loc cloc in
let eq = find_coq_constr_s "eq" in
let var = mkVar (id_of_string v) in
let assert_cstr = mkApp (eq, [|t; var; cstr|]) in
if debug_print_tacs then
Printf.eprintf "assert (%s : %s).\n" h (pp_coq_constr assert_cstr)
else ();
Tactics.assert_tac (Name (id_of_string h)) assert_cstr
| AUTO ->
if debug_print_tacs then Printf.eprintf "auto.\n"
else ();
Auto.default_auto
(* Proves a goal, with a given prover. *)
let make_proof (env, id) prover ps =
if debug_print_tacs then
let (fixfun, _) = extr_get_fixfun env id in
let fn = string_of_ident fixfun.fixfun_name in
let in_s = concat_list (List.map string_of_ident fixfun.fixfun_args) " " in
let lem = "Lemma " ^ fn ^ "_correct_printed : forall " ^ in_s ^ " po, " ^
fn ^ " " ^ in_s ^ " = po -> " ^ string_of_ident id ^ " " ^ in_s ^
" po." in
Printf.eprintf "\n\n\n%s\nProof.\n" lem
else ();
let intro = prover.prov_intro (env, id) ps in
let concl = prover.prov_concl (env, id) ps in
let prover = prover.prov_branch in
let rec apply_tacs tacs = match tacs with
| Prop_tacs _ -> assert false
| Tac_list (t::tl) ->
begin if debug_print_goals then
begin Printf.printf "\n\n%s\n\n" (pp_tac_atom t);
Vernacentries.print_subgoals () end
else () end;
Pfedit.by (build_tac_atom t); apply_tacs (Tac_list tl)
| Tac_list [] -> () in
apply_tacs intro;
List.iter (fun branch ->
if debug_print_goals then Vernacentries.print_subgoals ()
else ();
let proof = get_proof_from_tac (env, id) prover branch in
let intros_tac = Tac_list [INTROS proof.pres_intros] in
match proof.pres_tacts with
| Tac_list _ -> apply_tacs intros_tac;
apply_tacs proof.pres_tacts
| Prop_tacs (til, prop) -> let bint, aint, norm, apro =
List.fold_right (fun ti (bi, ai, n, ap) ->
ti.ti_before_intros::bi, ti.ti_after_intros::ai,
ti.ti_normal::n, ti.ti_after_prop::ap) til ([], [], [], []) in
let bi_tac = Tac_list (List.flatten bint) in
let ai_tac = Tac_list (List.flatten aint) in
let n_tac = Tac_list (List.flatten norm) in
let ap_tac = Tac_list (List.flatten apro) in
let prop_tac = Tac_list [APPLYPROP prop] in
apply_tacs bi_tac;
apply_tacs intros_tac;
apply_tacs ai_tac;
apply_tacs n_tac;
apply_tacs prop_tac;
apply_tacs ap_tac
) ps.scheme_branches;
apply_tacs concl;
if debug_print_tacs then
Printf.eprintf "Qed.\n"
else ()
(****************)
(* Goal finders *)
(****************)
Utils
let isEq constr =
if isInd constr then
let ind = destInd constr in
let _,oid = Inductive.lookup_mind_specif (Global.env ()) ind in
(string_of_id oid.mind_typename = "eq")
else false
(* Goal finders *)
let find_eq_get_sides = fun _ constr -> match kind_of_term constr with
| App (f, [|_;c1;c2|]) when isEq f -> Some (c1, c2)
| _ -> None
let find_let_in_cstr v = fun n cstr -> match n with
| Some n -> if v = string_of_id n then Some cstr else None
| None -> None
let find_fa_name = fun n _ -> match n with
| Some n -> Some (string_of_id n)
| None -> None
(***************)
(* Hyp finders *)
(***************)
let hyp_whole_hyp _ c = c
let hyp_eq_right _ c = match kind_of_term c with
| App (f, [|_;_;c|]) when isEq f -> c
| _ -> raise Not_found
let hyp_eq_left _ c = match kind_of_term c with
| App (f, [|_;c;_|]) when isEq f -> c
| _ -> raise Not_found
let hyp_def c _ = match c with | Some c -> c | _ -> raise Not_found
(***********)
Provers
(***********)
let mk_ti_bi tal = {
ti_before_intros = tal;
ti_after_intros = [];
ti_normal = [];
ti_after_prop = [];
}
let mk_ti_ai tal = {
ti_before_intros = [];
ti_after_intros = tal;
ti_normal = [];
ti_after_prop = [];
}
let mk_ti_n tal = {
ti_before_intros = [];
ti_after_intros = [];
ti_normal = tal;
ti_after_prop = [];
}
let mk_ti_ap tal = {
ti_before_intros = [];
ti_after_intros = [];
ti_normal = [];
ti_after_prop = tal;
}
let mk_ti_ai_n tal1 tal2 = {
ti_before_intros = [];
ti_after_intros = tal1;
ti_normal = tal2;
ti_after_prop = [];
}
(*********************************************************)
(* SIMPLE PROVER *)
(* - only partial mode *)
(* - only complete specifications *)
(* - no equalities, no linearization, *)
(* no logical connectors *)
(*********************************************************)
let simple_pc_intro (env, id) _ =
let f_name = string_of_ident (fst (extr_get_fixfun env id)).fixfun_name in
Tac_list [
(* intros predicate arguments *)
INTROSUNTIL 0;
intro H ( )
INTRO "H";
(* rewrite H (or subst H or change right with left) *)
SUBST "po";
apply ind scheme
APPLYIND f_name
]
let simple_pc_concl _ _ = Tac_list []
let list_pos l e =
let rec rec_pos l i = match l with
| [] -> raise Not_found
| e'::tl -> if e = e' then i else rec_pos tl (i+1) in
rec_pos l 0
let rec get_pmterm_name_order pm = match pm with
| PMTerm (_, Some n) -> [n]
| PMNot (pm, _) -> get_pmterm_name_order pm
| PMOr (pml, _) -> List.flatten (List.map get_pmterm_name_order pml)
| PMAnd (pml, _) -> List.flatten (List.map get_pmterm_name_order pml)
| PMChoice (pml, _) -> assert false
not imp yet , TODO : find one is used .
| _ -> []
let get_init_prem_order (env, id) prop_name =
let spec = extr_get_spec env id in
let prop = List.find (fun prop -> match prop.prop_name with
| Some pn -> pn = prop_name
| None -> false) spec.spec_props in
List.flatten (List.map get_pmterm_name_order prop.prop_prems)
let simple_pc_branch (env, id) branch goal =
let fun_name = string_of_ident (fst (extr_get_fixfun env id)).fixfun_name in
let prop_name = match branch.psb_prop_name with Some n -> n
| _ -> assert false in
let (hname_index, til, _, _, recvars) =
List.fold_left (fun (hname_index, til, pmn, last_i, recvars) (at, _) ->
let dep_pred, pmn = match at with
| (LetVar (_, (t, _), po) | CaseConstr ((t, _), _, _, po)) ->
let n = po.po_prem_name in if n = "" then None, pmn else
begin match pmn with | None ->
begin match t with
| FixFun(f, _) -> let f = string_of_ident f in
if f = fun_name then None, Some n
else Some f, Some n
| _ -> None, Some n
end
| Some pmn when n <> pmn ->
begin match t with
| FixFun(f, _) -> let f = string_of_ident f in
if f = fun_name then None, Some n
else Some f, Some n
| _ -> None, Some n
end
| _ -> None, pmn
end
| _ -> None, pmn in
if dep_pred <> None then
let dep_pred = match dep_pred with Some n -> n | _ -> assert false in
let hrec = fresh_string_id "HREC_" () in
let i, tacs, hn, rv = match at with
| LetVar (pi, (_, (_, Some t)), _) ->
let v = pi.pi_func_name in
let i, _ = goal_iterator false true false
(find_let_in_cstr v) goal (last_i+1) in
let hn = (*fresh_string_id "HLREC_" () in *) v in
i, [ASSERTEQUAL (hrec, v, LocInHyp (hn, hyp_def), t); AUTO;
SYMMETRY hrec], hn, [v,hrec]
| CaseConstr (_, cstr_name, pil, _) ->
let i, (_, _) = goal_iterator false false true
find_eq_get_sides goal (last_i+1) in
i, [], hrec, [] in
let ti = mk_ti_n (tacs@[APPLYPROPIN (dep_pred ^ "_correct", hrec)]) in
((i, hn)::hname_index, ti::til, pmn, i, recvars@rv)
else match at with
| LetVar (pi, (_, (_, Some t)), _)
| LetDum (pi, (_, (_, Some t))) ->
let v = pi.pi_func_name in
let i, _ = goal_iterator false true false
(find_let_in_cstr v) goal (last_i+1) in
fresh_string_id " HLV _ " ( )
let eqhname = hname ^ "EQ" in
let ti = mk_ti_ai_n
[ASSERTEQUAL (eqhname, v, LocInHyp (hname, hyp_def), t); AUTO]
[CHANGEV (eqhname, v, LocInHyp (eqhname, hyp_eq_right))] in
((i, hname)::hname_index, til@[ti], pmn, i, recvars)
| CaseConstr (mt, cstr_name, pil, _) ->
let i, (c1, _) = goal_iterator false false true
find_eq_get_sides goal (last_i+1) in
let hname = fresh_string_id "HCC_" () in
let ti = mk_ti_n [CHANGEC (hname, LocInHyp (hname, hyp_eq_left),
LocInHyp (hname, hyp_eq_right))] in
((i, hname)::hname_index, til@[ti], pmn, i, recvars)
| CaseDum _ ->
let i, _ = goal_iterator false false true
find_eq_get_sides goal (last_i+1) in
let hname = fresh_string_id "HCD_" () in
((i, hname)::hname_index, til, pmn, i, recvars)
old code for LetDums , they are now processed as ...
| LetDum ( pi , _ ) - >
let v = pi.pi_func_name in
let i , _ = goal_iterator false true false
( find_let_in_cstr v ) goal ( last_i+1 ) in
let = fresh_string_id " HLD _ " ( ) in
( ( i , hname)::hname_index , til , , i , )
let v = pi.pi_func_name in
let i, _ = goal_iterator false true false
(find_let_in_cstr v) goal (last_i+1) in
let hname = fresh_string_id "HLD_" () in
((i, hname)::hname_index, til, pmn, i, recvars) *)
| _ -> (hname_index, til, pmn, last_i, recvars)
) ([], [], None, 0, []) branch.psb_branch in
let nb_h = get_hyp_num goal in
let hnames, p_h = let rec mk_hnames hnames p_h nb_h =
if nb_h = 0 then hnames, p_h else
let hn, p_h = try List.assoc nb_h hname_index, p_h
with Not_found -> try let i, n =
goal_iterator true false false find_fa_name goal nb_h in
if i = nb_h then n , p_h
(* modified for proof printing. TODO: find a solution to keep real names? *)
(*new*) if i = nb_h then fresh_string_id "na_" (), p_h
else raise Not_found
with Not_found -> let n = fresh_string_id "HREC_" () in n, n::p_h in
(mk_hnames (hn::hnames) p_h (nb_h-1)) in mk_hnames [] [] nb_h in
new p_h version
let p_h = List.filter (fun hn -> try String.sub hn 0 5 = "HREC_" ||
List.mem_assoc hn recvars with _ -> false) hnames in
let p_h = List.map (fun hn -> if List.mem_assoc hn recvars then
List.assoc hn recvars else hn) p_h in
let get_branch_prem_order atl = List.fold_right (fun (at, _) (pml, ono) ->
let hno = match at with
| LetVar (_, _, po) -> let n = po.po_prem_name in
if n = "" then None else Some n
| CaseConstr (_, _, _, po) -> let n = po.po_prem_name in
if n = "" then None else Some n
| _ -> None in
match hno with
| Some hn -> if ono = hno then (pml, ono) else (hn::pml, hno)
| None -> (pml, ono)
) atl ([], None) in
let premisse_reorder p_h =
let prop_name =
match branch.psb_prop_name with Some n -> n | _ -> assert false in
let init_order =
get_init_prem_order (env, id) (ident_of_string prop_name) in
let init_order = List.map string_of_ident init_order in
let branch_order, _ = get_branch_prem_order branch.psb_branch in
let rec order_prem pml init branch = match init with
| [] -> []
| i::init -> (List.nth pml (list_pos branch i))::
(order_prem pml init branch)
in
(*TODO: find all the HRECs !*)
order_prem p_h init_order branch_order
in
let p_h = premisse_reorder p_h in
let ti_revert_rec = mk_ti_n [REVERT (List.rev p_h)] in
{ pres_intros = hnames;
pres_tacts = Prop_tacs (til@[ti_revert_rec], prop_name);
}
let simple_pc = {
prov_intro = simple_pc_intro;
prov_branch = simple_pc_branch;
prov_concl = simple_pc_concl;
}
| null | https://raw.githubusercontent.com/picnic/RelationExtraction/a4cee37d0a8e5f0eff2e010e6305e037aa0d2564/reltacs.ml | ocaml | **************************************************************************
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
**************************************************************************
**************
Proofs stuff
**************
A pattern to search in the proof goal.
TODO: check that forall term = type ?
H is rec hyp name
Hypothesis number in a goal.
How to find a coq constr. It is either the constr itself or a place to find
it in an hypothesis.
intros until i
spec constr name
spec constr name
fun name
CHANGEV (h, v, c) : change v with c if h is v = c
Pretty printers.
Tactics, to be applied at each step of the proof.
The result returned by a prover.
The type of a prover.
return type : named_declaration list =
(identifier * constr option * types) list
Proves a goal, with a given prover.
**************
Goal finders
**************
Goal finders
*************
Hyp finders
*************
*********
*********
*******************************************************
SIMPLE PROVER
- only partial mode
- only complete specifications
- no equalities, no linearization,
no logical connectors
*******************************************************
intros predicate arguments
rewrite H (or subst H or change right with left)
fresh_string_id "HLREC_" () in
modified for proof printing. TODO: find a solution to keep real names?
new
TODO: find all the HRECs ! | RelationExtraction - Extraction of inductive relations for Coq
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
Copyright 2012 CNAM - ENSIIE
< >
< >
< >
open Term
open Pattern
open Names
open Libnames
open Nametab
open Util
open Pp
open Declarations
open Pred
open Proof_scheme
open Coq_stuff
let debug_print_goals = false
let debug_print_tacs = false
type 'a goal_finder = identifier option -> constr -> 'a option
goal_iterator :
bool - > bool - > bool - > ' a goal_finder - > constr - > int - > ( int * ' a )
goal_iterator browses the goal and try to identify one part of the product
with f and return the f result and the position of the product part in the
goal .
The three boolean flags indicate if goal_iterator must call f on foralls ,
, and premisses .
bool -> bool -> bool -> 'a goal_finder -> constr -> int -> (int * 'a)
goal_iterator browses the goal and try to identify one part of the product
with f and return the f result and the position of the product part in the
goal.
The three boolean flags indicate if goal_iterator must call f on foralls,
letins, and premisses.
*)
let goal_iterator fa li pr f goal start =
let rec rec_it i term = match kind_of_term term with
| Prod (Name n, c, c_next) when (fa || pr) && i >= start &&
begin match f (Some n) c with
| Some res -> i, res
| None -> rec_it (i+1) c_next end
| Prod (Anonymous, c, c_next) when pr && i >= start ->
begin match f None c with
| Some res -> i, res
| None -> rec_it (i+1) c_next end
| Prod (_, _, c_next) -> rec_it (i+1) c_next
| LetIn (Name n, c, _, c_next) when li && i >= start ->
begin match f (Some n) c with
| Some res -> i, res
| None -> rec_it (i+1) c_next end
| LetIn (_, _, _, c_next) -> rec_it (i+1) c_next
| _ -> raise Not_found in
rec_it 1 goal
let get_hyp_num goal =
let rec rec_ghn i term = match kind_of_term term with
| Prod (_, _, c_next) -> rec_ghn (i+1) c_next
| LetIn (_, _, _, c_next) -> rec_ghn (i+1) c_next
| _ -> i in
rec_ghn 0 goal
type hyp_finder = constr option -> constr -> constr
type coq_constr_loc =
| CoqConstr of constr
| LocInHyp of string * hyp_finder
A coq tactic .
type tac_atom =
| INTRO of string
| INTROS of string list
| REVERT of string list
| SYMMETRY of string
| SUBST of string
| APPLY of string
| APPLYIN of string * string
| EAPPLY of string
| CHANGEV of string * string * coq_constr_loc
| CHANGEC of string * coq_constr_loc * coq_constr_loc
CHANGEC ( h , cp , c ) : change cp with c if h is cp = c
| ASSERTEQUAL of string * string * coq_constr_loc * types
ASSERTEQUAL ( h , v , c , t ) : assert ( h : v = c ) if c has type t
| AUTO
let rec concat_list l sep = match l with
| [] -> ""
| [a] -> a
| a::tl -> a ^ sep ^ (concat_list tl sep)
let pp_coq_constr_loc ccl = match ccl with
| CoqConstr _ -> "[constr]"
| LocInHyp (h, _) -> "[in hyp: " ^ h ^ "]"
let pp_tac_atom ta = match ta with
| INTRO s -> "INTRO " ^ s
| INTROS sl -> "INTROS " ^ concat_list sl " "
| INTROSUNTIL i -> "INTROSUNTIL" ^ string_of_int i
| REVERT sl -> "REVERT " ^ concat_list sl " "
| SYMMETRY s -> "SYMMETRY " ^ s
| SUBST s -> "SUBST " ^ s
| APPLY s -> "APPLY " ^ s
| APPLYIN (s, h) -> "APPLY " ^ s ^ " IN " ^ h
| EAPPLY s -> "EAPPLY " ^ s
| APPLYPROP s -> "APPLYPROP " ^ s
| APPLYPROPIN (s, h) -> "APPLYPROP " ^ s ^ " IN " ^ h
| APPLYIND s -> "APPLYIND " ^ s
| CHANGEV (h, v, c) ->
"CHANGEV " ^ h ^ ": " ^ v ^ " -> " ^ pp_coq_constr_loc c
| CHANGEC (h, c1, c2) ->
"CHANGEC " ^ h ^ ": " ^ pp_coq_constr_loc c1 ^ " -> " ^ pp_coq_constr_loc c2
| ASSERTEQUAL (h, v, c, _) ->
"ASSERTEQUAL " ^ h ^ ": " ^ v ^ " = " ^ pp_coq_constr_loc c
| AUTO -> "AUTO"
let pp_tac_atom_list tal = concat_list (List.map pp_tac_atom tal) " ; "
type tac_info = {
ti_before_intros : tac_atom list;
ti_after_intros : tac_atom list;
ti_normal : tac_atom list;
ti_after_prop : tac_atom list;
}
let pp_tac_info ti =
"BI: " ^ pp_tac_atom_list ti.ti_before_intros ^ "\n" ^
"AI: " ^ pp_tac_atom_list ti.ti_after_intros ^ "\n" ^
"NN: " ^ pp_tac_atom_list ti.ti_normal ^ "\n" ^
"AP: " ^ pp_tac_atom_list ti.ti_after_prop ^ "\n"
A set of tactics to be applied in order to prove a subgoal .
type tacts =
| Prop_tacs of tac_info list * string
| Tac_list of tac_atom list
let pp_tacts tacts = match tacts with
| Prop_tacs (til, s) -> "Prop tacs (" ^ s ^ "):\n" ^
concat_list (List.map pp_tac_info til) "\n"
| Tac_list tal -> "List tacs:\n" ^ pp_tac_atom_list tal
type prover_result = {
pres_intros : string list;
pres_tacts : tacts;
}
let pp_prover_result pr =
"Prover result:\nIntros: " ^ concat_list pr.pres_intros " " ^
"\n" ^ pp_tacts pr.pres_tacts
type scheme_prover = {
prov_intro :
((htyp, henv) extract_env * ident) -> (htyp fix_term) proof_scheme -> tacts;
prov_branch : ((htyp, henv) extract_env * ident) ->
(htyp fix_term) ps_branch -> constr -> prover_result;
prov_concl :
((htyp, henv) extract_env * ident) -> (htyp fix_term) proof_scheme -> tacts;
}
Coq usefull functions .
let get_goal =
let goal = ref (mkRel 1) in
let tac = ( fun goal_s ->
goal := Goal.V82.concl (Evd.sig_sig goal_s) (Evd.sig_it goal_s);
Tacticals.tclIDTAC goal_s ) in
fun () -> (Pfedit.by tac; !goal)
let get_hyps =
let hyps = ref ([]) in
let tac = ( fun goal_s ->
hyps := Environ.named_context_of_val
(Goal.V82.hyps (Evd.sig_sig goal_s) (Evd.sig_it goal_s));
Tacticals.tclIDTAC goal_s ) in
fun () -> (Pfedit.by tac; !hyps)
let get_evarmap =
let evm = ref (Evd.empty) in
let tac = ( fun goal_s ->
evm := Evd.sig_sig goal_s;
Tacticals.tclIDTAC goal_s ) in
fun () -> (Pfedit.by tac; !evm)
let pat_from_constr constr =
let evm = get_evarmap () in
snd (pattern_of_constr evm constr)
let get_proof_from_tac (env, id) prover branch =
let term = get_goal () in
prover (env, id) branch term
let rec get_hyp_by_name hn hyps = match hyps with
| [] -> raise Not_found
| (id, topt, t)::hyps_tl -> if string_of_id id = hn then topt, t else
get_hyp_by_name hn hyps_tl
let constr_of_constr_loc cstr_loc = match cstr_loc with
| CoqConstr cstr -> cstr
| LocInHyp (hn, hyp_finder) -> let h_cstr_opt, h_cstr =
get_hyp_by_name hn (get_hyps ()) in
hyp_finder h_cstr_opt h_cstr
Makes real Coq tactics and applies them .
let rec build_tac_atom ta = match ta with
| INTRO str ->
if debug_print_tacs then Printf.eprintf "intro %s.\n" str
else ();
Tactics.intro_using (id_of_string str)
| INTROS strl ->
if debug_print_tacs then Printf.eprintf "intros %s.\n" (concat_list strl " ")
else ();
Tactics.intros_using (List.map id_of_string strl)
| INTROSUNTIL i ->
if debug_print_tacs then Printf.eprintf "intros until %d.\n" i
else ();
Tactics.intros_until_n_wored i
| REVERT (strl) ->
if debug_print_tacs && List.length strl > 0 then
Printf.eprintf "revert %s.\n" (concat_list strl " ")
else ();
Tactics.revert (List.map id_of_string strl)
| SYMMETRY str ->
if debug_print_tacs then Printf.eprintf "symmetry in %s.\n" str
else ();
Tactics.symmetry_in (id_of_string str)
| SUBST str ->
if debug_print_tacs then Printf.eprintf "subst %s.\n" str
else ();
Equality.subst [id_of_string str]
| APPLY str -> let cstr = find_coq_constr_s str in
if debug_print_tacs then Printf.eprintf "apply %s.\n" str
else ();
Tactics.apply cstr
| APPLYIN (str, h) -> let cstr = find_coq_constr_s str in
if debug_print_tacs then Printf.eprintf "apply %s in %s.\n" str h
else ();
Tactics.simple_apply_in (id_of_string h) cstr
| EAPPLY str -> let cstr = find_coq_constr_s str in
if debug_print_tacs then Printf.eprintf "eapply %s.\n" str
else ();
Tactics.eapply cstr
| APPLYPROP str -> let cstr = find_coq_constr_s str in
if debug_print_tacs then Printf.eprintf "apply %s; try assumption.\n" str
else ();
Tacticals.tclTHEN (Tactics.apply cstr)
(Tacticals.tclTRY Tactics.assumption)
| APPLYPROPIN (str, h) -> let cstr = find_coq_constr_s str in
if debug_print_tacs then
Printf.eprintf "apply %s in %s; try assumption.\n" str h
else ();
Tacticals.tclTHEN (Tactics.simple_apply_in (id_of_string h) cstr)
(Tacticals.tclTRY Tactics.assumption)
| APPLYIND str -> let ind_scheme = str ^ "_ind" in
build_tac_atom (APPLY ind_scheme)
| CHANGEC (h, cstr_pat, cloc) ->
let cstr_pat = constr_of_constr_loc cstr_pat in
let cstr = constr_of_constr_loc cloc in
let hyps_ids = List.map (fun (id, _, _) -> id) (get_hyps ()) in
let orig_hyp_id = id_of_string h in
let tac = Equality.replace cstr_pat cstr in
let t = List.fold_right (fun hid tac ->
if orig_hyp_id = hid then tac else
Tacticals.tclTHEN (Equality.replace_in hid cstr_pat cstr) tac
) hyps_ids tac in
let s = "replace (" ^ (pp_coq_constr cstr_pat) ^ ") with (" ^
(pp_coq_constr cstr) ^ ") in *" in
if debug_print_tacs then Printf.eprintf "%s.\n" s
else ();
t
| CHANGEV (h, v, cloc) ->
let cstr_pat = mkVar (id_of_string v) in
build_tac_atom (CHANGEC (h, CoqConstr cstr_pat, cloc))
| ASSERTEQUAL (h, v, cloc, t) ->
let cstr = constr_of_constr_loc cloc in
let eq = find_coq_constr_s "eq" in
let var = mkVar (id_of_string v) in
let assert_cstr = mkApp (eq, [|t; var; cstr|]) in
if debug_print_tacs then
Printf.eprintf "assert (%s : %s).\n" h (pp_coq_constr assert_cstr)
else ();
Tactics.assert_tac (Name (id_of_string h)) assert_cstr
| AUTO ->
if debug_print_tacs then Printf.eprintf "auto.\n"
else ();
Auto.default_auto
let make_proof (env, id) prover ps =
if debug_print_tacs then
let (fixfun, _) = extr_get_fixfun env id in
let fn = string_of_ident fixfun.fixfun_name in
let in_s = concat_list (List.map string_of_ident fixfun.fixfun_args) " " in
let lem = "Lemma " ^ fn ^ "_correct_printed : forall " ^ in_s ^ " po, " ^
fn ^ " " ^ in_s ^ " = po -> " ^ string_of_ident id ^ " " ^ in_s ^
" po." in
Printf.eprintf "\n\n\n%s\nProof.\n" lem
else ();
let intro = prover.prov_intro (env, id) ps in
let concl = prover.prov_concl (env, id) ps in
let prover = prover.prov_branch in
let rec apply_tacs tacs = match tacs with
| Prop_tacs _ -> assert false
| Tac_list (t::tl) ->
begin if debug_print_goals then
begin Printf.printf "\n\n%s\n\n" (pp_tac_atom t);
Vernacentries.print_subgoals () end
else () end;
Pfedit.by (build_tac_atom t); apply_tacs (Tac_list tl)
| Tac_list [] -> () in
apply_tacs intro;
List.iter (fun branch ->
if debug_print_goals then Vernacentries.print_subgoals ()
else ();
let proof = get_proof_from_tac (env, id) prover branch in
let intros_tac = Tac_list [INTROS proof.pres_intros] in
match proof.pres_tacts with
| Tac_list _ -> apply_tacs intros_tac;
apply_tacs proof.pres_tacts
| Prop_tacs (til, prop) -> let bint, aint, norm, apro =
List.fold_right (fun ti (bi, ai, n, ap) ->
ti.ti_before_intros::bi, ti.ti_after_intros::ai,
ti.ti_normal::n, ti.ti_after_prop::ap) til ([], [], [], []) in
let bi_tac = Tac_list (List.flatten bint) in
let ai_tac = Tac_list (List.flatten aint) in
let n_tac = Tac_list (List.flatten norm) in
let ap_tac = Tac_list (List.flatten apro) in
let prop_tac = Tac_list [APPLYPROP prop] in
apply_tacs bi_tac;
apply_tacs intros_tac;
apply_tacs ai_tac;
apply_tacs n_tac;
apply_tacs prop_tac;
apply_tacs ap_tac
) ps.scheme_branches;
apply_tacs concl;
if debug_print_tacs then
Printf.eprintf "Qed.\n"
else ()
Utils
let isEq constr =
if isInd constr then
let ind = destInd constr in
let _,oid = Inductive.lookup_mind_specif (Global.env ()) ind in
(string_of_id oid.mind_typename = "eq")
else false
let find_eq_get_sides = fun _ constr -> match kind_of_term constr with
| App (f, [|_;c1;c2|]) when isEq f -> Some (c1, c2)
| _ -> None
let find_let_in_cstr v = fun n cstr -> match n with
| Some n -> if v = string_of_id n then Some cstr else None
| None -> None
let find_fa_name = fun n _ -> match n with
| Some n -> Some (string_of_id n)
| None -> None
let hyp_whole_hyp _ c = c
let hyp_eq_right _ c = match kind_of_term c with
| App (f, [|_;_;c|]) when isEq f -> c
| _ -> raise Not_found
let hyp_eq_left _ c = match kind_of_term c with
| App (f, [|_;c;_|]) when isEq f -> c
| _ -> raise Not_found
let hyp_def c _ = match c with | Some c -> c | _ -> raise Not_found
Provers
let mk_ti_bi tal = {
ti_before_intros = tal;
ti_after_intros = [];
ti_normal = [];
ti_after_prop = [];
}
let mk_ti_ai tal = {
ti_before_intros = [];
ti_after_intros = tal;
ti_normal = [];
ti_after_prop = [];
}
let mk_ti_n tal = {
ti_before_intros = [];
ti_after_intros = [];
ti_normal = tal;
ti_after_prop = [];
}
let mk_ti_ap tal = {
ti_before_intros = [];
ti_after_intros = [];
ti_normal = [];
ti_after_prop = tal;
}
let mk_ti_ai_n tal1 tal2 = {
ti_before_intros = [];
ti_after_intros = tal1;
ti_normal = tal2;
ti_after_prop = [];
}
let simple_pc_intro (env, id) _ =
let f_name = string_of_ident (fst (extr_get_fixfun env id)).fixfun_name in
Tac_list [
INTROSUNTIL 0;
intro H ( )
INTRO "H";
SUBST "po";
apply ind scheme
APPLYIND f_name
]
let simple_pc_concl _ _ = Tac_list []
let list_pos l e =
let rec rec_pos l i = match l with
| [] -> raise Not_found
| e'::tl -> if e = e' then i else rec_pos tl (i+1) in
rec_pos l 0
let rec get_pmterm_name_order pm = match pm with
| PMTerm (_, Some n) -> [n]
| PMNot (pm, _) -> get_pmterm_name_order pm
| PMOr (pml, _) -> List.flatten (List.map get_pmterm_name_order pml)
| PMAnd (pml, _) -> List.flatten (List.map get_pmterm_name_order pml)
| PMChoice (pml, _) -> assert false
not imp yet , TODO : find one is used .
| _ -> []
let get_init_prem_order (env, id) prop_name =
let spec = extr_get_spec env id in
let prop = List.find (fun prop -> match prop.prop_name with
| Some pn -> pn = prop_name
| None -> false) spec.spec_props in
List.flatten (List.map get_pmterm_name_order prop.prop_prems)
let simple_pc_branch (env, id) branch goal =
let fun_name = string_of_ident (fst (extr_get_fixfun env id)).fixfun_name in
let prop_name = match branch.psb_prop_name with Some n -> n
| _ -> assert false in
let (hname_index, til, _, _, recvars) =
List.fold_left (fun (hname_index, til, pmn, last_i, recvars) (at, _) ->
let dep_pred, pmn = match at with
| (LetVar (_, (t, _), po) | CaseConstr ((t, _), _, _, po)) ->
let n = po.po_prem_name in if n = "" then None, pmn else
begin match pmn with | None ->
begin match t with
| FixFun(f, _) -> let f = string_of_ident f in
if f = fun_name then None, Some n
else Some f, Some n
| _ -> None, Some n
end
| Some pmn when n <> pmn ->
begin match t with
| FixFun(f, _) -> let f = string_of_ident f in
if f = fun_name then None, Some n
else Some f, Some n
| _ -> None, Some n
end
| _ -> None, pmn
end
| _ -> None, pmn in
if dep_pred <> None then
let dep_pred = match dep_pred with Some n -> n | _ -> assert false in
let hrec = fresh_string_id "HREC_" () in
let i, tacs, hn, rv = match at with
| LetVar (pi, (_, (_, Some t)), _) ->
let v = pi.pi_func_name in
let i, _ = goal_iterator false true false
(find_let_in_cstr v) goal (last_i+1) in
i, [ASSERTEQUAL (hrec, v, LocInHyp (hn, hyp_def), t); AUTO;
SYMMETRY hrec], hn, [v,hrec]
| CaseConstr (_, cstr_name, pil, _) ->
let i, (_, _) = goal_iterator false false true
find_eq_get_sides goal (last_i+1) in
i, [], hrec, [] in
let ti = mk_ti_n (tacs@[APPLYPROPIN (dep_pred ^ "_correct", hrec)]) in
((i, hn)::hname_index, ti::til, pmn, i, recvars@rv)
else match at with
| LetVar (pi, (_, (_, Some t)), _)
| LetDum (pi, (_, (_, Some t))) ->
let v = pi.pi_func_name in
let i, _ = goal_iterator false true false
(find_let_in_cstr v) goal (last_i+1) in
fresh_string_id " HLV _ " ( )
let eqhname = hname ^ "EQ" in
let ti = mk_ti_ai_n
[ASSERTEQUAL (eqhname, v, LocInHyp (hname, hyp_def), t); AUTO]
[CHANGEV (eqhname, v, LocInHyp (eqhname, hyp_eq_right))] in
((i, hname)::hname_index, til@[ti], pmn, i, recvars)
| CaseConstr (mt, cstr_name, pil, _) ->
let i, (c1, _) = goal_iterator false false true
find_eq_get_sides goal (last_i+1) in
let hname = fresh_string_id "HCC_" () in
let ti = mk_ti_n [CHANGEC (hname, LocInHyp (hname, hyp_eq_left),
LocInHyp (hname, hyp_eq_right))] in
((i, hname)::hname_index, til@[ti], pmn, i, recvars)
| CaseDum _ ->
let i, _ = goal_iterator false false true
find_eq_get_sides goal (last_i+1) in
let hname = fresh_string_id "HCD_" () in
((i, hname)::hname_index, til, pmn, i, recvars)
old code for LetDums , they are now processed as ...
| LetDum ( pi , _ ) - >
let v = pi.pi_func_name in
let i , _ = goal_iterator false true false
( find_let_in_cstr v ) goal ( last_i+1 ) in
let = fresh_string_id " HLD _ " ( ) in
( ( i , hname)::hname_index , til , , i , )
let v = pi.pi_func_name in
let i, _ = goal_iterator false true false
(find_let_in_cstr v) goal (last_i+1) in
let hname = fresh_string_id "HLD_" () in
((i, hname)::hname_index, til, pmn, i, recvars) *)
| _ -> (hname_index, til, pmn, last_i, recvars)
) ([], [], None, 0, []) branch.psb_branch in
let nb_h = get_hyp_num goal in
let hnames, p_h = let rec mk_hnames hnames p_h nb_h =
if nb_h = 0 then hnames, p_h else
let hn, p_h = try List.assoc nb_h hname_index, p_h
with Not_found -> try let i, n =
goal_iterator true false false find_fa_name goal nb_h in
if i = nb_h then n , p_h
else raise Not_found
with Not_found -> let n = fresh_string_id "HREC_" () in n, n::p_h in
(mk_hnames (hn::hnames) p_h (nb_h-1)) in mk_hnames [] [] nb_h in
new p_h version
let p_h = List.filter (fun hn -> try String.sub hn 0 5 = "HREC_" ||
List.mem_assoc hn recvars with _ -> false) hnames in
let p_h = List.map (fun hn -> if List.mem_assoc hn recvars then
List.assoc hn recvars else hn) p_h in
let get_branch_prem_order atl = List.fold_right (fun (at, _) (pml, ono) ->
let hno = match at with
| LetVar (_, _, po) -> let n = po.po_prem_name in
if n = "" then None else Some n
| CaseConstr (_, _, _, po) -> let n = po.po_prem_name in
if n = "" then None else Some n
| _ -> None in
match hno with
| Some hn -> if ono = hno then (pml, ono) else (hn::pml, hno)
| None -> (pml, ono)
) atl ([], None) in
let premisse_reorder p_h =
let prop_name =
match branch.psb_prop_name with Some n -> n | _ -> assert false in
let init_order =
get_init_prem_order (env, id) (ident_of_string prop_name) in
let init_order = List.map string_of_ident init_order in
let branch_order, _ = get_branch_prem_order branch.psb_branch in
let rec order_prem pml init branch = match init with
| [] -> []
| i::init -> (List.nth pml (list_pos branch i))::
(order_prem pml init branch)
in
order_prem p_h init_order branch_order
in
let p_h = premisse_reorder p_h in
let ti_revert_rec = mk_ti_n [REVERT (List.rev p_h)] in
{ pres_intros = hnames;
pres_tacts = Prop_tacs (til@[ti_revert_rec], prop_name);
}
let simple_pc = {
prov_intro = simple_pc_intro;
prov_branch = simple_pc_branch;
prov_concl = simple_pc_concl;
}
|
2526deb46b95936165bbc7e5b0cba0a98e107d8fa0f2466e53628238a92c5cb5 | alonsodomin/groot | Types.hs | {-# LANGUAGE OverloadedStrings #-}
module Test.Groot.Types
( describeTypes
) where
import Data.Attoparsec.Text
import Data.Either
import qualified Data.Text as T
import Data.Text.Arbitrary
import Network.AWS.Types
import Test.Hspec
import Test.QuickCheck
import Groot.Internal.Data.Text
import Groot.Types
-- Arbitrary instances
instance Arbitrary ServiceId where
arbitrary = arbitraryBoundedEnum
instance Arbitrary AccountId where
arbitrary = AccountId . T.pack <$> listOf1 (elements ['0'..'9'])
instance Arbitrary Region where
arbitrary = arbitraryBoundedEnum
instance Arbitrary a => Arbitrary (Arn a) where
arbitrary = Arn <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
arnParsePreservation :: (FromText a, ToText a, Eq a) => Arn a -> Bool
arnParsePreservation arn = parseOnly parser (toText arn) == Right arn
DummyArnPath to verify basic ARN parsing
newtype DummyArnPath = DummyArnPath Text
deriving (Eq, Show)
instance FromText DummyArnPath where
parser = DummyArnPath <$> takeText
instance ToText DummyArnPath where
toText (DummyArnPath path) = path
type DummyArn = Arn DummyArnPath
instance Arbitrary DummyArnPath where
arbitrary = DummyArnPath <$> arbitrary
quickCheckDummyArn =
quickCheck $ \x -> arnParsePreservation (x :: DummyArn)
describeARN :: IO ()
describeARN = hspec $ do
describe "ARN" $ do
it "parses a valid ARN" $ do
let validArn = "arn:aws:ecs:eu-west-1:340721489904:container-instance/b7e184d6-5b5a-4fa8-8fd3-27bd2c4b0988"
let expectedARN = Arn ECS (Just Ireland) (AccountId "340721489904") (DummyArnPath "container-instance/b7e184d6-5b5a-4fa8-8fd3-27bd2c4b0988")
parseOnly parser validArn `shouldBe` (Right expectedARN)
it "parses arns without region" $ do
let givenArn = "arn:aws:iam::340721489904:role/arole"
let expected = Arn IAM Nothing (AccountId "340721489904") (RoleArnPath "arole")
parseOnly parser givenArn `shouldBe` (Right expected)
it "fails to parse non-ARNs" $ do
let invalidArn = "this is not an ARN"
parseOnly (parser :: Parser DummyArn) invalidArn `shouldSatisfy` isLeft
it "renders as an URN" $ do
let arn = Arn EC2 (Just Oregon) (AccountId "340721489904") (DummyArnPath "instance/b7e184d6-5b5a-4fa8-8fd3-27bd2c4b0988")
let expected = "arn:aws:ec2:us-west-2:340721489904:instance/b7e184d6-5b5a-4fa8-8fd3-27bd2c4b0988"
showText arn `shouldBe` expected
describeAmi :: IO ()
describeAmi = hspec $ do
describe "AMI" $ do
it "parses an AMI string" $ do
let validAMI = "ami-78328334"
let expectedAMI = Ami "78328334"
parseOnly parser validAMI `shouldBe` (Right expectedAMI)
it "fails to parse non-AMIs" $ do
let invalidAmi = "this is not an AMI"
parseOnly (parser :: Parser Ami) invalidAmi `shouldSatisfy` isLeft
it "renders AMI as a string" $ do
let ami = Ami "0dj9393rj"
let expected = "ami-0dj9393rj"
showText ami `shouldBe` expected
describeBaseTypes :: IO ()
describeBaseTypes = describeARN *> describeAmi *> quickCheckDummyArn
instance Arbitrary ClusterName where
arbitrary = ClusterName <$> arbitrary
instance Arbitrary ClusterArnPath where
arbitrary = ClusterArnPath <$> arbitrary
quickCheckClusterArn :: IO ()
quickCheckClusterArn = quickCheck $ \x -> arnParsePreservation (x :: ClusterArn)
describeClusterTypes :: IO ()
describeClusterTypes = quickCheckClusterArn
describeTypes :: IO ()
describeTypes = describeARN *> describeAmi *> quickCheckDummyArn *> describeClusterTypes
| null | https://raw.githubusercontent.com/alonsodomin/groot/040215db2797bef27b1c336ea826a58ddd45f8de/test/Test/Groot/Types.hs | haskell | # LANGUAGE OverloadedStrings #
Arbitrary instances |
module Test.Groot.Types
( describeTypes
) where
import Data.Attoparsec.Text
import Data.Either
import qualified Data.Text as T
import Data.Text.Arbitrary
import Network.AWS.Types
import Test.Hspec
import Test.QuickCheck
import Groot.Internal.Data.Text
import Groot.Types
instance Arbitrary ServiceId where
arbitrary = arbitraryBoundedEnum
instance Arbitrary AccountId where
arbitrary = AccountId . T.pack <$> listOf1 (elements ['0'..'9'])
instance Arbitrary Region where
arbitrary = arbitraryBoundedEnum
instance Arbitrary a => Arbitrary (Arn a) where
arbitrary = Arn <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
arnParsePreservation :: (FromText a, ToText a, Eq a) => Arn a -> Bool
arnParsePreservation arn = parseOnly parser (toText arn) == Right arn
DummyArnPath to verify basic ARN parsing
newtype DummyArnPath = DummyArnPath Text
deriving (Eq, Show)
instance FromText DummyArnPath where
parser = DummyArnPath <$> takeText
instance ToText DummyArnPath where
toText (DummyArnPath path) = path
type DummyArn = Arn DummyArnPath
instance Arbitrary DummyArnPath where
arbitrary = DummyArnPath <$> arbitrary
quickCheckDummyArn =
quickCheck $ \x -> arnParsePreservation (x :: DummyArn)
describeARN :: IO ()
describeARN = hspec $ do
describe "ARN" $ do
it "parses a valid ARN" $ do
let validArn = "arn:aws:ecs:eu-west-1:340721489904:container-instance/b7e184d6-5b5a-4fa8-8fd3-27bd2c4b0988"
let expectedARN = Arn ECS (Just Ireland) (AccountId "340721489904") (DummyArnPath "container-instance/b7e184d6-5b5a-4fa8-8fd3-27bd2c4b0988")
parseOnly parser validArn `shouldBe` (Right expectedARN)
it "parses arns without region" $ do
let givenArn = "arn:aws:iam::340721489904:role/arole"
let expected = Arn IAM Nothing (AccountId "340721489904") (RoleArnPath "arole")
parseOnly parser givenArn `shouldBe` (Right expected)
it "fails to parse non-ARNs" $ do
let invalidArn = "this is not an ARN"
parseOnly (parser :: Parser DummyArn) invalidArn `shouldSatisfy` isLeft
it "renders as an URN" $ do
let arn = Arn EC2 (Just Oregon) (AccountId "340721489904") (DummyArnPath "instance/b7e184d6-5b5a-4fa8-8fd3-27bd2c4b0988")
let expected = "arn:aws:ec2:us-west-2:340721489904:instance/b7e184d6-5b5a-4fa8-8fd3-27bd2c4b0988"
showText arn `shouldBe` expected
describeAmi :: IO ()
describeAmi = hspec $ do
describe "AMI" $ do
it "parses an AMI string" $ do
let validAMI = "ami-78328334"
let expectedAMI = Ami "78328334"
parseOnly parser validAMI `shouldBe` (Right expectedAMI)
it "fails to parse non-AMIs" $ do
let invalidAmi = "this is not an AMI"
parseOnly (parser :: Parser Ami) invalidAmi `shouldSatisfy` isLeft
it "renders AMI as a string" $ do
let ami = Ami "0dj9393rj"
let expected = "ami-0dj9393rj"
showText ami `shouldBe` expected
describeBaseTypes :: IO ()
describeBaseTypes = describeARN *> describeAmi *> quickCheckDummyArn
instance Arbitrary ClusterName where
arbitrary = ClusterName <$> arbitrary
instance Arbitrary ClusterArnPath where
arbitrary = ClusterArnPath <$> arbitrary
quickCheckClusterArn :: IO ()
quickCheckClusterArn = quickCheck $ \x -> arnParsePreservation (x :: ClusterArn)
describeClusterTypes :: IO ()
describeClusterTypes = quickCheckClusterArn
describeTypes :: IO ()
describeTypes = describeARN *> describeAmi *> quickCheckDummyArn *> describeClusterTypes
|
c78daef1f6d0cc64027a518afb972a70a37965e74b56e8195c639b68329e643d | maitria/avi | t_install.clj | (ns avi.t-install
(:require [midje.sweet :refer :all]
[avi.install :refer :all]))
(def test-prefix "/foo")
(defn build-command
[os-name]
(last (install-commands test-prefix {"os.name" os-name,
"java.home" "/java-home/jre"})))
(facts "about installing avi"
(facts "about installing on Mac OS X"
(fact "the JNI library name is libavi_jni.dylib"
(build-command "Mac OS X") => (contains ["-o" "/foo/lib/libavi_jni.dylib"]))
(fact "the build command has -lcurses"
(build-command "Mac OS X") => (contains ["-lcurses"]))
(fact "the build command does not have -ltinfo"
(build-command "Mac OS X") =not=> (contains ["-ltinfo"]))
(fact "the build command includes headers from JavaVM.framework"
(build-command "Mac OS X") => (contains ["-I/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers"])
(build-command "Mac OS X") => (contains ["-I/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers/darwin"]))
(fact "the build command specifies -shared"
(build-command "Mac OS X") => (contains ["-shared"]))
(fact "the build command does not have -fPIC"
(build-command "Mac OS X") =not=> (contains ["-fPIC"])))
(facts "about installing on Linux"
(fact "the JNI library name is libavi_jni.so"
(build-command "Linux") => (contains ["-o" "/foo/lib/libavi_jni.so"]))
(fact "the build command specifies -shared"
(build-command "Linux") => (contains ["-shared"]))
(fact "the build command specifies -ltinfo"
(build-command "Linux") => (contains ["-ltinfo"]))
(fact "the build command has -fPIC"
(build-command "Linux") => (contains ["-fPIC"]))
(fact "the build command contains headers from the java.home property"
(build-command "Linux") => (contains ["-I/java-home/jre/../include"])
(build-command "Linux") => (contains ["-I/java-home/jre/../include/linux"]))))
| null | https://raw.githubusercontent.com/maitria/avi/c641e9e32af4300ea7273a41e86b4f47d0f2c092/test/avi/t_install.clj | clojure | (ns avi.t-install
(:require [midje.sweet :refer :all]
[avi.install :refer :all]))
(def test-prefix "/foo")
(defn build-command
[os-name]
(last (install-commands test-prefix {"os.name" os-name,
"java.home" "/java-home/jre"})))
(facts "about installing avi"
(facts "about installing on Mac OS X"
(fact "the JNI library name is libavi_jni.dylib"
(build-command "Mac OS X") => (contains ["-o" "/foo/lib/libavi_jni.dylib"]))
(fact "the build command has -lcurses"
(build-command "Mac OS X") => (contains ["-lcurses"]))
(fact "the build command does not have -ltinfo"
(build-command "Mac OS X") =not=> (contains ["-ltinfo"]))
(fact "the build command includes headers from JavaVM.framework"
(build-command "Mac OS X") => (contains ["-I/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers"])
(build-command "Mac OS X") => (contains ["-I/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers/darwin"]))
(fact "the build command specifies -shared"
(build-command "Mac OS X") => (contains ["-shared"]))
(fact "the build command does not have -fPIC"
(build-command "Mac OS X") =not=> (contains ["-fPIC"])))
(facts "about installing on Linux"
(fact "the JNI library name is libavi_jni.so"
(build-command "Linux") => (contains ["-o" "/foo/lib/libavi_jni.so"]))
(fact "the build command specifies -shared"
(build-command "Linux") => (contains ["-shared"]))
(fact "the build command specifies -ltinfo"
(build-command "Linux") => (contains ["-ltinfo"]))
(fact "the build command has -fPIC"
(build-command "Linux") => (contains ["-fPIC"]))
(fact "the build command contains headers from the java.home property"
(build-command "Linux") => (contains ["-I/java-home/jre/../include"])
(build-command "Linux") => (contains ["-I/java-home/jre/../include/linux"]))))
| |
92660cc7b9931f17d5498b4ff987c01e34a5ae4202d3c37602330609e0d44516 | craff/simple_httpd | echo.ml |
module S = Simple_httpd
module H = S.Headers
let now_ = Unix.gettimeofday
(* util: a little middleware collecting statistics *)
let filter_stat () : S.filter * (unit -> string) =
let n_req = ref 0 in
let total_time_ = ref 0. in
let parse_time_ = ref 0. in
let build_time_ = ref 0. in
let m req =
incr n_req;
let t1 = S.Request.start_time req in
let t2 = now_ () in
(req, fun response ->
let t3 = now_ () in
total_time_ := !total_time_ +. (t3 -. t1);
parse_time_ := !parse_time_ +. (t2 -. t1);
build_time_ := !build_time_ +. (t3 -. t2);
response)
and get_stat () =
Printf.sprintf "%d requests (average response time: %.3fms = %.3fms + %.3fms)"
!n_req (!total_time_ /. float !n_req *. 1e3)
(!parse_time_ /. float !n_req *. 1e3)
(!build_time_ /. float !n_req *. 1e3)
in
m, get_stat
let () =
let addr = ref "127.0.0.1" in
let port = ref 8080 in
let j = ref 32 in
Arg.parse (Arg.align [
"--addr", Arg.Set_string addr, " set address";
"-a", Arg.Set_string addr, " set address";
"--port", Arg.Set_int port, " set port";
"-p", Arg.Set_int port, " set port";
"--log", Arg.Int (fun n -> S.set_log_lvl n), " set debug lvl";
"-j", Arg.Set_int j, " maximum number of connections";
]) (fun _ -> raise (Arg.Bad "")) "echo [option]*";
let listens = S.[{addr= !addr;port= !port;ssl=None}] in
let server = S.create ~listens ~max_connections:!j () in
let filter_stat, get_stats = filter_stat () in
let filter_zip =
Simple_httpd_camlzip.filter ~compress_above:1024 ~buf_size:(16*1024) ()
in
let filter = S.compose_cross filter_zip filter_stat in
(* say hello *)
S.add_route_handler ~meth:GET server ~filter
S.Route.(exact "hello" @/ string @/ return)
(fun name _req -> S.Response.make_string ("hello " ^name ^"!\n"));
(* compressed file access *)
S.add_route_handler ~meth:GET server
S.Route.(exact "zcat" @/ string @/ return)
(fun path _req ->
let ic = open_in path in
let str = S.Input.of_chan ic in
let mime_type =
try
let p = Unix.open_process_in (Printf.sprintf "file -i -b %S" path) in
try
let s = [H.Content_Type, String.trim (input_line p)] in
ignore @@ Unix.close_process_in p;
s
with _ -> ignore @@ Unix.close_process_in p; []
with _ -> []
in
S.Response.make_stream ~headers:mime_type str
);
(* echo request *)
S.add_route_handler server
S.Route.(exact "echo" @/ return)
(fun req ->
let q =
S.Request.query req |> List.map (fun (k,v) -> Printf.sprintf "%S = %S" k v)
|> String.concat ";"
in
S.Response.make_string
(Format.asprintf "echo:@ %a@ (query: %s)@." S.Request.pp req q));
(* file upload *)
S.add_route_handler_stream ~meth:PUT server
S.Route.(exact "upload" @/ string @/ return)
(fun path req ->
S.log (fun k->k "start upload %S, headers:\n%s\n\n%!" path
(Format.asprintf "%a" S.Headers.pp (S.Request.headers req)));
try
let oc = open_out @@ "/tmp/" ^ path in
S.Input.to_chan oc req.S.Request.body;
flush oc;
S.Response.make_string "uploaded file"
with e ->
S.Response.fail ~code:500 "couldn't upload file: %s" (Printexc.to_string e)
);
(* stats *)
S.add_route_handler server S.Route.(exact "stats" @/ return)
(fun _req ->
let stats = get_stats() in
S.Response.make_string stats
);
VFS
Simple_httpd_dir.add_vfs server
~config:(Simple_httpd_dir.config ~download:true
~dir_behavior:Simple_httpd_dir.Index_or_lists ())
~vfs:Vfs.vfs ~prefix:"vfs";
(* main page *)
S.add_route_handler server S.Route.(return)
(fun _req ->
let open Simple_httpd_html in
let h = html [] [
head[][title[][txt "index of echo"]];
body[][
h3[] [txt "welcome!"];
p[] [b[] [txt "endpoints are:"]];
ul[] [
li[][pre[][txt "/hello/:name (GET)"]];
li[][pre[][a[A.href "/echo/"][txt "echo"]; txt " echo back query"]];
li[][pre[][txt "/upload/:path (PUT) to upload a file"]];
li[][pre[][txt "/zcat/:path (GET) to download a file (deflate transfer-encoding)"]];
li[][pre[][a[A.href "/stats/"][txt"/stats/"]; txt" (GET) to access statistics"]];
li[][pre[][a[A.href "/vfs/"][txt"/vfs"]; txt" (GET) to access a VFS embedded in the binary"]];
]
]
] in
let s = to_string_top h in
S.Response.make_string ~headers:[H.Content_Type, "text/html"] s);
List.iter S.(fun l ->
Printf.printf "listening on :%d\n%!" l.addr l.port) (S.listens server);
match S.run server with
| Ok () -> ()
| Error e -> raise e
| null | https://raw.githubusercontent.com/craff/simple_httpd/d00b635120ae787c31b221f5c6a7a74b9204d924/examples/echo.ml | ocaml | util: a little middleware collecting statistics
say hello
compressed file access
echo request
file upload
stats
main page |
module S = Simple_httpd
module H = S.Headers
let now_ = Unix.gettimeofday
let filter_stat () : S.filter * (unit -> string) =
let n_req = ref 0 in
let total_time_ = ref 0. in
let parse_time_ = ref 0. in
let build_time_ = ref 0. in
let m req =
incr n_req;
let t1 = S.Request.start_time req in
let t2 = now_ () in
(req, fun response ->
let t3 = now_ () in
total_time_ := !total_time_ +. (t3 -. t1);
parse_time_ := !parse_time_ +. (t2 -. t1);
build_time_ := !build_time_ +. (t3 -. t2);
response)
and get_stat () =
Printf.sprintf "%d requests (average response time: %.3fms = %.3fms + %.3fms)"
!n_req (!total_time_ /. float !n_req *. 1e3)
(!parse_time_ /. float !n_req *. 1e3)
(!build_time_ /. float !n_req *. 1e3)
in
m, get_stat
let () =
let addr = ref "127.0.0.1" in
let port = ref 8080 in
let j = ref 32 in
Arg.parse (Arg.align [
"--addr", Arg.Set_string addr, " set address";
"-a", Arg.Set_string addr, " set address";
"--port", Arg.Set_int port, " set port";
"-p", Arg.Set_int port, " set port";
"--log", Arg.Int (fun n -> S.set_log_lvl n), " set debug lvl";
"-j", Arg.Set_int j, " maximum number of connections";
]) (fun _ -> raise (Arg.Bad "")) "echo [option]*";
let listens = S.[{addr= !addr;port= !port;ssl=None}] in
let server = S.create ~listens ~max_connections:!j () in
let filter_stat, get_stats = filter_stat () in
let filter_zip =
Simple_httpd_camlzip.filter ~compress_above:1024 ~buf_size:(16*1024) ()
in
let filter = S.compose_cross filter_zip filter_stat in
S.add_route_handler ~meth:GET server ~filter
S.Route.(exact "hello" @/ string @/ return)
(fun name _req -> S.Response.make_string ("hello " ^name ^"!\n"));
S.add_route_handler ~meth:GET server
S.Route.(exact "zcat" @/ string @/ return)
(fun path _req ->
let ic = open_in path in
let str = S.Input.of_chan ic in
let mime_type =
try
let p = Unix.open_process_in (Printf.sprintf "file -i -b %S" path) in
try
let s = [H.Content_Type, String.trim (input_line p)] in
ignore @@ Unix.close_process_in p;
s
with _ -> ignore @@ Unix.close_process_in p; []
with _ -> []
in
S.Response.make_stream ~headers:mime_type str
);
S.add_route_handler server
S.Route.(exact "echo" @/ return)
(fun req ->
let q =
S.Request.query req |> List.map (fun (k,v) -> Printf.sprintf "%S = %S" k v)
|> String.concat ";"
in
S.Response.make_string
(Format.asprintf "echo:@ %a@ (query: %s)@." S.Request.pp req q));
S.add_route_handler_stream ~meth:PUT server
S.Route.(exact "upload" @/ string @/ return)
(fun path req ->
S.log (fun k->k "start upload %S, headers:\n%s\n\n%!" path
(Format.asprintf "%a" S.Headers.pp (S.Request.headers req)));
try
let oc = open_out @@ "/tmp/" ^ path in
S.Input.to_chan oc req.S.Request.body;
flush oc;
S.Response.make_string "uploaded file"
with e ->
S.Response.fail ~code:500 "couldn't upload file: %s" (Printexc.to_string e)
);
S.add_route_handler server S.Route.(exact "stats" @/ return)
(fun _req ->
let stats = get_stats() in
S.Response.make_string stats
);
VFS
Simple_httpd_dir.add_vfs server
~config:(Simple_httpd_dir.config ~download:true
~dir_behavior:Simple_httpd_dir.Index_or_lists ())
~vfs:Vfs.vfs ~prefix:"vfs";
S.add_route_handler server S.Route.(return)
(fun _req ->
let open Simple_httpd_html in
let h = html [] [
head[][title[][txt "index of echo"]];
body[][
h3[] [txt "welcome!"];
p[] [b[] [txt "endpoints are:"]];
ul[] [
li[][pre[][txt "/hello/:name (GET)"]];
li[][pre[][a[A.href "/echo/"][txt "echo"]; txt " echo back query"]];
li[][pre[][txt "/upload/:path (PUT) to upload a file"]];
li[][pre[][txt "/zcat/:path (GET) to download a file (deflate transfer-encoding)"]];
li[][pre[][a[A.href "/stats/"][txt"/stats/"]; txt" (GET) to access statistics"]];
li[][pre[][a[A.href "/vfs/"][txt"/vfs"]; txt" (GET) to access a VFS embedded in the binary"]];
]
]
] in
let s = to_string_top h in
S.Response.make_string ~headers:[H.Content_Type, "text/html"] s);
List.iter S.(fun l ->
Printf.printf "listening on :%d\n%!" l.addr l.port) (S.listens server);
match S.run server with
| Ok () -> ()
| Error e -> raise e
|
bd8ad49a8c27c4c57745d5a5e9cf3867bce6e6ca5a89459d5350088ccbd32ddf | heidihoward/ocaml-raft | raftMonitorWrapper.ml | open Core_kernel.Std
exception SPLMonitorFailure of string
type s = RaftMonitor.s
type t = RaftMonitor.t * (s list)
let s_to_string = function
|`RestartElection -> "restart election"
|`Startup -> "startup"
|`StepDown_from_Candidate -> "stepdown candidate"
|`StepDown_from_Leader -> "stepdown leader"
|`StartElection -> "start election"
|`WinElection -> "win election"
|`Recover -> "recover"
let init () = (RaftMonitor.init (), [])
let tick (monitor,history) statecall =
try
let new_mon = RaftMonitor.tick monitor statecall in
(* printf "%s \n" (s_to_string statecall); *)
(new_mon, statecall::history)
with
RaftMonitor.Bad_statecall ->
raise (SPLMonitorFailure (List.to_string ~f:s_to_string (statecall::history)))
| null | https://raw.githubusercontent.com/heidihoward/ocaml-raft/b1502ebf8c19be28270d11994abac68e5a6418be/spl/raftMonitorWrapper.ml | ocaml | printf "%s \n" (s_to_string statecall); | open Core_kernel.Std
exception SPLMonitorFailure of string
type s = RaftMonitor.s
type t = RaftMonitor.t * (s list)
let s_to_string = function
|`RestartElection -> "restart election"
|`Startup -> "startup"
|`StepDown_from_Candidate -> "stepdown candidate"
|`StepDown_from_Leader -> "stepdown leader"
|`StartElection -> "start election"
|`WinElection -> "win election"
|`Recover -> "recover"
let init () = (RaftMonitor.init (), [])
let tick (monitor,history) statecall =
try
let new_mon = RaftMonitor.tick monitor statecall in
(new_mon, statecall::history)
with
RaftMonitor.Bad_statecall ->
raise (SPLMonitorFailure (List.to_string ~f:s_to_string (statecall::history)))
|
e46cf8174f5ec33bc5e836fb38c907167d52dc5995060b39b29095e86669be45 | benoitc/sieve | sieve_example.erl | -module(sieve_example).
-export([start/0, proxy/1]).
proxy(_Data) ->
{remote, {"openbsd.org", 80}}.
start() ->
barrel:start(),
barrel:start_listener(http, 100, barrel_tcp,
[{port, 8080}], sieve_revproxy, [{proxy, {?MODULE, proxy}}]).
| null | https://raw.githubusercontent.com/benoitc/sieve/b64fdb44b336681e645cc0f73428c5ecfdb5e271/src/sieve_example.erl | erlang | -module(sieve_example).
-export([start/0, proxy/1]).
proxy(_Data) ->
{remote, {"openbsd.org", 80}}.
start() ->
barrel:start(),
barrel:start_listener(http, 100, barrel_tcp,
[{port, 8080}], sieve_revproxy, [{proxy, {?MODULE, proxy}}]).
| |
510e7275c3a4395ded33d7b143ecc30718639fb7ebe0399206e2ed9e491b5bd6 | saltysystems/overworld | ow_ecs.erl | -module(ow_ecs).
-behaviour(gen_server).
-define(SERVER(World),
{via, gproc, {n, l, {?MODULE, World}}}
).
%% API
-export([start/1, start_link/1, stop/1]).
-export([
new_entity/2,
rm_entity/2,
entity/2,
entities/1,
add_component/4,
add_components/3,
del_component/3,
del_components/3,
try_component/3,
match_component/2,
match_components/2,
foreach_component/3,
add_system/3,
add_system/2,
del_system/2,
proc/1,
proc/2,
to_map/1,
get/3,
get/2,
take/3,
take/2
]).
%% gen_server callbacks
-export([
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Types and Records
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-record(world, {
name :: term(),
systems = [] :: [{term(), system()}],
entities :: ets:tid(),
components :: ets:tid()
}).
-type world() :: #world{}.
-export_type([world/0]).
-type component() :: {term(), term()}.
-type entity() :: {term(), [component()]}.
-export_type([entity/0]).
-type system() :: {mfa() | fun()}.
-type id() :: integer().
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% API
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
start(World) ->
gen_server:start(?SERVER(World), ?MODULE, [World], []).
start_link(World) ->
gen_server:start_link(?SERVER(World), ?MODULE, [World], []).
stop(World) ->
gen_server:stop(?SERVER(World)).
% This can potentially create an unbounded number of atoms! Careful!
-spec to_map(entity()) -> map().
to_map({EntityID, Components}) ->
% Create the component map
EMap = maps:from_list(Components),
% Add the ID
EMap#{id => EntityID}.
-spec get(term(), [component()]) -> term().
get(Component, ComponentList) ->
get(Component, ComponentList, false).
-spec get(term(), [component()], term()) -> term().
get(Component, ComponentList, Default) ->
case lists:keyfind(Component, 1, ComponentList) of
{_Component, Data} ->
Data;
false ->
Default
end.
-spec take(term(), [component()]) -> term().
take(Component, ComponentList) ->
take(Component, ComponentList, false).
-spec take(term(), [component()], term()) -> {term(), [term()]}.
take(Component, ComponentList, Default) ->
case lists:keytake(Component, 1, ComponentList) of
{value, {_Component, Data}, Rest} ->
{Data, Rest};
false ->
Default
end.
-spec try_component(term(), id(), world()) -> [term()] | false.
try_component(ComponentName, EntityID, World) ->
gen_server:call(
?SERVER(World), {try_component, ComponentName, EntityID}
).
-spec match_component(term(), world()) -> [entity()].
match_component(ComponentName, World) ->
gen_server:call(?SERVER(World), {match_component, ComponentName}).
-spec match_components([term()], world()) -> [entity()].
match_components(List, World) ->
% Multi-match. Try to match several components and return the common
elements . Use sets v2 introduced in OTP 24
Sets = [
sets:from_list(match_component(X, World), [{version, 2}])
|| X <- List
],
sets:to_list(sets:intersection(Sets)).
-spec foreach_component(fun(), term(), world()) -> ok.
foreach_component(Fun, Component, World) ->
Entities = match_component(Component, World),
F =
fun({ID, EntityComponents}) ->
Values = get(Component, EntityComponents),
Fun(ID, Values)
end,
lists:foreach(F, Entities).
-spec new_entity(id(), world()) -> ok.
new_entity(EntityID, World) ->
gen_server:call(?SERVER(World), {new_entity, EntityID}).
-spec rm_entity(id(), world()) -> ok.
rm_entity(EntityID, World) ->
gen_server:call(?SERVER(World), {rm_entity, EntityID}).
-spec entity(id(), world()) -> [term()] | false.
entity(EntityID, World) ->
gen_server:call(?SERVER(World), {entity, EntityID}).
-spec entities(world()) -> [{id(), list()}].
entities(World) ->
gen_server:call(?SERVER(World), entities).
-spec add_component(term(), term(), id(), world()) -> true.
add_component(Name, Data, EntityID, World) ->
gen_server:call(?SERVER(World), {add_component, Name, Data, EntityID}).
% TODO: ok -> true?
-spec add_components([{term(), term()}], id(), world()) -> ok.
add_components(Components, EntityID, World) ->
F =
fun({Component, Data}) ->
add_component(Component, Data, EntityID, World)
end,
lists:foreach(F, Components).
-spec del_component(term(), id(), world()) -> true.
del_component(Name, EntityID, World) ->
gen_server:call(?SERVER(World), {del_component, Name, EntityID}).
% TODO: ok -> true?
-spec del_components([term()], id(), world()) -> ok.
del_components(Components, EntityID, World) ->
F =
fun(Component) ->
del_component(Component, EntityID, World)
end,
lists:foreach(F, Components).
-spec add_system(system(), world()) -> ok.
add_system(System, World) ->
add_system(System, 100, World).
-spec add_system(system(), integer(), world()) -> ok.
add_system(System, Priority, World) ->
gen_server:call(?SERVER(World), {add_system, System, Priority}).
-spec del_system(system(), world()) -> ok.
del_system(System, World) ->
gen_server:call(?SERVER(World), {del_system, System}).
-spec proc(world()) -> any().
proc(World) ->
proc(World, []).
-spec proc(world(), any()) -> [any()].
proc(World, Data) ->
Systems = gen_server:call(?SERVER(World), systems),
Fun = fun({_Prio, Sys}, Acc) ->
Result =
case Sys of
{M, F, 1} ->
erlang:apply(M, F, [World]);
{M, F, 2} ->
erlang:apply(M, F, [World, Data]);
Fun2 ->
Fun2(World, Data)
end,
[Result | Acc]
end,
lists:foldl(Fun, [], Systems).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% gen_server callbacks
%%%%%%%/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
init([WorldName]) ->
World = #world{
name = WorldName,
systems = [],
entities = ets:new(entities, [set, public]),
components = ets:new(components, [bag, public])
},
{ok, World}.
handle_call(
{add_component, ComponentName, ComponentData, EntityID}, _From, State
) ->
#world{entities = E, components = C} = State,
% On the entity table, we want to get the entity by key and insert a new
% version with the data
Components =
case ets:lookup(E, EntityID) of
[] ->
% No components
[{ComponentName, ComponentData}];
[{EntityID, ComponentList}] ->
% Check if the component already exists
case lists:keytake(ComponentName, 1, ComponentList) of
{value, _Tuple, ComponentList2} ->
Throw away the old data and add the new data
[{ComponentName, ComponentData} | ComponentList2];
false ->
[{ComponentName, ComponentData} | ComponentList]
end
end,
% Insert the new entity and component list
ets:insert(E, {EntityID, Components}),
% Insert the entity EntityID into the component table
ets:insert(C, {ComponentName, EntityID}),
{reply, ok, State};
handle_call({del_component, ComponentName, EntityID}, _From, State) ->
#world{entities = E, components = C} = State,
% Remove the data from the entity
case ets:lookup_element(E, EntityID, 2) of
[] ->
ok;
ComponentList ->
Delete the key - value identified by ComponentName
ComponentList1 = lists:keydelete(
ComponentName, 1, ComponentList
),
% Update the entity table
ets:insert(E, {EntityID, ComponentList1})
end,
% Remove the data from the component bag
ets:delete_object(C, {ComponentName, EntityID}),
{reply, true, State};
handle_call({try_component, ComponentName, EntityID}, _From, State) ->
#world{entities = E, components = C} = State,
Resp =
case ets:match_object(C, {ComponentName, EntityID}) of
[] ->
false;
_Match ->
% It exists in the component table, so return the Entity data
% back to the caller
[{EntityID, Data}] = ets:lookup(E, EntityID),
Data
end,
{reply, Resp, State};
handle_call({match_component, ComponentName}, _From, State) ->
% From the component bag table, get all matches
#world{entities = E, components = C} = State,
Matches = ets:lookup(C, ComponentName),
% Use the entity IDs from the lookup in the component table to
% generate a list of IDs for which to return data to the caller
IDs = [ets:lookup(E, EntityID) || {_, EntityID} <- Matches],
Resp = lists:flatten(IDs),
{reply, Resp, State};
handle_call({new_entity, EntityID}, _From, State) ->
#world{entities = E} = State,
Resp =
case ets:lookup(E, EntityID) of
[] ->
% ok, add 'em
ets:insert(E, {EntityID, []});
_Entity ->
ok
end,
{reply, Resp, State};
handle_call({rm_entity, EntityID}, _From, State) ->
#world{entities = E, components = C} = State,
Resp =
case ets:lookup(E, EntityID) of
[] ->
% ok, nothing to do
ok;
[{EntityID, Components}] ->
% Remove the entity from the entity table
ets:delete(E, EntityID),
% Delete all instances of it from the component table as well
[
ets:delete_object(C, {N, EntityID})
|| {N, _} <- Components
],
ok
end,
{reply, Resp, State};
handle_call({entity, EntityID}, _From, State) ->
#world{entities = E} = State,
Resp =
case ets:lookup(E, EntityID) of
[] ->
false;
[Entity] ->
{_ID, Components} = Entity,
Components
end,
{reply, Resp, State};
handle_call(entities, _From, State) ->
#world{entities = E} = State,
ets:match_object(E, {'$0', '$1'});
handle_call(systems, _From, State) ->
#world{systems = S} = State,
{reply, S, State};
handle_call({add_system, Callback, Prio}, _From, State) ->
#world{systems = S} = State,
S0 =
case lists:keytake(Callback, 2, S) of
false ->
S;
{value, _Tuple, SRest} ->
% Replace the current value instead
SRest
end,
S1 = lists:keysort(1, [{Prio, Callback} | S0]),
Reply = {ok, Prio},
{reply, Reply, State#world{systems = S1}};
handle_call({del_system, Callback}, _From, State = #world{systems = S}) ->
S1 = lists:keydelete(Callback, 2, S),
{reply, ok, State#world{systems = S1}}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% internal functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
| null | https://raw.githubusercontent.com/saltysystems/overworld/c4f658f08f0a4e63a8d87ddff337a39fc8d0fcfe/src/ow_ecs.erl | erlang | API
gen_server callbacks
API
This can potentially create an unbounded number of atoms! Careful!
Create the component map
Add the ID
Multi-match. Try to match several components and return the common
TODO: ok -> true?
TODO: ok -> true?
gen_server callbacks
/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
On the entity table, we want to get the entity by key and insert a new
version with the data
No components
Check if the component already exists
Insert the new entity and component list
Insert the entity EntityID into the component table
Remove the data from the entity
Update the entity table
Remove the data from the component bag
It exists in the component table, so return the Entity data
back to the caller
From the component bag table, get all matches
Use the entity IDs from the lookup in the component table to
generate a list of IDs for which to return data to the caller
ok, add 'em
ok, nothing to do
Remove the entity from the entity table
Delete all instances of it from the component table as well
Replace the current value instead
internal functions
| -module(ow_ecs).
-behaviour(gen_server).
-define(SERVER(World),
{via, gproc, {n, l, {?MODULE, World}}}
).
-export([start/1, start_link/1, stop/1]).
-export([
new_entity/2,
rm_entity/2,
entity/2,
entities/1,
add_component/4,
add_components/3,
del_component/3,
del_components/3,
try_component/3,
match_component/2,
match_components/2,
foreach_component/3,
add_system/3,
add_system/2,
del_system/2,
proc/1,
proc/2,
to_map/1,
get/3,
get/2,
take/3,
take/2
]).
-export([
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
Types and Records
-record(world, {
name :: term(),
systems = [] :: [{term(), system()}],
entities :: ets:tid(),
components :: ets:tid()
}).
-type world() :: #world{}.
-export_type([world/0]).
-type component() :: {term(), term()}.
-type entity() :: {term(), [component()]}.
-export_type([entity/0]).
-type system() :: {mfa() | fun()}.
-type id() :: integer().
start(World) ->
gen_server:start(?SERVER(World), ?MODULE, [World], []).
start_link(World) ->
gen_server:start_link(?SERVER(World), ?MODULE, [World], []).
stop(World) ->
gen_server:stop(?SERVER(World)).
-spec to_map(entity()) -> map().
to_map({EntityID, Components}) ->
EMap = maps:from_list(Components),
EMap#{id => EntityID}.
-spec get(term(), [component()]) -> term().
get(Component, ComponentList) ->
get(Component, ComponentList, false).
-spec get(term(), [component()], term()) -> term().
get(Component, ComponentList, Default) ->
case lists:keyfind(Component, 1, ComponentList) of
{_Component, Data} ->
Data;
false ->
Default
end.
-spec take(term(), [component()]) -> term().
take(Component, ComponentList) ->
take(Component, ComponentList, false).
-spec take(term(), [component()], term()) -> {term(), [term()]}.
take(Component, ComponentList, Default) ->
case lists:keytake(Component, 1, ComponentList) of
{value, {_Component, Data}, Rest} ->
{Data, Rest};
false ->
Default
end.
-spec try_component(term(), id(), world()) -> [term()] | false.
try_component(ComponentName, EntityID, World) ->
gen_server:call(
?SERVER(World), {try_component, ComponentName, EntityID}
).
-spec match_component(term(), world()) -> [entity()].
match_component(ComponentName, World) ->
gen_server:call(?SERVER(World), {match_component, ComponentName}).
-spec match_components([term()], world()) -> [entity()].
match_components(List, World) ->
elements . Use sets v2 introduced in OTP 24
Sets = [
sets:from_list(match_component(X, World), [{version, 2}])
|| X <- List
],
sets:to_list(sets:intersection(Sets)).
-spec foreach_component(fun(), term(), world()) -> ok.
foreach_component(Fun, Component, World) ->
Entities = match_component(Component, World),
F =
fun({ID, EntityComponents}) ->
Values = get(Component, EntityComponents),
Fun(ID, Values)
end,
lists:foreach(F, Entities).
-spec new_entity(id(), world()) -> ok.
new_entity(EntityID, World) ->
gen_server:call(?SERVER(World), {new_entity, EntityID}).
-spec rm_entity(id(), world()) -> ok.
rm_entity(EntityID, World) ->
gen_server:call(?SERVER(World), {rm_entity, EntityID}).
-spec entity(id(), world()) -> [term()] | false.
entity(EntityID, World) ->
gen_server:call(?SERVER(World), {entity, EntityID}).
-spec entities(world()) -> [{id(), list()}].
entities(World) ->
gen_server:call(?SERVER(World), entities).
-spec add_component(term(), term(), id(), world()) -> true.
add_component(Name, Data, EntityID, World) ->
gen_server:call(?SERVER(World), {add_component, Name, Data, EntityID}).
-spec add_components([{term(), term()}], id(), world()) -> ok.
add_components(Components, EntityID, World) ->
F =
fun({Component, Data}) ->
add_component(Component, Data, EntityID, World)
end,
lists:foreach(F, Components).
-spec del_component(term(), id(), world()) -> true.
del_component(Name, EntityID, World) ->
gen_server:call(?SERVER(World), {del_component, Name, EntityID}).
-spec del_components([term()], id(), world()) -> ok.
del_components(Components, EntityID, World) ->
F =
fun(Component) ->
del_component(Component, EntityID, World)
end,
lists:foreach(F, Components).
-spec add_system(system(), world()) -> ok.
add_system(System, World) ->
add_system(System, 100, World).
-spec add_system(system(), integer(), world()) -> ok.
add_system(System, Priority, World) ->
gen_server:call(?SERVER(World), {add_system, System, Priority}).
-spec del_system(system(), world()) -> ok.
del_system(System, World) ->
gen_server:call(?SERVER(World), {del_system, System}).
-spec proc(world()) -> any().
proc(World) ->
proc(World, []).
-spec proc(world(), any()) -> [any()].
proc(World, Data) ->
Systems = gen_server:call(?SERVER(World), systems),
Fun = fun({_Prio, Sys}, Acc) ->
Result =
case Sys of
{M, F, 1} ->
erlang:apply(M, F, [World]);
{M, F, 2} ->
erlang:apply(M, F, [World, Data]);
Fun2 ->
Fun2(World, Data)
end,
[Result | Acc]
end,
lists:foldl(Fun, [], Systems).
init([WorldName]) ->
World = #world{
name = WorldName,
systems = [],
entities = ets:new(entities, [set, public]),
components = ets:new(components, [bag, public])
},
{ok, World}.
handle_call(
{add_component, ComponentName, ComponentData, EntityID}, _From, State
) ->
#world{entities = E, components = C} = State,
Components =
case ets:lookup(E, EntityID) of
[] ->
[{ComponentName, ComponentData}];
[{EntityID, ComponentList}] ->
case lists:keytake(ComponentName, 1, ComponentList) of
{value, _Tuple, ComponentList2} ->
Throw away the old data and add the new data
[{ComponentName, ComponentData} | ComponentList2];
false ->
[{ComponentName, ComponentData} | ComponentList]
end
end,
ets:insert(E, {EntityID, Components}),
ets:insert(C, {ComponentName, EntityID}),
{reply, ok, State};
handle_call({del_component, ComponentName, EntityID}, _From, State) ->
#world{entities = E, components = C} = State,
case ets:lookup_element(E, EntityID, 2) of
[] ->
ok;
ComponentList ->
Delete the key - value identified by ComponentName
ComponentList1 = lists:keydelete(
ComponentName, 1, ComponentList
),
ets:insert(E, {EntityID, ComponentList1})
end,
ets:delete_object(C, {ComponentName, EntityID}),
{reply, true, State};
handle_call({try_component, ComponentName, EntityID}, _From, State) ->
#world{entities = E, components = C} = State,
Resp =
case ets:match_object(C, {ComponentName, EntityID}) of
[] ->
false;
_Match ->
[{EntityID, Data}] = ets:lookup(E, EntityID),
Data
end,
{reply, Resp, State};
handle_call({match_component, ComponentName}, _From, State) ->
#world{entities = E, components = C} = State,
Matches = ets:lookup(C, ComponentName),
IDs = [ets:lookup(E, EntityID) || {_, EntityID} <- Matches],
Resp = lists:flatten(IDs),
{reply, Resp, State};
handle_call({new_entity, EntityID}, _From, State) ->
#world{entities = E} = State,
Resp =
case ets:lookup(E, EntityID) of
[] ->
ets:insert(E, {EntityID, []});
_Entity ->
ok
end,
{reply, Resp, State};
handle_call({rm_entity, EntityID}, _From, State) ->
#world{entities = E, components = C} = State,
Resp =
case ets:lookup(E, EntityID) of
[] ->
ok;
[{EntityID, Components}] ->
ets:delete(E, EntityID),
[
ets:delete_object(C, {N, EntityID})
|| {N, _} <- Components
],
ok
end,
{reply, Resp, State};
handle_call({entity, EntityID}, _From, State) ->
#world{entities = E} = State,
Resp =
case ets:lookup(E, EntityID) of
[] ->
false;
[Entity] ->
{_ID, Components} = Entity,
Components
end,
{reply, Resp, State};
handle_call(entities, _From, State) ->
#world{entities = E} = State,
ets:match_object(E, {'$0', '$1'});
handle_call(systems, _From, State) ->
#world{systems = S} = State,
{reply, S, State};
handle_call({add_system, Callback, Prio}, _From, State) ->
#world{systems = S} = State,
S0 =
case lists:keytake(Callback, 2, S) of
false ->
S;
{value, _Tuple, SRest} ->
SRest
end,
S1 = lists:keysort(1, [{Prio, Callback} | S0]),
Reply = {ok, Prio},
{reply, Reply, State#world{systems = S1}};
handle_call({del_system, Callback}, _From, State = #world{systems = S}) ->
S1 = lists:keydelete(Callback, 2, S),
{reply, ok, State#world{systems = S1}}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
|
bed060a9ff239a80875507109c181db54fc629374e2dc9d4f6c84c65a8e7360d | maybevoid/casimir | Lift.hs |
module Casimir.Base.Lift
( IdLift (..)
, Lift (..)
, LiftMonoid (..)
, MaybeLift (..)
, FreeLift (..)
, HigherLift (..)
, LiftFunctor (..)
)
where
import Data.Kind
import Data.Functor.Identity
import Casimir.Base.Effect
import Casimir.Base.ContraLift
class LiftFunctor
(lift1 :: (Type -> Type) -> (Type -> Type) -> Type)
(lift2 :: (Type -> Type) -> (Type -> Type) -> Type)
where
transformLift
:: forall eff1 eff2
. (Effect eff1, Effect eff2)
=> lift1 eff1 eff2
-> lift2 eff1 eff2
data IdLift
(eff1 :: Type -> Type)
(eff2 :: Type -> Type)
where
IdLift :: IdLift eff eff
newtype Lift eff1 eff2 = Lift
{ runLift :: eff1 ~> eff2 }
data HigherLift
(eff1 :: Type -> Type)
(eff2 :: Type -> Type)
= HigherLift
{ hlBaseLift :: eff1 ~> eff2
, hlContraLift :: ContraLift eff1 eff2
}
data MaybeLift
(lift :: (Type -> Type) -> (Type -> Type) -> Type)
eff1 eff2
where
NoLift :: MaybeLift lift eff eff
JustLift :: lift eff1 eff2 -> MaybeLift lift eff1 eff2
class
(LiftMonoid lift)
=> FreeLift t lift eff1 eff2 where
freeLift :: lift eff1 eff2
class LiftMonoid lift where
idLift
:: forall eff . (Effect eff) => lift eff eff
joinLift
:: forall eff1 eff2 eff3
. ( Effect eff1
, Effect eff2
, Effect eff3
)
=> lift eff1 eff2
-> lift eff2 eff3
-> lift eff1 eff3
instance LiftMonoid IdLift where
idLift = IdLift
joinLift IdLift IdLift = IdLift
instance LiftMonoid Lift where
idLift = Lift id
joinLift (Lift lift1) (Lift lift2) =
Lift $ lift2 . lift1
instance LiftMonoid HigherLift where
idLift = HigherLift id identityContraLift
joinLift
(HigherLift lift1 contraLift1)
(HigherLift lift2 contraLift2)
= HigherLift
(lift2 . lift1)
(joinContraLift contraLift1 contraLift2)
instance
(LiftMonoid lift)
=> LiftMonoid (MaybeLift lift) where
idLift = NoLift
joinLift NoLift lift = lift
joinLift lift NoLift = lift
joinLift (JustLift lift1) (JustLift lift2) =
JustLift $ joinLift lift1 lift2
instance LiftFunctor IdLift Lift where
transformLift IdLift = Lift id
instance LiftFunctor IdLift HigherLift where
transformLift
:: forall eff1 eff2
. (Effect eff1, Effect eff2)
=> IdLift eff1 eff2
-> HigherLift eff1 eff2
transformLift IdLift = HigherLift id $
ContraLift contraLift
where
contraLift
:: forall a
. ((forall x . eff1 x -> eff1 (Identity x))
-> eff1 (Identity a))
-> eff1 a
contraLift cont =
fmap runIdentity $ cont $ fmap Identity
instance
LiftFunctor IdLift (MaybeLift lift) where
transformLift
:: forall eff1 eff2
. IdLift eff1 eff2
-> MaybeLift lift eff1 eff2
transformLift IdLift = NoLift
instance {-# OVERLAPPABLE #-}
LiftFunctor lift (MaybeLift lift) where
transformLift
:: forall eff1 eff2
. lift eff1 eff2
-> MaybeLift lift eff1 eff2
transformLift = JustLift
instance
LiftFunctor HigherLift Lift where
transformLift
:: forall eff1 eff2
. HigherLift eff1 eff2
-> Lift eff1 eff2
transformLift (HigherLift lift _) = Lift lift
| null | https://raw.githubusercontent.com/maybevoid/casimir/ebbfa403739d6f258e6ac6793549006a0e8bff42/casimir/src/lib/Casimir/Base/Lift.hs | haskell | # OVERLAPPABLE # |
module Casimir.Base.Lift
( IdLift (..)
, Lift (..)
, LiftMonoid (..)
, MaybeLift (..)
, FreeLift (..)
, HigherLift (..)
, LiftFunctor (..)
)
where
import Data.Kind
import Data.Functor.Identity
import Casimir.Base.Effect
import Casimir.Base.ContraLift
class LiftFunctor
(lift1 :: (Type -> Type) -> (Type -> Type) -> Type)
(lift2 :: (Type -> Type) -> (Type -> Type) -> Type)
where
transformLift
:: forall eff1 eff2
. (Effect eff1, Effect eff2)
=> lift1 eff1 eff2
-> lift2 eff1 eff2
data IdLift
(eff1 :: Type -> Type)
(eff2 :: Type -> Type)
where
IdLift :: IdLift eff eff
newtype Lift eff1 eff2 = Lift
{ runLift :: eff1 ~> eff2 }
data HigherLift
(eff1 :: Type -> Type)
(eff2 :: Type -> Type)
= HigherLift
{ hlBaseLift :: eff1 ~> eff2
, hlContraLift :: ContraLift eff1 eff2
}
data MaybeLift
(lift :: (Type -> Type) -> (Type -> Type) -> Type)
eff1 eff2
where
NoLift :: MaybeLift lift eff eff
JustLift :: lift eff1 eff2 -> MaybeLift lift eff1 eff2
class
(LiftMonoid lift)
=> FreeLift t lift eff1 eff2 where
freeLift :: lift eff1 eff2
class LiftMonoid lift where
idLift
:: forall eff . (Effect eff) => lift eff eff
joinLift
:: forall eff1 eff2 eff3
. ( Effect eff1
, Effect eff2
, Effect eff3
)
=> lift eff1 eff2
-> lift eff2 eff3
-> lift eff1 eff3
instance LiftMonoid IdLift where
idLift = IdLift
joinLift IdLift IdLift = IdLift
instance LiftMonoid Lift where
idLift = Lift id
joinLift (Lift lift1) (Lift lift2) =
Lift $ lift2 . lift1
instance LiftMonoid HigherLift where
idLift = HigherLift id identityContraLift
joinLift
(HigherLift lift1 contraLift1)
(HigherLift lift2 contraLift2)
= HigherLift
(lift2 . lift1)
(joinContraLift contraLift1 contraLift2)
instance
(LiftMonoid lift)
=> LiftMonoid (MaybeLift lift) where
idLift = NoLift
joinLift NoLift lift = lift
joinLift lift NoLift = lift
joinLift (JustLift lift1) (JustLift lift2) =
JustLift $ joinLift lift1 lift2
instance LiftFunctor IdLift Lift where
transformLift IdLift = Lift id
instance LiftFunctor IdLift HigherLift where
transformLift
:: forall eff1 eff2
. (Effect eff1, Effect eff2)
=> IdLift eff1 eff2
-> HigherLift eff1 eff2
transformLift IdLift = HigherLift id $
ContraLift contraLift
where
contraLift
:: forall a
. ((forall x . eff1 x -> eff1 (Identity x))
-> eff1 (Identity a))
-> eff1 a
contraLift cont =
fmap runIdentity $ cont $ fmap Identity
instance
LiftFunctor IdLift (MaybeLift lift) where
transformLift
:: forall eff1 eff2
. IdLift eff1 eff2
-> MaybeLift lift eff1 eff2
transformLift IdLift = NoLift
LiftFunctor lift (MaybeLift lift) where
transformLift
:: forall eff1 eff2
. lift eff1 eff2
-> MaybeLift lift eff1 eff2
transformLift = JustLift
instance
LiftFunctor HigherLift Lift where
transformLift
:: forall eff1 eff2
. HigherLift eff1 eff2
-> Lift eff1 eff2
transformLift (HigherLift lift _) = Lift lift
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.