_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
|
---|---|---|---|---|---|---|---|---|
ab2b21b696f0b9aef4142aafe05d5c494cb1db75ab2f4006932b0b00d496766d | mvoidex/hsdev | Transaction.hs | # LANGUAGE TypeApplications , MultiWayIf , OverloadedStrings #
module HsDev.Database.SQLite.Transaction (
TransactionType(..),
Retries(..), def, noRetry, retryForever, retryN,
-- * Transactions
withTransaction, beginTransaction, commitTransaction, rollbackTransaction,
transaction, transaction_,
-- * Retry functions
retry, retry_
) where
import Control.Concurrent
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Default
import Database.SQLite.Simple as SQL hiding (withTransaction)
import HsDev.Server.Types (SessionMonad, serverSqlDatabase)
-- | Three types of transactions
data TransactionType = Deferred | Immediate | Exclusive
deriving (Eq, Ord, Read, Show)
-- | Retry config
data Retries = Retries {
retriesIntervals :: [Int],
retriesError :: SQLError -> Bool }
instance Default Retries where
def = Retries (replicate 10 100000) $ \e -> sqlError e `elem` [ErrorBusy, ErrorLocked]
-- | Don't retry
noRetry :: Retries
noRetry = Retries [] (const False)
-- | Retry forever
retryForever :: Int -> Retries
retryForever interval = def { retriesIntervals = repeat interval }
-- | Retry with interval N times
retryN :: Int -> Int -> Retries
retryN interval times = def { retriesIntervals = replicate times interval }
-- | Run actions inside transaction
withTransaction :: (MonadIO m, MonadMask m) => Connection -> TransactionType -> Retries -> m a -> m a
withTransaction conn t rs act = mask $ \restore -> do
mretry restore (beginTransaction conn t)
(restore act <* mretry restore (commitTransaction conn)) `onException` rollbackTransaction conn
where
mretry restore' fn = mretry' (retriesIntervals rs) where
mretry' [] = fn
mretry' (tm:tms) = catch @_ @SQLError fn $ \e -> if
| retriesError rs e -> do
_ <- restore' $ liftIO $ threadDelay tm
mretry' tms
| otherwise -> throwM e
-- | Begin transaction
beginTransaction :: MonadIO m => Connection -> TransactionType -> m ()
beginTransaction conn t = liftIO $ SQL.execute_ conn $ case t of
Deferred -> "begin transaction;"
Immediate -> "begin immediate transaction;"
Exclusive -> "begin exclusive transaction;"
-- | Commit transaction
commitTransaction :: MonadIO m => Connection -> m ()
commitTransaction conn = liftIO $ SQL.execute_ conn "commit transaction;"
-- | Rollback transaction
rollbackTransaction :: MonadIO m => Connection -> m ()
rollbackTransaction conn = liftIO $ SQL.execute_ conn "rollback transaction;"
-- | Run transaction in @SessionMonad@
transaction :: SessionMonad m => TransactionType -> Retries -> m a -> m a
transaction t rs act = do
conn <- serverSqlDatabase
withTransaction conn t rs act
-- | Transaction with default retries config
transaction_ :: SessionMonad m => TransactionType -> m a -> m a
transaction_ t = transaction t def
-- | Retry operation
retry :: (MonadIO m, MonadCatch m) => Retries -> m a -> m a
retry rs = retry' (retriesIntervals rs) where
retry' [] fn = fn
retry' (tm:tms) fn = catch @_ @SQLError fn $ \e -> if
| retriesError rs e -> do
liftIO $ threadDelay tm
retry' tms fn
| otherwise -> throwM e
-- | Retry with default params
retry_ :: (MonadIO m, MonadCatch m) => m a -> m a
retry_ = retry def
| null | https://raw.githubusercontent.com/mvoidex/hsdev/016646080a6859e4d9b4a1935fc1d732e388db1a/src/HsDev/Database/SQLite/Transaction.hs | haskell | * Transactions
* Retry functions
| Three types of transactions
| Retry config
| Don't retry
| Retry forever
| Retry with interval N times
| Run actions inside transaction
| Begin transaction
| Commit transaction
| Rollback transaction
| Run transaction in @SessionMonad@
| Transaction with default retries config
| Retry operation
| Retry with default params | # LANGUAGE TypeApplications , MultiWayIf , OverloadedStrings #
module HsDev.Database.SQLite.Transaction (
TransactionType(..),
Retries(..), def, noRetry, retryForever, retryN,
withTransaction, beginTransaction, commitTransaction, rollbackTransaction,
transaction, transaction_,
retry, retry_
) where
import Control.Concurrent
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Default
import Database.SQLite.Simple as SQL hiding (withTransaction)
import HsDev.Server.Types (SessionMonad, serverSqlDatabase)
data TransactionType = Deferred | Immediate | Exclusive
deriving (Eq, Ord, Read, Show)
data Retries = Retries {
retriesIntervals :: [Int],
retriesError :: SQLError -> Bool }
instance Default Retries where
def = Retries (replicate 10 100000) $ \e -> sqlError e `elem` [ErrorBusy, ErrorLocked]
noRetry :: Retries
noRetry = Retries [] (const False)
retryForever :: Int -> Retries
retryForever interval = def { retriesIntervals = repeat interval }
retryN :: Int -> Int -> Retries
retryN interval times = def { retriesIntervals = replicate times interval }
withTransaction :: (MonadIO m, MonadMask m) => Connection -> TransactionType -> Retries -> m a -> m a
withTransaction conn t rs act = mask $ \restore -> do
mretry restore (beginTransaction conn t)
(restore act <* mretry restore (commitTransaction conn)) `onException` rollbackTransaction conn
where
mretry restore' fn = mretry' (retriesIntervals rs) where
mretry' [] = fn
mretry' (tm:tms) = catch @_ @SQLError fn $ \e -> if
| retriesError rs e -> do
_ <- restore' $ liftIO $ threadDelay tm
mretry' tms
| otherwise -> throwM e
beginTransaction :: MonadIO m => Connection -> TransactionType -> m ()
beginTransaction conn t = liftIO $ SQL.execute_ conn $ case t of
Deferred -> "begin transaction;"
Immediate -> "begin immediate transaction;"
Exclusive -> "begin exclusive transaction;"
commitTransaction :: MonadIO m => Connection -> m ()
commitTransaction conn = liftIO $ SQL.execute_ conn "commit transaction;"
rollbackTransaction :: MonadIO m => Connection -> m ()
rollbackTransaction conn = liftIO $ SQL.execute_ conn "rollback transaction;"
transaction :: SessionMonad m => TransactionType -> Retries -> m a -> m a
transaction t rs act = do
conn <- serverSqlDatabase
withTransaction conn t rs act
transaction_ :: SessionMonad m => TransactionType -> m a -> m a
transaction_ t = transaction t def
retry :: (MonadIO m, MonadCatch m) => Retries -> m a -> m a
retry rs = retry' (retriesIntervals rs) where
retry' [] fn = fn
retry' (tm:tms) fn = catch @_ @SQLError fn $ \e -> if
| retriesError rs e -> do
liftIO $ threadDelay tm
retry' tms fn
| otherwise -> throwM e
retry_ :: (MonadIO m, MonadCatch m) => m a -> m a
retry_ = retry def
|
adb4e0d8469ebe02325709e144554785ebb609f3252be149a877a4c659de55e6 | OlivierSohn/hamazed | Continuous.hs | # LANGUAGE NoImplicitPrelude #
module Imj.Geo.Continuous
(-- * Continuous coordinates
Vec2(..)
, module Imj.Geo.Continuous.Conversion
-- * Sampled continuous geometry
-- ** Circle
, fullCircle
, translatedFullCircle
, fullCircleFromQuarterArc
, translatedFullCircleFromQuarterArc
-- ** Parabola
, parabola
* Polygon extremities
, polyExtremities
-- * Vec2 utilities
, sumVec2d
, diffVec2d
, integrateVelocity
, scalarProd
, rotateByQuarters
*
, Pos, Vel, Acc
) where
import Imj.Prelude
import Imj.Geo.Continuous.Types
import Imj.Geo.Continuous.Conversion
import Imj.Iteration
import Imj.Physics.Continuous.Types
| Creates a list of 4 ' Vec2 ' from a single one by rotating it successively by pi/2 .
rotateByQuarters :: Vec2 Pos -> [Vec2 Pos]
rotateByQuarters v@(Vec2 x y) =
[v,
Vec2 x $ -y,
Vec2 (-x) $ -y,
Vec2 (-x) y]
-- | Sums two 'Vec2'.
# INLINE sumVec2d #
sumVec2d :: Vec2 a -> Vec2 a -> Vec2 a
sumVec2d (Vec2 vx vy) (Vec2 wx wy) =
Vec2 (vx+wx) (vy+wy)
| Diffs two ' Vec2 ' .
# INLINE diffVec2d #
diffVec2d :: Vec2 a -> Vec2 a -> Vec2 b
diffVec2d (Vec2 vx vy) (Vec2 wx wy) =
Vec2 (vx-wx) (vy-wy)
-- | Multiplies a 'Vec2' by a scalar.
scalarProd :: Float -> Vec2 a -> Vec2 a
scalarProd f (Vec2 x y) = Vec2 (f*x) (f*y)
-- | Integrate twice a constant acceleration over a duration, return a position
# INLINE integrateAcceleration2 #
integrateAcceleration2 :: Frame -> Vec2 Acc -> Vec2 Pos
integrateAcceleration2 (Frame time) (Vec2 vx vy) =
let factor = 0.5 * fromIntegral (time * time)
in Vec2 (vx * factor) (vy * factor)
-- | Integrate once a constant acceleration over a duration, return a velocity
# INLINE integrateAcceleration1 #
integrateAcceleration1 :: Frame -> Vec2 Acc -> Vec2 Vel
integrateAcceleration1 (Frame time) (Vec2 vx vy) =
let factor = fromIntegral time
in Vec2 (vx * factor) (vy * factor)
-- | Integrate a constant velocity over a duration, return a position
# INLINE integrateVelocity #
integrateVelocity :: Frame -> Vec2 Vel -> Vec2 Pos
integrateVelocity (Frame time) (Vec2 vx vy) =
let factor = fromIntegral time
in Vec2 (vx * factor) (vy * factor)
gravity :: Vec2 Acc
this number was adjusted so that the timing in
-- game looks good. Instead, we could have adjusted the scale
-- of the world.
| Using
< equations [ 1 ] and [ 2 ] in " Constant linear acceleration in any direction " > :
\ [ \vec v = \vec a*t + \vec v_0 \ ] ( 1 )
\ [ \vec r = \vec r_0 + \vec v_0*t + { 1 \over 2 } * \vec a*t^2 \ ] ( 2 )
\ [ where \ ]
\ [ \vec r = current\;position \ ]
\ [ \vec r_0 = initial\;position \ ]
\ [ \ ]
\ [ \vec a = gravity\;force \ ]
\ [ t = time \ ]
< equations [1] and [2] in "Constant linear acceleration in any direction">:
\[ \vec v = \vec a*t + \vec v_0 \] (1)
\[ \vec r = \vec r_0 + \vec v_0*t + {1 \over 2}* \vec a*t^2 \] (2)
\[ where \]
\[ \vec r = current\;position \]
\[ \vec r_0 = initial\;position \]
\[ \vec v_0 = initial\;velocity \]
\[ \vec a = gravity\;force \]
\[ t = time \]
-}
parabola :: VecPosSpeed -> Frame -> VecPosSpeed
parabola (VecPosSpeed r0 v0) time =
let iv = integrateVelocity time v0
ia = integrateAcceleration2 time gravity
newPos = sumVec2d r0 $ sumVec2d iv ia
newSpeed = sumVec2d v0 $ integrateAcceleration1 time gravity
in VecPosSpeed newPos newSpeed
mkPointOnCircle :: Float -> Float -> Vec2 Pos
mkPointOnCircle radius angle =
let x = radius * sin angle
y = radius * cos angle
in Vec2 x y
discretizeArcOfCircle :: Float -> Float -> Float -> Int -> [Vec2 Pos]
discretizeArcOfCircle radius arcAngle firstAngle resolution =
let angleIncrement = arcAngle / (fromIntegral resolution :: Float)
in map (\i ->
let angle = firstAngle + angleIncrement * (fromIntegral i :: Float)
in mkPointOnCircle radius angle) [0..resolution]
fullCircleFromQuarterArc :: Float -> Float -> Int -> [Vec2 Pos]
fullCircleFromQuarterArc radius firstAngle quarterArcResolution =
let quarterArcAngle = pi/2
quarterCircle = discretizeArcOfCircle radius quarterArcAngle firstAngle quarterArcResolution
in concatMap rotateByQuarters quarterCircle
fullCircle :: Float -> Float -> Int -> [Vec2 Pos]
fullCircle radius firstAngle resolution =
let totalAngle = 2*pi
in discretizeArcOfCircle radius totalAngle firstAngle resolution
-- | Samples a circle in an optimized way, to reduce the number of 'sin' and 'cos'
-- calls.
--
The total number of points will always be a multiple of 4 .
translatedFullCircleFromQuarterArc :: Vec2 Pos
-- ^ Center
-> Float
-- ^ Radius
-> Float
^ The angle corresponding to the first sampled point
-> Int
-- ^ The total number of sampled points __per quarter arc__.
-> [Vec2 Pos]
translatedFullCircleFromQuarterArc center radius firstAngle resolution =
let circle = fullCircleFromQuarterArc radius firstAngle resolution
in map (sumVec2d center) circle
-- | Samples a circle.
translatedFullCircle :: Vec2 Pos
-- ^ Center
-> Float
-- ^ Radius
-> Float
^ The angle corresponding to the first sampled point
-> Int
-- ^ The total number of sampled points
-> [Vec2 Pos]
translatedFullCircle center radius firstAngle resolution =
let circle = fullCircle radius firstAngle resolution
in map (sumVec2d center) circle
-- | Returns the extremities of a polygon. Note that it is equal to 'translatedFullCircle'
polyExtremities :: Vec2 Pos
-- ^ Center
-> Float
-- ^ Radius
-> Float
-- ^ Rotate angle
-> Int
-- ^ Number of sides of the polygon.
-> [Vec2 Pos]
polyExtremities = translatedFullCircle
| null | https://raw.githubusercontent.com/OlivierSohn/hamazed/6c2b20d839ede7b8651fb7b425cb27ea93808a4a/imj-base/src/Imj/Geo/Continuous.hs | haskell | * Continuous coordinates
* Sampled continuous geometry
** Circle
** Parabola
* Vec2 utilities
| Sums two 'Vec2'.
| Multiplies a 'Vec2' by a scalar.
| Integrate twice a constant acceleration over a duration, return a position
| Integrate once a constant acceleration over a duration, return a velocity
| Integrate a constant velocity over a duration, return a position
game looks good. Instead, we could have adjusted the scale
of the world.
| Samples a circle in an optimized way, to reduce the number of 'sin' and 'cos'
calls.
^ Center
^ Radius
^ The total number of sampled points __per quarter arc__.
| Samples a circle.
^ Center
^ Radius
^ The total number of sampled points
| Returns the extremities of a polygon. Note that it is equal to 'translatedFullCircle'
^ Center
^ Radius
^ Rotate angle
^ Number of sides of the polygon. | # LANGUAGE NoImplicitPrelude #
module Imj.Geo.Continuous
Vec2(..)
, module Imj.Geo.Continuous.Conversion
, fullCircle
, translatedFullCircle
, fullCircleFromQuarterArc
, translatedFullCircleFromQuarterArc
, parabola
* Polygon extremities
, polyExtremities
, sumVec2d
, diffVec2d
, integrateVelocity
, scalarProd
, rotateByQuarters
*
, Pos, Vel, Acc
) where
import Imj.Prelude
import Imj.Geo.Continuous.Types
import Imj.Geo.Continuous.Conversion
import Imj.Iteration
import Imj.Physics.Continuous.Types
| Creates a list of 4 ' Vec2 ' from a single one by rotating it successively by pi/2 .
rotateByQuarters :: Vec2 Pos -> [Vec2 Pos]
rotateByQuarters v@(Vec2 x y) =
[v,
Vec2 x $ -y,
Vec2 (-x) $ -y,
Vec2 (-x) y]
# INLINE sumVec2d #
sumVec2d :: Vec2 a -> Vec2 a -> Vec2 a
sumVec2d (Vec2 vx vy) (Vec2 wx wy) =
Vec2 (vx+wx) (vy+wy)
| Diffs two ' Vec2 ' .
# INLINE diffVec2d #
diffVec2d :: Vec2 a -> Vec2 a -> Vec2 b
diffVec2d (Vec2 vx vy) (Vec2 wx wy) =
Vec2 (vx-wx) (vy-wy)
scalarProd :: Float -> Vec2 a -> Vec2 a
scalarProd f (Vec2 x y) = Vec2 (f*x) (f*y)
# INLINE integrateAcceleration2 #
integrateAcceleration2 :: Frame -> Vec2 Acc -> Vec2 Pos
integrateAcceleration2 (Frame time) (Vec2 vx vy) =
let factor = 0.5 * fromIntegral (time * time)
in Vec2 (vx * factor) (vy * factor)
# INLINE integrateAcceleration1 #
integrateAcceleration1 :: Frame -> Vec2 Acc -> Vec2 Vel
integrateAcceleration1 (Frame time) (Vec2 vx vy) =
let factor = fromIntegral time
in Vec2 (vx * factor) (vy * factor)
# INLINE integrateVelocity #
integrateVelocity :: Frame -> Vec2 Vel -> Vec2 Pos
integrateVelocity (Frame time) (Vec2 vx vy) =
let factor = fromIntegral time
in Vec2 (vx * factor) (vy * factor)
gravity :: Vec2 Acc
this number was adjusted so that the timing in
| Using
< equations [ 1 ] and [ 2 ] in " Constant linear acceleration in any direction " > :
\ [ \vec v = \vec a*t + \vec v_0 \ ] ( 1 )
\ [ \vec r = \vec r_0 + \vec v_0*t + { 1 \over 2 } * \vec a*t^2 \ ] ( 2 )
\ [ where \ ]
\ [ \vec r = current\;position \ ]
\ [ \vec r_0 = initial\;position \ ]
\ [ \ ]
\ [ \vec a = gravity\;force \ ]
\ [ t = time \ ]
< equations [1] and [2] in "Constant linear acceleration in any direction">:
\[ \vec v = \vec a*t + \vec v_0 \] (1)
\[ \vec r = \vec r_0 + \vec v_0*t + {1 \over 2}* \vec a*t^2 \] (2)
\[ where \]
\[ \vec r = current\;position \]
\[ \vec r_0 = initial\;position \]
\[ \vec v_0 = initial\;velocity \]
\[ \vec a = gravity\;force \]
\[ t = time \]
-}
parabola :: VecPosSpeed -> Frame -> VecPosSpeed
parabola (VecPosSpeed r0 v0) time =
let iv = integrateVelocity time v0
ia = integrateAcceleration2 time gravity
newPos = sumVec2d r0 $ sumVec2d iv ia
newSpeed = sumVec2d v0 $ integrateAcceleration1 time gravity
in VecPosSpeed newPos newSpeed
mkPointOnCircle :: Float -> Float -> Vec2 Pos
mkPointOnCircle radius angle =
let x = radius * sin angle
y = radius * cos angle
in Vec2 x y
discretizeArcOfCircle :: Float -> Float -> Float -> Int -> [Vec2 Pos]
discretizeArcOfCircle radius arcAngle firstAngle resolution =
let angleIncrement = arcAngle / (fromIntegral resolution :: Float)
in map (\i ->
let angle = firstAngle + angleIncrement * (fromIntegral i :: Float)
in mkPointOnCircle radius angle) [0..resolution]
fullCircleFromQuarterArc :: Float -> Float -> Int -> [Vec2 Pos]
fullCircleFromQuarterArc radius firstAngle quarterArcResolution =
let quarterArcAngle = pi/2
quarterCircle = discretizeArcOfCircle radius quarterArcAngle firstAngle quarterArcResolution
in concatMap rotateByQuarters quarterCircle
fullCircle :: Float -> Float -> Int -> [Vec2 Pos]
fullCircle radius firstAngle resolution =
let totalAngle = 2*pi
in discretizeArcOfCircle radius totalAngle firstAngle resolution
The total number of points will always be a multiple of 4 .
translatedFullCircleFromQuarterArc :: Vec2 Pos
-> Float
-> Float
^ The angle corresponding to the first sampled point
-> Int
-> [Vec2 Pos]
translatedFullCircleFromQuarterArc center radius firstAngle resolution =
let circle = fullCircleFromQuarterArc radius firstAngle resolution
in map (sumVec2d center) circle
translatedFullCircle :: Vec2 Pos
-> Float
-> Float
^ The angle corresponding to the first sampled point
-> Int
-> [Vec2 Pos]
translatedFullCircle center radius firstAngle resolution =
let circle = fullCircle radius firstAngle resolution
in map (sumVec2d center) circle
polyExtremities :: Vec2 Pos
-> Float
-> Float
-> Int
-> [Vec2 Pos]
polyExtremities = translatedFullCircle
|
9cbdcba0e64f73a5dd3a7eace2a22d3b7001e54b9960120a28a8478b7807e38c | coccinelle/coccinelle | single_statement.mli |
* This file is part of Coccinelle , licensed under the terms of the GPL v2 .
* See copyright.txt in the Coccinelle source code for more information .
* The Coccinelle source code can be obtained at
* This file is part of Coccinelle, licensed under the terms of the GPL v2.
* See copyright.txt in the Coccinelle source code for more information.
* The Coccinelle source code can be obtained at
*)
val single_statement : Ast0_cocci.rule -> Ast0_cocci.rule
| null | https://raw.githubusercontent.com/coccinelle/coccinelle/57cbff0c5768e22bb2d8c20e8dae74294515c6b3/parsing_cocci/single_statement.mli | ocaml |
* This file is part of Coccinelle , licensed under the terms of the GPL v2 .
* See copyright.txt in the Coccinelle source code for more information .
* The Coccinelle source code can be obtained at
* This file is part of Coccinelle, licensed under the terms of the GPL v2.
* See copyright.txt in the Coccinelle source code for more information.
* The Coccinelle source code can be obtained at
*)
val single_statement : Ast0_cocci.rule -> Ast0_cocci.rule
|
|
474e4c6ffdfc20497757021d4c8bf40bae5eddd6bd33da8b8eb95d5d79569726 | uber/queryparser | Test.hs | Copyright ( c ) 2017 Uber Technologies , Inc.
--
-- 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.
# LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE MultiParamTypeClasses #
# OPTIONS_GHC -fno - warn - orphans #
module Database.Sql.Util.Lineage.ColumnPlus.Test where
import Test.HUnit
import Test . HUnit . Ticket
import qualified Database.Sql.Util.Test as Test
import Database.Sql.Util.Catalog
import Database.Sql.Util.Lineage.ColumnPlus
import Database.Sql.Type as SQL
import Database.Sql.Position
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text.Lazy as TL
import Data.Proxy (Proxy(..))
instance Test.TestableAnalysis HasColumnLineage a where
type TestResult HasColumnLineage a = ColumnLineagePlus
runTest _ _ = snd . getColumnLineage
testHive :: TL.Text -> Catalog -> (ColumnLineagePlus -> Assertion) -> [Assertion]
testHive = Test.testResolvedHive (Proxy :: Proxy HasColumnLineage)
testVertica :: TL.Text -> Catalog -> (ColumnLineagePlus -> Assertion) -> [Assertion]
testVertica = Test.testResolvedVertica (Proxy :: Proxy HasColumnLineage)
testAll :: TL.Text -> Catalog -> (ColumnLineagePlus -> Assertion) -> [Assertion]
testAll = Test.testResolvedAll (Proxy :: Proxy HasColumnLineage)
testColumnLineage :: Test
testColumnLineage = test
[ "Generate column lineages for parsed queries" ~: concat
[ testAll "SELECT 1;" defaultTestCatalog (@?= M.empty)
, testAll "SELECT 1 FROM foo JOIN bar ON foo.a = bar.b;" defaultTestCatalog (@?= M.empty)
, testAll "SELECT 1 FROM foo GROUP BY 1;" defaultTestCatalog (@?= M.empty)
, testVertica "INSERT INTO foo VALUES (1, 2);"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, singleTableSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedTableName "default_db" "public" "foo"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, singleColumnSet Range{ start = Position 1 0 0, end = Position 1 29 29 }
$ FullyQualifiedColumnName "default_db" "public" "foo" "a"
)
]
)
, testVertica "INSERT INTO foo (SELECT a FROM bar);"
defaultTestCatalog
(@?= M.fromList
[
( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, ColumnPlusSet M.empty $ M.fromList
[ ( FullyQualifiedTableName "default_db" "public" "bar"
, S.singleton Range{start = Position 1 31 31, end = Position 1 34 34}
)
, ( FullyQualifiedTableName "default_db" "public" "foo"
, S.singleton Range{start = Position 1 12 12, end = Position 1 15 15}
)
]
)
,
( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, ColumnPlusSet
( M.fromList
[ ( FullyQualifiedColumnName "default_db" "public" "foo" "a"
, M.singleton (FieldChain M.empty) $ S.singleton Range{start = Position 1 0 0, end = Position 1 34 34}
)
, ( FullyQualifiedColumnName "default_db" "public" "bar" "a"
, M.singleton (FieldChain M.empty) $ S.singleton Range{start = Position 1 31 31, end = Position 1 34 34}
)
]
)
M.empty
)
]
)
, testHive "INSERT INTO TABLE foo SELECT a FROM bar;"
defaultTestCatalog
(@?= M.fromList
[
( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, ColumnPlusSet M.empty $ M.fromList
[ ( FullyQualifiedTableName "default_db" "public" "bar"
, S.singleton Range{start = Position 1 36 36, end = Position 1 39 39}
)
, ( FullyQualifiedTableName "default_db" "public" "foo"
, S.singleton Range{start = Position 1 18 18, end = Position 1 21 21}
)
]
)
,
( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, ColumnPlusSet
( M.fromList
[ ( FullyQualifiedColumnName "default_db" "public" "foo" "a"
, M.singleton (FieldChain M.empty) $ S.singleton Range{start = Position 1 0 0, end = Position 1 39 39}
)
, ( FullyQualifiedColumnName "default_db" "public" "bar" "a"
, M.singleton (FieldChain M.empty) $ S.singleton Range{start = Position 1 36 36, end = Position 1 39 39}
)
]
)
M.empty
)
]
)
, testVertica "CREATE TABLE baz LIKE bar;"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b", emptyColumnPlusSet )
]
)
, testHive "CREATE TABLE baz LIKE bar;"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b", emptyColumnPlusSet )
]
)
Presto support for CREATE TABLE is not yet implemented
, testVertica "CREATE TABLE baz (quux int);"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "quux", emptyColumnPlusSet )
]
)
, testHive "CREATE TABLE baz (quux int);"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "quux", emptyColumnPlusSet )
]
)
Presto support for CREATE TABLE is not yet implemented
, testVertica "CREATE TABLE baz AS (SELECT * FROM bar);"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz"
, singleTableSet Range{start = Position 1 35 35, end = Position 1 38 38}
$ FullyQualifiedTableName "default_db" "public" "bar"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a"
, singleColumnSet Range{start = Position 1 35 35, end = Position 1 38 38}
$ FullyQualifiedColumnName "default_db" "public" "bar" "a"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b"
, singleColumnSet Range{start = Position 1 35 35, end = Position 1 38 38}
$ FullyQualifiedColumnName "default_db" "public" "bar" "b"
)
]
)
, testHive "CREATE TABLE baz AS SELECT * FROM bar;"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz"
, singleTableSet Range{start = Position 1 34 34, end = Position 1 37 37}
$ FullyQualifiedTableName "default_db" "public" "bar"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a"
, singleColumnSet Range{start = Position 1 34 34, end = Position 1 37 37}
$ FullyQualifiedColumnName "default_db" "public" "bar" "a"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b"
, singleColumnSet Range{start = Position 1 34 34, end = Position 1 37 37}
$ FullyQualifiedColumnName "default_db" "public" "bar" "b"
)
]
)
, testVertica "CREATE TABLE baz AS (SELECT foo.a, bar.b FROM bar CROSS JOIN foo);"
defaultTestCatalog
(@?= M.fromList
[ ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a"
, singleColumnSet Range{start = Position 1 61 61, end = Position 1 64 64} -- interesting that this matches the table, not the column
$ FullyQualifiedColumnName "default_db" "public" "foo" "a"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b"
, singleColumnSet Range{start = Position 1 46 46, end = Position 1 49 49}
$ FullyQualifiedColumnName "default_db" "public" "bar" "b"
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "baz"
, ColumnPlusSet M.empty $ M.fromList
[ ( FullyQualifiedTableName "default_db" "public" "foo"
, S.singleton Range{start = Position 1 61 61, end = Position 1 64 64}
)
, ( FullyQualifiedTableName "default_db" "public" "bar"
, S.singleton Range{start = Position 1 46 46, end = Position 1 49 49}
)
]
)
]
)
, testHive "CREATE TABLE baz AS SELECT foo.a, bar.b FROM bar CROSS JOIN foo;"
defaultTestCatalog
(@?= M.fromList
[ ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a"
, singleColumnSet Range{start = Position 1 60 60, end = Position 1 63 63}
$ FullyQualifiedColumnName "default_db" "public" "foo" "a"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b"
, singleColumnSet Range{start = Position 1 45 45, end = Position 1 48 48}
$ FullyQualifiedColumnName "default_db" "public" "bar" "b"
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "baz"
, ColumnPlusSet M.empty $ M.fromList
[ ( FullyQualifiedTableName "default_db" "public" "foo"
, S.singleton Range{start = Position 1 60 60, end = Position 1 63 63}
)
, ( FullyQualifiedTableName "default_db" "public" "bar"
, S.singleton Range{start = Position 1 45 45, end = Position 1 48 48}
)
]
)
]
)
, testAll "DROP TABLE IF EXISTS foo;"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a", emptyColumnPlusSet )
]
)
, testAll "DELETE FROM foo;"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a", emptyColumnPlusSet )
]
)
, testAll "DELETE FROM foo WHERE EXISTS (SELECT * FROM bar);"
defaultTestCatalog
(@?= M.fromList
[ ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, ColumnPlusSet
( M.fromList
[ ( FullyQualifiedColumnName "default_db" "public" "foo" "a"
, M.singleton (FieldChain M.empty)
$ S.singleton Range{start = Position 1 12 12, end = Position 1 15 15}
)
]
)
( M.singleton (FullyQualifiedTableName "default_db" "public" "bar")
$ S.singleton Range{start = Position 1 44 44, end = Position 1 47 47}
)
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, ColumnPlusSet M.empty
( M.fromList
[ ( FullyQualifiedTableName "default_db" "public" "foo"
, S.singleton Range{start = Position 1 12 12, end = Position 1 15 15}
)
, ( FullyQualifiedTableName "default_db" "public" "bar"
, S.singleton Range{start = Position 1 44 44, end = Position 1 47 47}
)
]
)
)
]
)
, testAll "DELETE FROM foo WHERE EXISTS (SELECT * FROM bar WHERE foo.a = bar.a);"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, ColumnPlusSet
( M.fromList
[ ( FullyQualifiedColumnName "default_db" "public" "bar" "a"
, M.singleton (FieldChain M.empty)
$ S.singleton Range { start = Position 1 44 44, end = Position 1 47 47 }
)
, ( FullyQualifiedColumnName "default_db" "public" "foo" "a"
, M.singleton (FieldChain M.empty)
$ S.singleton Range { start = Position 1 12 12, end = Position 1 15 15 }
)
]
)
( M.fromList
[ ( FullyQualifiedTableName "default_db" "public" "bar"
, S.singleton Range { start = Position 1 44 44, end = Position 1 47 47 }
)
, ( FullyQualifiedTableName "default_db" "public" "foo"
, S.singleton Range { start = Position 1 12 12, end = Position 1 15 15 }
)
]
)
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, ColumnPlusSet
( M.fromList
[ ( FullyQualifiedColumnName "default_db" "public" "bar" "a"
, M.singleton (FieldChain M.empty)
$ S.singleton Range { start = Position 1 44 44, end = Position 1 47 47 }
)
, ( FullyQualifiedColumnName "default_db" "public" "foo" "a"
, M.singleton (FieldChain M.empty)
$ S.singleton Range { start = Position 1 12 12, end = Position 1 15 15 }
)
]
)
( M.singleton (FullyQualifiedTableName "default_db" "public" "bar")
$ S.singleton Range { start = Position 1 44 44, end = Position 1 47 47 }
)
)
]
)
, testVertica "ALTER TABLE foo RENAME TO bar;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "bar"
, singleTableSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedTableName "default_db" "public" "foo"
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "foo", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "bar" "a"
, singleColumnSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedColumnName "default_db" "public" "foo" "a"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a", emptyColumnPlusSet )
]
)
, testVertica "ALTER TABLE foo SET SCHEMA other_schema;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "other_schema" "foo"
, singleTableSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedTableName "default_db" "public" "foo"
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "foo", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "other_schema" "foo" "a"
, singleColumnSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedColumnName "default_db" "public" "foo" "a" )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a", emptyColumnPlusSet )
]
)
, testVertica "ALTER TABLE foo ADD PRIMARY KEY (bar);" defaultTestCatalog (@?= M.empty)
, testVertica "TRUNCATE TABLE foo;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a", emptyColumnPlusSet )
]
)
, testHive "TRUNCATE TABLE foo;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a", emptyColumnPlusSet )
]
)
Presto does n't have TRUNCATE
, testHive "TRUNCATE TABLE foo PARTITION (datestr = '2016-04-01', a = '42');" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, singleTableSet Range{start = Position 1 15 15, end = Position 1 18 18}
$ FullyQualifiedTableName "default_db" "public" "foo"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, singleColumnSet Range{start = Position 1 15 15, end = Position 1 18 18}
$ FullyQualifiedColumnName "default_db" "public" "foo" "a"
)
]
)
, testHive "ALTER TABLE foo SET LOCATION 'hdfs';" defaultTestCatalog (@?= M.empty)
, testVertica "ALTER PROJECTION foo RENAME TO bar;" defaultTestCatalog (@?= M.empty)
, testAll "GRANT SELECT ON foo TO bar;" defaultTestCatalog (@?= M.empty)
, testVertica "ALTER TABLE foo, foo1, bar RENAME TO foo1, foo2, baz;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "bar"
, emptyColumnPlusSet
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "bar" "a"
, emptyColumnPlusSet
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "bar" "b"
, emptyColumnPlusSet
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "baz"
, singleTableSet Range{start = Position 1 23 23, end = Position 1 26 26}
$ FullyQualifiedTableName "default_db" "public" "bar"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a"
, singleColumnSet Range{start = Position 1 23 23, end = Position 1 26 26}
$ FullyQualifiedColumnName "default_db" "public" "bar" "a"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b"
, singleColumnSet Range{start = Position 1 23 23, end = Position 1 26 26}
$ FullyQualifiedColumnName "default_db" "public" "bar" "b"
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, emptyColumnPlusSet
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, emptyColumnPlusSet
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo1" "a"
, emptyColumnPlusSet
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "foo1"
, emptyColumnPlusSet
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "foo2"
, singleTableSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedTableName "default_db" "public" "foo"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo2" "a"
, singleColumnSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedColumnName "default_db" "public" "foo" "a"
)
]
)
, testHive "INSERT OVERWRITE TABLE foo SELECT a FROM bar;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, singleTableSet Range{start = Position 1 41 41, end = Position 1 44 44}
$ FullyQualifiedTableName "default_db" "public" "bar"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, singleColumnSet Range{start = Position 1 41 41, end = Position 1 44 44}
$ FullyQualifiedColumnName "default_db" "public" "bar" "a"
)
]
)
, testHive "INSERT OVERWRITE TABLE foo SELECT a.x.y FROM bar;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, singleTableSet Range{start = Position 1 45 45, end = Position 1 48 48}
$ FullyQualifiedTableName "default_db" "public" "bar"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, mempty
{ columnPlusColumns = M.singleton (FullyQualifiedColumnName "default_db" "public" "bar" "a")
$ M.singleton
( FieldChain $ M.singleton (StructFieldName () "x")
$ FieldChain $ M.singleton (StructFieldName () "y")
$ FieldChain M.empty
)
( S.singleton Range{start = Position 1 34 34, end = Position 1 37 37} )
}
)
]
)
, testVertica "CREATE TABLE baz AS (SELECT a LIKE b as c FROM bar);"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz"
, singleTableSet Range{start = Position 1 47 47, end = Position 1 50 50}
$ FullyQualifiedTableName "default_db" "public" "bar"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "c"
, mempty
{ columnPlusColumns = M.fromList
[ ( FullyQualifiedColumnName "default_db" "public" "bar" "a", M.singleton (FieldChain mempty)
$ S.singleton Range{start = Position 1 47 47, end = Position 1 50 50}
)
, (FullyQualifiedColumnName "default_db" "public" "bar" "b", M.singleton (FieldChain mempty)
$ S.singleton Range{start = Position 1 47 47, end = Position 1 50 50}
)
]
}
)
]
)
]
]
type DefaultCatalogType =
'[Database "default_db"
'[ Schema "public"
'[ Table "foo" '[Column "a" SqlType]
, Table "bar"
'[ Column "a" SqlType
, Column "b" SqlType
]
]
]
]
defaultCatalogProxy :: Proxy DefaultCatalogType
defaultCatalogProxy = Proxy
defaultDatabase :: DatabaseName ()
defaultDatabase = DatabaseName () "default_db"
publicSchema :: UQSchemaName ()
publicSchema = mkNormalSchema "public" ()
defaultTestCatalog :: Catalog
defaultTestCatalog = makeCatalog (mkCatalog defaultCatalogProxy) [publicSchema] defaultDatabase
tests :: Test
tests = test [ testColumnLineage ]
| null | https://raw.githubusercontent.com/uber/queryparser/6015e8f273f4498326fec0315ac5580d7036f8a4/test/Database/Sql/Util/Lineage/ColumnPlus/Test.hs | haskell |
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
interesting that this matches the table, not the column | Copyright ( c ) 2017 Uber Technologies , Inc.
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
# LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE MultiParamTypeClasses #
# OPTIONS_GHC -fno - warn - orphans #
module Database.Sql.Util.Lineage.ColumnPlus.Test where
import Test.HUnit
import Test . HUnit . Ticket
import qualified Database.Sql.Util.Test as Test
import Database.Sql.Util.Catalog
import Database.Sql.Util.Lineage.ColumnPlus
import Database.Sql.Type as SQL
import Database.Sql.Position
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text.Lazy as TL
import Data.Proxy (Proxy(..))
instance Test.TestableAnalysis HasColumnLineage a where
type TestResult HasColumnLineage a = ColumnLineagePlus
runTest _ _ = snd . getColumnLineage
testHive :: TL.Text -> Catalog -> (ColumnLineagePlus -> Assertion) -> [Assertion]
testHive = Test.testResolvedHive (Proxy :: Proxy HasColumnLineage)
testVertica :: TL.Text -> Catalog -> (ColumnLineagePlus -> Assertion) -> [Assertion]
testVertica = Test.testResolvedVertica (Proxy :: Proxy HasColumnLineage)
testAll :: TL.Text -> Catalog -> (ColumnLineagePlus -> Assertion) -> [Assertion]
testAll = Test.testResolvedAll (Proxy :: Proxy HasColumnLineage)
testColumnLineage :: Test
testColumnLineage = test
[ "Generate column lineages for parsed queries" ~: concat
[ testAll "SELECT 1;" defaultTestCatalog (@?= M.empty)
, testAll "SELECT 1 FROM foo JOIN bar ON foo.a = bar.b;" defaultTestCatalog (@?= M.empty)
, testAll "SELECT 1 FROM foo GROUP BY 1;" defaultTestCatalog (@?= M.empty)
, testVertica "INSERT INTO foo VALUES (1, 2);"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, singleTableSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedTableName "default_db" "public" "foo"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, singleColumnSet Range{ start = Position 1 0 0, end = Position 1 29 29 }
$ FullyQualifiedColumnName "default_db" "public" "foo" "a"
)
]
)
, testVertica "INSERT INTO foo (SELECT a FROM bar);"
defaultTestCatalog
(@?= M.fromList
[
( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, ColumnPlusSet M.empty $ M.fromList
[ ( FullyQualifiedTableName "default_db" "public" "bar"
, S.singleton Range{start = Position 1 31 31, end = Position 1 34 34}
)
, ( FullyQualifiedTableName "default_db" "public" "foo"
, S.singleton Range{start = Position 1 12 12, end = Position 1 15 15}
)
]
)
,
( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, ColumnPlusSet
( M.fromList
[ ( FullyQualifiedColumnName "default_db" "public" "foo" "a"
, M.singleton (FieldChain M.empty) $ S.singleton Range{start = Position 1 0 0, end = Position 1 34 34}
)
, ( FullyQualifiedColumnName "default_db" "public" "bar" "a"
, M.singleton (FieldChain M.empty) $ S.singleton Range{start = Position 1 31 31, end = Position 1 34 34}
)
]
)
M.empty
)
]
)
, testHive "INSERT INTO TABLE foo SELECT a FROM bar;"
defaultTestCatalog
(@?= M.fromList
[
( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, ColumnPlusSet M.empty $ M.fromList
[ ( FullyQualifiedTableName "default_db" "public" "bar"
, S.singleton Range{start = Position 1 36 36, end = Position 1 39 39}
)
, ( FullyQualifiedTableName "default_db" "public" "foo"
, S.singleton Range{start = Position 1 18 18, end = Position 1 21 21}
)
]
)
,
( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, ColumnPlusSet
( M.fromList
[ ( FullyQualifiedColumnName "default_db" "public" "foo" "a"
, M.singleton (FieldChain M.empty) $ S.singleton Range{start = Position 1 0 0, end = Position 1 39 39}
)
, ( FullyQualifiedColumnName "default_db" "public" "bar" "a"
, M.singleton (FieldChain M.empty) $ S.singleton Range{start = Position 1 36 36, end = Position 1 39 39}
)
]
)
M.empty
)
]
)
, testVertica "CREATE TABLE baz LIKE bar;"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b", emptyColumnPlusSet )
]
)
, testHive "CREATE TABLE baz LIKE bar;"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b", emptyColumnPlusSet )
]
)
Presto support for CREATE TABLE is not yet implemented
, testVertica "CREATE TABLE baz (quux int);"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "quux", emptyColumnPlusSet )
]
)
, testHive "CREATE TABLE baz (quux int);"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "quux", emptyColumnPlusSet )
]
)
Presto support for CREATE TABLE is not yet implemented
, testVertica "CREATE TABLE baz AS (SELECT * FROM bar);"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz"
, singleTableSet Range{start = Position 1 35 35, end = Position 1 38 38}
$ FullyQualifiedTableName "default_db" "public" "bar"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a"
, singleColumnSet Range{start = Position 1 35 35, end = Position 1 38 38}
$ FullyQualifiedColumnName "default_db" "public" "bar" "a"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b"
, singleColumnSet Range{start = Position 1 35 35, end = Position 1 38 38}
$ FullyQualifiedColumnName "default_db" "public" "bar" "b"
)
]
)
, testHive "CREATE TABLE baz AS SELECT * FROM bar;"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz"
, singleTableSet Range{start = Position 1 34 34, end = Position 1 37 37}
$ FullyQualifiedTableName "default_db" "public" "bar"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a"
, singleColumnSet Range{start = Position 1 34 34, end = Position 1 37 37}
$ FullyQualifiedColumnName "default_db" "public" "bar" "a"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b"
, singleColumnSet Range{start = Position 1 34 34, end = Position 1 37 37}
$ FullyQualifiedColumnName "default_db" "public" "bar" "b"
)
]
)
, testVertica "CREATE TABLE baz AS (SELECT foo.a, bar.b FROM bar CROSS JOIN foo);"
defaultTestCatalog
(@?= M.fromList
[ ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a"
$ FullyQualifiedColumnName "default_db" "public" "foo" "a"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b"
, singleColumnSet Range{start = Position 1 46 46, end = Position 1 49 49}
$ FullyQualifiedColumnName "default_db" "public" "bar" "b"
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "baz"
, ColumnPlusSet M.empty $ M.fromList
[ ( FullyQualifiedTableName "default_db" "public" "foo"
, S.singleton Range{start = Position 1 61 61, end = Position 1 64 64}
)
, ( FullyQualifiedTableName "default_db" "public" "bar"
, S.singleton Range{start = Position 1 46 46, end = Position 1 49 49}
)
]
)
]
)
, testHive "CREATE TABLE baz AS SELECT foo.a, bar.b FROM bar CROSS JOIN foo;"
defaultTestCatalog
(@?= M.fromList
[ ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a"
, singleColumnSet Range{start = Position 1 60 60, end = Position 1 63 63}
$ FullyQualifiedColumnName "default_db" "public" "foo" "a"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b"
, singleColumnSet Range{start = Position 1 45 45, end = Position 1 48 48}
$ FullyQualifiedColumnName "default_db" "public" "bar" "b"
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "baz"
, ColumnPlusSet M.empty $ M.fromList
[ ( FullyQualifiedTableName "default_db" "public" "foo"
, S.singleton Range{start = Position 1 60 60, end = Position 1 63 63}
)
, ( FullyQualifiedTableName "default_db" "public" "bar"
, S.singleton Range{start = Position 1 45 45, end = Position 1 48 48}
)
]
)
]
)
, testAll "DROP TABLE IF EXISTS foo;"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a", emptyColumnPlusSet )
]
)
, testAll "DELETE FROM foo;"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a", emptyColumnPlusSet )
]
)
, testAll "DELETE FROM foo WHERE EXISTS (SELECT * FROM bar);"
defaultTestCatalog
(@?= M.fromList
[ ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, ColumnPlusSet
( M.fromList
[ ( FullyQualifiedColumnName "default_db" "public" "foo" "a"
, M.singleton (FieldChain M.empty)
$ S.singleton Range{start = Position 1 12 12, end = Position 1 15 15}
)
]
)
( M.singleton (FullyQualifiedTableName "default_db" "public" "bar")
$ S.singleton Range{start = Position 1 44 44, end = Position 1 47 47}
)
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, ColumnPlusSet M.empty
( M.fromList
[ ( FullyQualifiedTableName "default_db" "public" "foo"
, S.singleton Range{start = Position 1 12 12, end = Position 1 15 15}
)
, ( FullyQualifiedTableName "default_db" "public" "bar"
, S.singleton Range{start = Position 1 44 44, end = Position 1 47 47}
)
]
)
)
]
)
, testAll "DELETE FROM foo WHERE EXISTS (SELECT * FROM bar WHERE foo.a = bar.a);"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, ColumnPlusSet
( M.fromList
[ ( FullyQualifiedColumnName "default_db" "public" "bar" "a"
, M.singleton (FieldChain M.empty)
$ S.singleton Range { start = Position 1 44 44, end = Position 1 47 47 }
)
, ( FullyQualifiedColumnName "default_db" "public" "foo" "a"
, M.singleton (FieldChain M.empty)
$ S.singleton Range { start = Position 1 12 12, end = Position 1 15 15 }
)
]
)
( M.fromList
[ ( FullyQualifiedTableName "default_db" "public" "bar"
, S.singleton Range { start = Position 1 44 44, end = Position 1 47 47 }
)
, ( FullyQualifiedTableName "default_db" "public" "foo"
, S.singleton Range { start = Position 1 12 12, end = Position 1 15 15 }
)
]
)
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, ColumnPlusSet
( M.fromList
[ ( FullyQualifiedColumnName "default_db" "public" "bar" "a"
, M.singleton (FieldChain M.empty)
$ S.singleton Range { start = Position 1 44 44, end = Position 1 47 47 }
)
, ( FullyQualifiedColumnName "default_db" "public" "foo" "a"
, M.singleton (FieldChain M.empty)
$ S.singleton Range { start = Position 1 12 12, end = Position 1 15 15 }
)
]
)
( M.singleton (FullyQualifiedTableName "default_db" "public" "bar")
$ S.singleton Range { start = Position 1 44 44, end = Position 1 47 47 }
)
)
]
)
, testVertica "ALTER TABLE foo RENAME TO bar;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "bar"
, singleTableSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedTableName "default_db" "public" "foo"
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "foo", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "bar" "a"
, singleColumnSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedColumnName "default_db" "public" "foo" "a"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a", emptyColumnPlusSet )
]
)
, testVertica "ALTER TABLE foo SET SCHEMA other_schema;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "other_schema" "foo"
, singleTableSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedTableName "default_db" "public" "foo"
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "foo", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "other_schema" "foo" "a"
, singleColumnSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedColumnName "default_db" "public" "foo" "a" )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a", emptyColumnPlusSet )
]
)
, testVertica "ALTER TABLE foo ADD PRIMARY KEY (bar);" defaultTestCatalog (@?= M.empty)
, testVertica "TRUNCATE TABLE foo;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a", emptyColumnPlusSet )
]
)
, testHive "TRUNCATE TABLE foo;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo", emptyColumnPlusSet )
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a", emptyColumnPlusSet )
]
)
Presto does n't have TRUNCATE
, testHive "TRUNCATE TABLE foo PARTITION (datestr = '2016-04-01', a = '42');" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, singleTableSet Range{start = Position 1 15 15, end = Position 1 18 18}
$ FullyQualifiedTableName "default_db" "public" "foo"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, singleColumnSet Range{start = Position 1 15 15, end = Position 1 18 18}
$ FullyQualifiedColumnName "default_db" "public" "foo" "a"
)
]
)
, testHive "ALTER TABLE foo SET LOCATION 'hdfs';" defaultTestCatalog (@?= M.empty)
, testVertica "ALTER PROJECTION foo RENAME TO bar;" defaultTestCatalog (@?= M.empty)
, testAll "GRANT SELECT ON foo TO bar;" defaultTestCatalog (@?= M.empty)
, testVertica "ALTER TABLE foo, foo1, bar RENAME TO foo1, foo2, baz;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "bar"
, emptyColumnPlusSet
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "bar" "a"
, emptyColumnPlusSet
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "bar" "b"
, emptyColumnPlusSet
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "baz"
, singleTableSet Range{start = Position 1 23 23, end = Position 1 26 26}
$ FullyQualifiedTableName "default_db" "public" "bar"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "a"
, singleColumnSet Range{start = Position 1 23 23, end = Position 1 26 26}
$ FullyQualifiedColumnName "default_db" "public" "bar" "a"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "b"
, singleColumnSet Range{start = Position 1 23 23, end = Position 1 26 26}
$ FullyQualifiedColumnName "default_db" "public" "bar" "b"
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, emptyColumnPlusSet
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, emptyColumnPlusSet
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo1" "a"
, emptyColumnPlusSet
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "foo1"
, emptyColumnPlusSet
)
, ( Left $ FullyQualifiedTableName "default_db" "public" "foo2"
, singleTableSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedTableName "default_db" "public" "foo"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo2" "a"
, singleColumnSet Range{start = Position 1 12 12, end = Position 1 15 15}
$ FullyQualifiedColumnName "default_db" "public" "foo" "a"
)
]
)
, testHive "INSERT OVERWRITE TABLE foo SELECT a FROM bar;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, singleTableSet Range{start = Position 1 41 41, end = Position 1 44 44}
$ FullyQualifiedTableName "default_db" "public" "bar"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, singleColumnSet Range{start = Position 1 41 41, end = Position 1 44 44}
$ FullyQualifiedColumnName "default_db" "public" "bar" "a"
)
]
)
, testHive "INSERT OVERWRITE TABLE foo SELECT a.x.y FROM bar;" defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "foo"
, singleTableSet Range{start = Position 1 45 45, end = Position 1 48 48}
$ FullyQualifiedTableName "default_db" "public" "bar"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "foo" "a"
, mempty
{ columnPlusColumns = M.singleton (FullyQualifiedColumnName "default_db" "public" "bar" "a")
$ M.singleton
( FieldChain $ M.singleton (StructFieldName () "x")
$ FieldChain $ M.singleton (StructFieldName () "y")
$ FieldChain M.empty
)
( S.singleton Range{start = Position 1 34 34, end = Position 1 37 37} )
}
)
]
)
, testVertica "CREATE TABLE baz AS (SELECT a LIKE b as c FROM bar);"
defaultTestCatalog
(@?= M.fromList
[ ( Left $ FullyQualifiedTableName "default_db" "public" "baz"
, singleTableSet Range{start = Position 1 47 47, end = Position 1 50 50}
$ FullyQualifiedTableName "default_db" "public" "bar"
)
, ( Right $ FullyQualifiedColumnName "default_db" "public" "baz" "c"
, mempty
{ columnPlusColumns = M.fromList
[ ( FullyQualifiedColumnName "default_db" "public" "bar" "a", M.singleton (FieldChain mempty)
$ S.singleton Range{start = Position 1 47 47, end = Position 1 50 50}
)
, (FullyQualifiedColumnName "default_db" "public" "bar" "b", M.singleton (FieldChain mempty)
$ S.singleton Range{start = Position 1 47 47, end = Position 1 50 50}
)
]
}
)
]
)
]
]
type DefaultCatalogType =
'[Database "default_db"
'[ Schema "public"
'[ Table "foo" '[Column "a" SqlType]
, Table "bar"
'[ Column "a" SqlType
, Column "b" SqlType
]
]
]
]
defaultCatalogProxy :: Proxy DefaultCatalogType
defaultCatalogProxy = Proxy
defaultDatabase :: DatabaseName ()
defaultDatabase = DatabaseName () "default_db"
publicSchema :: UQSchemaName ()
publicSchema = mkNormalSchema "public" ()
defaultTestCatalog :: Catalog
defaultTestCatalog = makeCatalog (mkCatalog defaultCatalogProxy) [publicSchema] defaultDatabase
tests :: Test
tests = test [ testColumnLineage ]
|
1ab4e132dec83093f44a7cb0a8ca11351d48007e7cbd69cfd41fb59b7b64a7a9 | imandra-ai/ocaml-opentelemetry | status_pp.mli | (** status.proto Pretty Printing *)
* { 2 Formatters }
val pp_status : Format.formatter -> Status_types.status -> unit
(** [pp_status v] formats v *)
| null | https://raw.githubusercontent.com/imandra-ai/ocaml-opentelemetry/62d1a9cec785186966e880c91c4c109875b0dd62/src/status_pp.mli | ocaml | * status.proto Pretty Printing
* [pp_status v] formats v |
* { 2 Formatters }
val pp_status : Format.formatter -> Status_types.status -> unit
|
2dcb63f7376eaaacaf8ff96084bcae74198fd67a8a9614c6087d05c49d32081b | gedge-platform/gedge-platform | rabbit_mirror_queue_slave.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2010 - 2021 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(rabbit_mirror_queue_slave).
%% For general documentation of HA design, see
%% rabbit_mirror_queue_coordinator
%%
We receive messages from GM and from publishers , and the gm
%% messages can arrive either before or after the 'actual' message.
All instructions from the GM group must be processed in the order
%% in which they're received.
-export([set_maximum_since_use/2, info/1, go/2]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
code_change/3, handle_pre_hibernate/1, prioritise_call/4,
prioritise_cast/3, prioritise_info/3, format_message_queue/2]).
-export([joined/2, members_changed/3, handle_msg/3, handle_terminate/2]).
-behaviour(gen_server2).
-behaviour(gm).
-include_lib("rabbit_common/include/rabbit.hrl").
-include("amqqueue.hrl").
-include("gm_specs.hrl").
%%----------------------------------------------------------------------------
-define(INFO_KEYS,
[pid,
name,
master_pid,
is_synchronised
]).
-define(SYNC_INTERVAL, 25). %% milliseconds
-define(RAM_DURATION_UPDATE_INTERVAL, 5000).
20 seconds
-record(state, { q,
gm,
backing_queue,
backing_queue_state,
sync_timer_ref,
rate_timer_ref,
: : Pid - > { Q Msg , Set MsgId , ChState }
: : MsgId - > AckTag
msg_id_status,
known_senders,
%% Master depth - local depth
depth_delta
}).
%%----------------------------------------------------------------------------
set_maximum_since_use(QPid, Age) ->
gen_server2:cast(QPid, {set_maximum_since_use, Age}).
info(QPid) -> gen_server2:call(QPid, info, infinity).
init(Q) when ?is_amqqueue(Q) ->
QName = amqqueue:get_name(Q),
?store_proc_name(QName),
{ok, {not_started, Q}, hibernate,
{backoff, ?HIBERNATE_AFTER_MIN, ?HIBERNATE_AFTER_MIN,
?DESIRED_HIBERNATE}, ?MODULE}.
go(SPid, sync) -> gen_server2:call(SPid, go, infinity);
go(SPid, async) -> gen_server2:cast(SPid, go).
handle_go(Q0) when ?is_amqqueue(Q0) ->
QName = amqqueue:get_name(Q0),
We join the GM group before we add ourselves to the amqqueue
%% record. As a result:
1 . We can receive msgs from GM that correspond to messages we will
%% never receive from publishers.
2 . When we receive a message from publishers , we must receive a
message from the GM group for it .
3 . However , that instruction from the GM group can arrive either
%% before or after the actual message. We need to be able to
distinguish between GM instructions arriving early , and case ( 1 )
%% above.
%%
process_flag(trap_exit, true), %% amqqueue_process traps exits too.
{ok, GM} = gm:start_link(QName, ?MODULE, [self()],
fun rabbit_misc:execute_mnesia_transaction/1),
MRef = erlang:monitor(process, GM),
%% We ignore the DOWN message because we are also linked and
%% trapping exits, we just want to not get stuck and we will exit
%% later.
receive
{joined, GM} -> erlang:demonitor(MRef, [flush]),
ok;
{'DOWN', MRef, _, _, _} -> ok
end,
Self = self(),
Node = node(),
case rabbit_misc:execute_mnesia_transaction(
fun() -> init_it(Self, GM, Node, QName) end) of
{new, QPid, GMPids} ->
ok = file_handle_cache:register_callback(
rabbit_amqqueue, set_maximum_since_use, [Self]),
ok = rabbit_memory_monitor:register(
Self, {rabbit_amqqueue, set_ram_duration_target, [Self]}),
{ok, BQ} = application:get_env(backing_queue_module),
Q1 = amqqueue:set_pid(Q0, QPid),
_ = BQ:delete_crashed(Q1), %% For crash recovery
BQS = bq_init(BQ, Q1, new),
State = #state { q = Q1,
gm = GM,
backing_queue = BQ,
backing_queue_state = BQS,
rate_timer_ref = undefined,
sync_timer_ref = undefined,
sender_queues = #{},
msg_id_ack = #{},
msg_id_status = #{},
known_senders = pmon:new(delegate),
depth_delta = undefined
},
ok = gm:broadcast(GM, request_depth),
ok = gm:validate_members(GM, [GM | [G || {G, _} <- GMPids]]),
rabbit_mirror_queue_misc:maybe_auto_sync(Q1),
{ok, State};
{stale, StalePid} ->
rabbit_mirror_queue_misc:log_warning(
QName, "Detected stale HA master: ~p~n", [StalePid]),
gm:leave(GM),
{error, {stale_master_pid, StalePid}};
duplicate_live_master ->
gm:leave(GM),
{error, {duplicate_live_master, Node}};
existing ->
gm:leave(GM),
{error, normal};
master_in_recovery ->
gm:leave(GM),
%% The queue record vanished - we must have a master starting
%% concurrently with us. In that case we can safely decide to do
%% nothing here, and the master will start us in
master : init_with_existing_bq/3
{error, normal}
end.
init_it(Self, GM, Node, QName) ->
case mnesia:read({rabbit_queue, QName}) of
[Q] when ?is_amqqueue(Q) ->
QPid = amqqueue:get_pid(Q),
SPids = amqqueue:get_slave_pids(Q),
GMPids = amqqueue:get_gm_pids(Q),
PSPids = amqqueue:get_slave_pids_pending_shutdown(Q),
case [Pid || Pid <- [QPid | SPids], node(Pid) =:= Node] of
[] -> stop_pending_slaves(QName, PSPids),
add_slave(Q, Self, GM),
{new, QPid, GMPids};
[QPid] -> case rabbit_mnesia:is_process_alive(QPid) of
true -> duplicate_live_master;
false -> {stale, QPid}
end;
[SPid] -> case rabbit_mnesia:is_process_alive(SPid) of
true -> existing;
false -> GMPids1 = [T || T = {_, S} <- GMPids, S =/= SPid],
SPids1 = SPids -- [SPid],
Q1 = amqqueue:set_slave_pids(Q, SPids1),
Q2 = amqqueue:set_gm_pids(Q1, GMPids1),
add_slave(Q2, Self, GM),
{new, QPid, GMPids1}
end
end;
[] ->
master_in_recovery
end.
%% Pending mirrors have been asked to stop by the master, but despite the node
%% being up these did not answer on the expected timeout. Stop local mirrors now.
stop_pending_slaves(QName, Pids) ->
[begin
rabbit_mirror_queue_misc:log_warning(
QName, "Detected a non-responsive classic queue mirror, stopping it: ~p~n", [Pid]),
case erlang:process_info(Pid, dictionary) of
undefined -> ok;
{dictionary, Dict} ->
Vhost = QName#resource.virtual_host,
{ok, AmqQSup} = rabbit_amqqueue_sup_sup:find_for_vhost(Vhost),
case proplists:get_value('$ancestors', Dict) of
[Sup, AmqQSup | _] ->
exit(Sup, kill),
exit(Pid, kill);
_ ->
ok
end
end
end || Pid <- Pids, node(Pid) =:= node(),
true =:= erlang:is_process_alive(Pid)].
%% Add to the end, so they are in descending order of age, see
%% rabbit_mirror_queue_misc:promote_slave/1
add_slave(Q0, New, GM) when ?is_amqqueue(Q0) ->
SPids = amqqueue:get_slave_pids(Q0),
GMPids = amqqueue:get_gm_pids(Q0),
SPids1 = SPids ++ [New],
GMPids1 = [{GM, New} | GMPids],
Q1 = amqqueue:set_slave_pids(Q0, SPids1),
Q2 = amqqueue:set_gm_pids(Q1, GMPids1),
rabbit_mirror_queue_misc:store_updated_slaves(Q2).
handle_call(go, _From, {not_started, Q} = NotStarted) ->
case handle_go(Q) of
{ok, State} -> {reply, ok, State};
{error, Error} -> {stop, Error, NotStarted}
end;
handle_call({gm_deaths, DeadGMPids}, From,
State = #state{ gm = GM, q = Q,
backing_queue = BQ,
backing_queue_state = BQS}) when ?is_amqqueue(Q) ->
QName = amqqueue:get_name(Q),
MPid = amqqueue:get_pid(Q),
Self = self(),
case rabbit_mirror_queue_misc:remove_from_queue(QName, Self, DeadGMPids) of
{error, not_found} ->
gen_server2:reply(From, ok),
{stop, normal, State};
{error, {not_synced, _SPids}} ->
BQ:delete_and_terminate({error, not_synced}, BQS),
{stop, normal, State#state{backing_queue_state = undefined}};
{ok, Pid, DeadPids, ExtraNodes} ->
rabbit_mirror_queue_misc:report_deaths(Self, false, QName,
DeadPids),
case Pid of
MPid ->
%% master hasn't changed
gen_server2:reply(From, ok),
rabbit_mirror_queue_misc:add_mirrors(
QName, ExtraNodes, async),
noreply(State);
Self ->
%% we've become master
QueueState = promote_me(From, State),
rabbit_mirror_queue_misc:add_mirrors(
QName, ExtraNodes, async),
{become, rabbit_amqqueue_process, QueueState, hibernate};
_ ->
%% master has changed to not us
gen_server2:reply(From, ok),
%% see rabbitmq-server#914;
It 's not always guaranteed that we wo n't have ExtraNodes .
If gm alters , master can change to not us with extra nodes ,
%% in which case we attempt to add mirrors on those nodes.
case ExtraNodes of
[] -> void;
_ -> rabbit_mirror_queue_misc:add_mirrors(
QName, ExtraNodes, async)
end,
Since GM is by nature lazy we need to make sure
%% there is some traffic when a master dies, to
%% make sure all mirrors get informed of the
%% death. That is all process_death does, create
%% some traffic.
ok = gm:broadcast(GM, process_death),
Q1 = amqqueue:set_pid(Q, Pid),
State1 = State#state{q = Q1},
noreply(State1)
end
end;
handle_call(info, _From, State) ->
reply(infos(?INFO_KEYS, State), State).
handle_cast(go, {not_started, Q} = NotStarted) ->
case handle_go(Q) of
{ok, State} -> {noreply, State};
{error, Error} -> {stop, Error, NotStarted}
end;
handle_cast({run_backing_queue, Mod, Fun}, State) ->
noreply(run_backing_queue(Mod, Fun, State));
handle_cast({gm, Instruction}, State = #state{q = Q0}) when ?is_amqqueue(Q0) ->
QName = amqqueue:get_name(Q0),
case rabbit_amqqueue:lookup(QName) of
{ok, Q1} when ?is_amqqueue(Q1) ->
SPids = amqqueue:get_slave_pids(Q1),
case lists:member(self(), SPids) of
true ->
handle_process_result(process_instruction(Instruction, State));
false ->
%% Potentially a duplicated mirror caused by a partial partition,
%% will stop as a new mirror could start unaware of our presence
{stop, shutdown, State}
end;
{error, not_found} ->
Would not expect this to happen after fixing # 953
{stop, shutdown, State}
end;
handle_cast({deliver, Delivery = #delivery{sender = Sender, flow = Flow}, true},
State) ->
%% Asynchronous, non-"mandatory", deliver mode.
%% We are acking messages to the channel process that sent us
%% the message delivery. See
%% rabbit_amqqueue_process:handle_ch_down for more info.
%% If message is rejected by the master, the publish will be nacked
%% even if mirrors confirm it. No need to check for length here.
maybe_flow_ack(Sender, Flow),
noreply(maybe_enqueue_message(Delivery, State));
handle_cast({sync_start, Ref, Syncer},
State = #state { depth_delta = DD,
backing_queue = BQ,
backing_queue_state = BQS }) ->
State1 = #state{rate_timer_ref = TRef} = ensure_rate_timer(State),
S = fun({MA, TRefN, BQSN}) ->
State1#state{depth_delta = undefined,
msg_id_ack = maps:from_list(MA),
rate_timer_ref = TRefN,
backing_queue_state = BQSN}
end,
case rabbit_mirror_queue_sync:slave(
DD, Ref, TRef, Syncer, BQ, BQS,
fun (BQN, BQSN) ->
BQSN1 = update_ram_duration(BQN, BQSN),
TRefN = rabbit_misc:send_after(?RAM_DURATION_UPDATE_INTERVAL,
self(), update_ram_duration),
{TRefN, BQSN1}
end) of
denied -> noreply(State1);
{ok, Res} -> noreply(set_delta(0, S(Res)));
{failed, Res} -> noreply(S(Res));
{stop, Reason, Res} -> {stop, Reason, S(Res)}
end;
handle_cast({set_maximum_since_use, Age}, State) ->
ok = file_handle_cache:set_maximum_since_use(Age),
noreply(State);
handle_cast({set_ram_duration_target, Duration},
State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
BQS1 = BQ:set_ram_duration_target(Duration, BQS),
noreply(State #state { backing_queue_state = BQS1 });
handle_cast(policy_changed, State) ->
%% During partial partitions, we might end up receiving messages expected by a master
%% Ignore them
noreply(State).
handle_info(update_ram_duration, State = #state{backing_queue = BQ,
backing_queue_state = BQS}) ->
BQS1 = update_ram_duration(BQ, BQS),
%% Don't call noreply/1, we don't want to set timers
{State1, Timeout} = next_state(State #state {
rate_timer_ref = undefined,
backing_queue_state = BQS1 }),
{noreply, State1, Timeout};
handle_info(sync_timeout, State) ->
noreply(backing_queue_timeout(
State #state { sync_timer_ref = undefined }));
handle_info(timeout, State) ->
noreply(backing_queue_timeout(State));
handle_info({'DOWN', _MonitorRef, process, ChPid, _Reason}, State) ->
local_sender_death(ChPid, State),
noreply(maybe_forget_sender(ChPid, down_from_ch, State));
handle_info({'EXIT', _Pid, Reason}, State) ->
{stop, Reason, State};
handle_info({bump_credit, Msg}, State) ->
credit_flow:handle_bump_msg(Msg),
noreply(State);
handle_info(bump_reduce_memory_use, State = #state{backing_queue = BQ,
backing_queue_state = BQS}) ->
BQS1 = BQ:handle_info(bump_reduce_memory_use, BQS),
BQS2 = BQ:resume(BQS1),
noreply(State#state{
backing_queue_state = BQS2
});
%% In the event of a short partition during sync we can detect the
%% master's 'death', drop out of sync, and then receive sync messages
%% which were still in flight. Ignore them.
handle_info({sync_msg, _Ref, _Msg, _Props, _Unacked}, State) ->
noreply(State);
handle_info({sync_complete, _Ref}, State) ->
noreply(State);
handle_info(Msg, State) ->
{stop, {unexpected_info, Msg}, State}.
terminate(_Reason, {not_started, _Q}) ->
ok;
terminate(_Reason, #state { backing_queue_state = undefined }) ->
We 've received a delete_and_terminate from gm , thus nothing to
%% do here.
ok;
terminate({shutdown, dropped} = R, State = #state{backing_queue = BQ,
backing_queue_state = BQS}) ->
%% See rabbit_mirror_queue_master:terminate/2
terminate_common(State),
BQ:delete_and_terminate(R, BQS);
terminate(shutdown, State) ->
terminate_shutdown(shutdown, State);
terminate({shutdown, _} = R, State) ->
terminate_shutdown(R, State);
terminate(Reason, State = #state{backing_queue = BQ,
backing_queue_state = BQS}) ->
terminate_common(State),
BQ:delete_and_terminate(Reason, BQS).
If the is shutdown , or { shutdown , _ } , it is not the queue
%% being deleted: it's just the node going down. Even though we're a
%% mirror, we have no idea whether or not we'll be the only copy coming
%% back up. Thus we must assume we will be, and preserve anything we
%% have on disk.
terminate_shutdown(Reason, State = #state{backing_queue = BQ,
backing_queue_state = BQS}) ->
terminate_common(State),
BQ:terminate(Reason, BQS).
terminate_common(State) ->
ok = rabbit_memory_monitor:deregister(self()),
stop_rate_timer(stop_sync_timer(State)).
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
handle_pre_hibernate({not_started, _Q} = State) ->
{hibernate, State};
handle_pre_hibernate(State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
{RamDuration, BQS1} = BQ:ram_duration(BQS),
DesiredDuration =
rabbit_memory_monitor:report_ram_duration(self(), RamDuration),
BQS2 = BQ:set_ram_duration_target(DesiredDuration, BQS1),
BQS3 = BQ:handle_pre_hibernate(BQS2),
{hibernate, stop_rate_timer(State #state { backing_queue_state = BQS3 })}.
prioritise_call(Msg, _From, _Len, _State) ->
case Msg of
info -> 9;
{gm_deaths, _Dead} -> 5;
_ -> 0
end.
prioritise_cast(Msg, _Len, _State) ->
case Msg of
{set_ram_duration_target, _Duration} -> 8;
{set_maximum_since_use, _Age} -> 8;
{run_backing_queue, _Mod, _Fun} -> 6;
{gm, _Msg} -> 5;
_ -> 0
end.
prioritise_info(Msg, _Len, _State) ->
case Msg of
update_ram_duration -> 8;
sync_timeout -> 6;
_ -> 0
end.
format_message_queue(Opt, MQ) -> rabbit_misc:format_message_queue(Opt, MQ).
%% ---------------------------------------------------------------------------
GM
%% ---------------------------------------------------------------------------
joined([SPid], _Members) -> SPid ! {joined, self()}, ok.
members_changed([_SPid], _Births, []) ->
ok;
members_changed([ SPid], _Births, Deaths) ->
case rabbit_misc:with_exit_handler(
rabbit_misc:const(ok),
fun() ->
gen_server2:call(SPid, {gm_deaths, Deaths}, infinity)
end) of
ok -> ok;
{promote, CPid} -> {become, rabbit_mirror_queue_coordinator, [CPid]}
end.
handle_msg([_SPid], _From, hibernate_heartbeat) ->
%% See rabbit_mirror_queue_coordinator:handle_pre_hibernate/1
ok;
handle_msg([_SPid], _From, request_depth) ->
%% This is only of value to the master
ok;
handle_msg([_SPid], _From, {ensure_monitoring, _Pid}) ->
%% This is only of value to the master
ok;
handle_msg([_SPid], _From, process_death) ->
%% We must not take any notice of the master death here since it
%% comes without ordering guarantees - there could still be
%% messages from the master we have yet to receive. When we get
%% members_changed, then there will be no more messages.
ok;
handle_msg([CPid], _From, {delete_and_terminate, _Reason} = Msg) ->
ok = gen_server2:cast(CPid, {gm, Msg}),
{stop, {shutdown, ring_shutdown}};
handle_msg([SPid], _From, {sync_start, Ref, Syncer, SPids}) ->
case lists:member(SPid, SPids) of
true -> gen_server2:cast(SPid, {sync_start, Ref, Syncer});
false -> ok
end;
handle_msg([SPid], _From, Msg) ->
ok = gen_server2:cast(SPid, {gm, Msg}).
handle_terminate([_SPid], _Reason) ->
ok.
%% ---------------------------------------------------------------------------
%% Others
%% ---------------------------------------------------------------------------
infos(Items, State) -> [{Item, i(Item, State)} || Item <- Items].
i(pid, _State) ->
self();
i(name, #state{q = Q}) when ?is_amqqueue(Q) ->
amqqueue:get_name(Q);
i(master_pid, #state{q = Q}) when ?is_amqqueue(Q) ->
amqqueue:get_pid(Q);
i(is_synchronised, #state{depth_delta = DD}) ->
DD =:= 0;
i(Item, _State) ->
throw({bad_argument, Item}).
bq_init(BQ, Q, Recover) ->
Self = self(),
BQ:init(Q, Recover,
fun (Mod, Fun) ->
rabbit_amqqueue:run_backing_queue(Self, Mod, Fun)
end).
run_backing_queue(rabbit_mirror_queue_master, Fun, State) ->
%% Yes, this might look a little crazy, but see comments in
%% confirm_sender_death/1
Fun(?MODULE, State);
run_backing_queue(Mod, Fun, State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
State #state { backing_queue_state = BQ:invoke(Mod, Fun, BQS) }.
%% This feature was used by `rabbit_amqqueue_process` and
` rabbit_mirror_queue_slave ` up - to and including RabbitMQ 3.7.x . It is
unused in 3.8.x and thus deprecated . We keep it to support in - place
%% upgrades to 3.8.x (i.e. mixed-version clusters), but it is a no-op
%% starting with that version.
send_mandatory(#delivery{mandatory = false}) ->
ok;
send_mandatory(#delivery{mandatory = true,
sender = SenderPid,
msg_seq_no = MsgSeqNo}) ->
gen_server2:cast(SenderPid, {mandatory_received, MsgSeqNo}).
send_or_record_confirm(_, #delivery{ confirm = false }, MS, _State) ->
MS;
send_or_record_confirm(published, #delivery { sender = ChPid,
confirm = true,
msg_seq_no = MsgSeqNo,
message = #basic_message {
id = MsgId,
is_persistent = true } },
MS, #state{q = Q}) when ?amqqueue_is_durable(Q) ->
maps:put(MsgId, {published, ChPid, MsgSeqNo} , MS);
send_or_record_confirm(_Status, #delivery { sender = ChPid,
confirm = true,
msg_seq_no = MsgSeqNo },
MS, _State) ->
ok = rabbit_misc:confirm_to_sender(ChPid, [MsgSeqNo]),
MS.
confirm_messages(MsgIds, State = #state { msg_id_status = MS }) ->
{CMs, MS1} =
lists:foldl(
fun (MsgId, {CMsN, MSN} = Acc) ->
%% We will never see 'discarded' here
case maps:find(MsgId, MSN) of
error ->
%% If it needed confirming, it'll have
%% already been done.
Acc;
{ok, published} ->
%% Still not seen it from the channel, just
%% record that it's been confirmed.
{CMsN, maps:put(MsgId, confirmed, MSN)};
{ok, {published, ChPid, MsgSeqNo}} ->
Seen from both GM and Channel . Can now
%% confirm.
{rabbit_misc:gb_trees_cons(ChPid, MsgSeqNo, CMsN),
maps:remove(MsgId, MSN)};
{ok, confirmed} ->
%% It's already been confirmed. This is
%% probably it's been both sync'd to disk
%% and then delivered and ack'd before we've
%% seen the publish from the
%% channel. Nothing to do here.
Acc
end
end, {gb_trees:empty(), MS}, MsgIds),
rabbit_misc:gb_trees_foreach(fun rabbit_misc:confirm_to_sender/2, CMs),
State #state { msg_id_status = MS1 }.
handle_process_result({ok, State}) -> noreply(State);
handle_process_result({stop, State}) -> {stop, normal, State}.
-spec promote_me({pid(), term()}, #state{}) -> no_return().
promote_me(From, #state { q = Q0,
gm = GM,
backing_queue = BQ,
backing_queue_state = BQS,
rate_timer_ref = RateTRef,
sender_queues = SQ,
msg_id_ack = MA,
msg_id_status = MS,
known_senders = KS}) when ?is_amqqueue(Q0) ->
QName = amqqueue:get_name(Q0),
rabbit_mirror_queue_misc:log_info(QName, "Promoting mirror ~s to master~n",
[rabbit_misc:pid_to_string(self())]),
Q1 = amqqueue:set_pid(Q0, self()),
DeathFun = rabbit_mirror_queue_master:sender_death_fun(),
DepthFun = rabbit_mirror_queue_master:depth_fun(),
{ok, CPid} = rabbit_mirror_queue_coordinator:start_link(Q1, GM, DeathFun, DepthFun),
true = unlink(GM),
gen_server2:reply(From, {promote, CPid}),
%% Everything that we're monitoring, we need to ensure our new
%% coordinator is monitoring.
MPids = pmon:monitored(KS),
ok = rabbit_mirror_queue_coordinator:ensure_monitoring(CPid, MPids),
%% We find all the messages that we've received from channels but
not from gm , and pass them to the
%% queue_process:init_with_backing_queue_state to be enqueued.
%%
%% We also have to requeue messages which are pending acks: the
%% consumers from the master queue have been lost and so these
%% messages need requeuing. They might also be pending
%% confirmation, and indeed they might also be pending arrival of
%% the publication from the channel itself, if we received both
the publication and the fetch via gm first ! does n't
%% affect confirmations: if the message was previously pending a
%% confirmation then it still will be, under the same msg_id. So
%% as a master, we need to be prepared to filter out the
%% publication of said messages from the channel (is_duplicate
( thus such requeued messages must remain in the msg_id_status
( MS ) which becomes seen_status ( SS ) in the master ) ) .
%%
%% Then there are messages we already have in the queue, which are
%% not currently pending acknowledgement:
1 . Messages we 've only received via gm :
%% Filter out subsequent publication from channel through
%% validate_message. Might have to issue confirms then or
%% later, thus queue_process state will have to know that
%% there's a pending confirm.
2 . Messages received via both gm and channel :
%% Queue will have to deal with issuing confirms if necessary.
%%
MS contains the following three entry types :
%%
%% a) published:
published via gm only ; pending arrival of publication from
%% channel, maybe pending confirm.
%%
b ) { published , ChPid , } :
published via gm and channel ; pending confirm .
%%
%% c) confirmed:
published via gm only , and confirmed ; pending publication
%% from channel.
%%
%% d) discarded:
seen via gm only as discarded . Pending publication from
%% channel
%%
%% The forms a, c and d only, need to go to the master state
seen_status ( SS ) .
%%
%% The form b only, needs to go through to the queue_process
state to form the msg_id_to_channel mapping ( MTC ) .
%%
%% No messages that are enqueued from SQ at this point will have
entries in MS .
%%
Messages that are extracted from MA may have entries in MS , and
%% those messages are then requeued. However, as discussed above,
this does not affect MS , nor which bits go through to SS in
Master , or MTC in queue_process .
St = [published, confirmed, discarded],
SS = maps:filter(fun (_MsgId, Status) -> lists:member(Status, St) end, MS),
AckTags = [AckTag || {_MsgId, AckTag} <- maps:to_list(MA)],
MasterState = rabbit_mirror_queue_master:promote_backing_queue_state(
QName, CPid, BQ, BQS, GM, AckTags, SS, MPids),
MTC = maps:fold(fun (MsgId, {published, ChPid, MsgSeqNo}, MTC0) ->
maps:put(MsgId, {ChPid, MsgSeqNo}, MTC0);
(_Msgid, _Status, MTC0) ->
MTC0
end, #{}, MS),
Deliveries = [promote_delivery(Delivery) ||
{_ChPid, {PubQ, _PendCh, _ChState}} <- maps:to_list(SQ),
Delivery <- queue:to_list(PubQ)],
AwaitGmDown = [ChPid || {ChPid, {_, _, down_from_ch}} <- maps:to_list(SQ)],
KS1 = lists:foldl(fun (ChPid0, KS0) ->
pmon:demonitor(ChPid0, KS0)
end, KS, AwaitGmDown),
rabbit_misc:store_proc_name(rabbit_amqqueue_process, QName),
rabbit_amqqueue_process:init_with_backing_queue_state(
Q1, rabbit_mirror_queue_master, MasterState, RateTRef, Deliveries, KS1,
MTC).
%% We reset mandatory to false here because we will have sent the
%% mandatory_received already as soon as we got the message. We also
%% need to send an ack for these messages since the channel is waiting
for one for the via - GM case and we will not now receive one .
promote_delivery(Delivery = #delivery{sender = Sender, flow = Flow}) ->
maybe_flow_ack(Sender, Flow),
Delivery#delivery{mandatory = false}.
noreply(State) ->
{NewState, Timeout} = next_state(State),
{noreply, ensure_rate_timer(NewState), Timeout}.
reply(Reply, State) ->
{NewState, Timeout} = next_state(State),
{reply, Reply, ensure_rate_timer(NewState), Timeout}.
next_state(State = #state{backing_queue = BQ, backing_queue_state = BQS}) ->
{MsgIds, BQS1} = BQ:drain_confirmed(BQS),
State1 = confirm_messages(MsgIds,
State #state { backing_queue_state = BQS1 }),
case BQ:needs_timeout(BQS1) of
false -> {stop_sync_timer(State1), hibernate };
idle -> {stop_sync_timer(State1), ?SYNC_INTERVAL};
timed -> {ensure_sync_timer(State1), 0 }
end.
backing_queue_timeout(State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
State#state{backing_queue_state = BQ:timeout(BQS)}.
ensure_sync_timer(State) ->
rabbit_misc:ensure_timer(State, #state.sync_timer_ref,
?SYNC_INTERVAL, sync_timeout).
stop_sync_timer(State) -> rabbit_misc:stop_timer(State, #state.sync_timer_ref).
ensure_rate_timer(State) ->
rabbit_misc:ensure_timer(State, #state.rate_timer_ref,
?RAM_DURATION_UPDATE_INTERVAL,
update_ram_duration).
stop_rate_timer(State) -> rabbit_misc:stop_timer(State, #state.rate_timer_ref).
ensure_monitoring(ChPid, State = #state { known_senders = KS }) ->
State #state { known_senders = pmon:monitor(ChPid, KS) }.
local_sender_death(ChPid, #state { known_senders = KS }) ->
%% The channel will be monitored iff we have received a delivery
%% from it but not heard about its death from the master. So if it
%% is monitored we need to point the death out to the master (see
%% essay).
ok = case pmon:is_monitored(ChPid, KS) of
false -> ok;
true -> confirm_sender_death(ChPid)
end.
confirm_sender_death(Pid) ->
%% We have to deal with the possibility that we'll be promoted to
%% master before this thing gets run. Consequently we set the
%% module to rabbit_mirror_queue_master so that if we do become a
%% rabbit_amqqueue_process before then, sane things will happen.
Fun =
fun (?MODULE, State = #state { known_senders = KS,
gm = GM }) ->
%% We're running still as a mirror
%%
%% See comment in local_sender_death/2; we might have
%% received a sender_death in the meanwhile so check
%% again.
ok = case pmon:is_monitored(Pid, KS) of
false -> ok;
true -> gm:broadcast(GM, {ensure_monitoring, [Pid]}),
confirm_sender_death(Pid)
end,
State;
(rabbit_mirror_queue_master, State) ->
We 've become a master . State is now opaque to
us . When we became master , if Pid was still known
%% to us then we'd have set up monitoring of it then,
%% so this is now a noop.
State
end,
Note that we do not remove our knowledge of this ChPid until we
get the sender_death from GM as well as a DOWN notification .
{ok, _TRef} = timer:apply_after(
?DEATH_TIMEOUT, rabbit_amqqueue, run_backing_queue,
[self(), rabbit_mirror_queue_master, Fun]),
ok.
forget_sender(_, running) -> false;
[ 1 ]
forget_sender(down_from_ch, down_from_ch) -> false;
forget_sender(Down1, Down2) when Down1 =/= Down2 -> true.
[ 1 ] If another mirror goes through confirm_sender_death/1 before we
do we can get two GM sender_death messages in a row for the same
%% channel - don't treat that as anything special.
%% Record and process lifetime events from channels. Forget all about a channel
only when down notifications are received from both the channel and from gm .
maybe_forget_sender(ChPid, ChState, State = #state { sender_queues = SQ,
msg_id_status = MS,
known_senders = KS }) ->
case maps:find(ChPid, SQ) of
error ->
State;
{ok, {MQ, PendCh, ChStateRecord}} ->
case forget_sender(ChState, ChStateRecord) of
true ->
credit_flow:peer_down(ChPid),
State #state { sender_queues = maps:remove(ChPid, SQ),
msg_id_status = lists:foldl(
fun maps:remove/2,
MS, sets:to_list(PendCh)),
known_senders = pmon:demonitor(ChPid, KS) };
false ->
SQ1 = maps:put(ChPid, {MQ, PendCh, ChState}, SQ),
State #state { sender_queues = SQ1 }
end
end.
maybe_enqueue_message(
Delivery = #delivery { message = #basic_message { id = MsgId },
sender = ChPid },
State = #state { sender_queues = SQ, msg_id_status = MS }) ->
send_mandatory(Delivery), %% must do this before confirms
State1 = ensure_monitoring(ChPid, State),
We will never see { published , ChPid , } here .
case maps:find(MsgId, MS) of
error ->
{MQ, PendingCh, ChState} = get_sender_queue(ChPid, SQ),
MQ1 = queue:in(Delivery, MQ),
SQ1 = maps:put(ChPid, {MQ1, PendingCh, ChState}, SQ),
State1 #state { sender_queues = SQ1 };
{ok, Status} ->
MS1 = send_or_record_confirm(
Status, Delivery, maps:remove(MsgId, MS), State1),
SQ1 = remove_from_pending_ch(MsgId, ChPid, SQ),
State1 #state { msg_id_status = MS1,
sender_queues = SQ1 }
end.
get_sender_queue(ChPid, SQ) ->
case maps:find(ChPid, SQ) of
error -> {queue:new(), sets:new(), running};
{ok, Val} -> Val
end.
remove_from_pending_ch(MsgId, ChPid, SQ) ->
case maps:find(ChPid, SQ) of
error ->
SQ;
{ok, {MQ, PendingCh, ChState}} ->
maps:put(ChPid, {MQ, sets:del_element(MsgId, PendingCh), ChState},
SQ)
end.
publish_or_discard(Status, ChPid, MsgId,
State = #state { sender_queues = SQ, msg_id_status = MS }) ->
%% We really are going to do the publish/discard right now, even
%% though we may not have seen it directly from the channel. But
%% we cannot issue confirms until the latter has happened. So we
need to keep track of the MsgId and its confirmation status in
%% the meantime.
State1 = ensure_monitoring(ChPid, State),
{MQ, PendingCh, ChState} = get_sender_queue(ChPid, SQ),
{MQ1, PendingCh1, MS1} =
case queue:out(MQ) of
{empty, _MQ2} ->
{MQ, sets:add_element(MsgId, PendingCh),
maps:put(MsgId, Status, MS)};
{{value, Delivery = #delivery {
message = #basic_message { id = MsgId } }}, MQ2} ->
{MQ2, PendingCh,
We received the msg from the channel first . Thus
%% we need to deal with confirms here.
send_or_record_confirm(Status, Delivery, MS, State1)};
{{value, #delivery {}}, _MQ2} ->
%% The instruction was sent to us before we were
%% within the slave_pids within the #amqqueue{}
%% record. We'll never receive the message directly
%% from the channel. And the channel will not be
%% expecting any confirms from us.
{MQ, PendingCh, MS}
end,
SQ1 = maps:put(ChPid, {MQ1, PendingCh1, ChState}, SQ),
State1 #state { sender_queues = SQ1, msg_id_status = MS1 }.
process_instruction({publish, ChPid, Flow, MsgProps,
Msg = #basic_message { id = MsgId }}, State) ->
maybe_flow_ack(ChPid, Flow),
State1 = #state { backing_queue = BQ, backing_queue_state = BQS } =
publish_or_discard(published, ChPid, MsgId, State),
BQS1 = BQ:publish(Msg, MsgProps, true, ChPid, Flow, BQS),
{ok, State1 #state { backing_queue_state = BQS1 }};
process_instruction({batch_publish, ChPid, Flow, Publishes}, State) ->
maybe_flow_ack(ChPid, Flow),
State1 = #state { backing_queue = BQ, backing_queue_state = BQS } =
lists:foldl(fun ({#basic_message { id = MsgId },
_MsgProps, _IsDelivered}, St) ->
publish_or_discard(published, ChPid, MsgId, St)
end, State, Publishes),
BQS1 = BQ:batch_publish(Publishes, ChPid, Flow, BQS),
{ok, State1 #state { backing_queue_state = BQS1 }};
process_instruction({publish_delivered, ChPid, Flow, MsgProps,
Msg = #basic_message { id = MsgId }}, State) ->
maybe_flow_ack(ChPid, Flow),
State1 = #state { backing_queue = BQ, backing_queue_state = BQS } =
publish_or_discard(published, ChPid, MsgId, State),
true = BQ:is_empty(BQS),
{AckTag, BQS1} = BQ:publish_delivered(Msg, MsgProps, ChPid, Flow, BQS),
{ok, maybe_store_ack(true, MsgId, AckTag,
State1 #state { backing_queue_state = BQS1 })};
process_instruction({batch_publish_delivered, ChPid, Flow, Publishes}, State) ->
maybe_flow_ack(ChPid, Flow),
{MsgIds,
State1 = #state { backing_queue = BQ, backing_queue_state = BQS }} =
lists:foldl(fun ({#basic_message { id = MsgId }, _MsgProps},
{MsgIds, St}) ->
{[MsgId | MsgIds],
publish_or_discard(published, ChPid, MsgId, St)}
end, {[], State}, Publishes),
true = BQ:is_empty(BQS),
{AckTags, BQS1} = BQ:batch_publish_delivered(Publishes, ChPid, Flow, BQS),
MsgIdsAndAcks = lists:zip(lists:reverse(MsgIds), AckTags),
State2 = lists:foldl(
fun ({MsgId, AckTag}, St) ->
maybe_store_ack(true, MsgId, AckTag, St)
end, State1 #state { backing_queue_state = BQS1 },
MsgIdsAndAcks),
{ok, State2};
process_instruction({discard, ChPid, Flow, MsgId}, State) ->
maybe_flow_ack(ChPid, Flow),
State1 = #state { backing_queue = BQ, backing_queue_state = BQS } =
publish_or_discard(discarded, ChPid, MsgId, State),
BQS1 = BQ:discard(MsgId, ChPid, Flow, BQS),
{ok, State1 #state { backing_queue_state = BQS1 }};
process_instruction({drop, Length, Dropped, AckRequired},
State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
QLen = BQ:len(BQS),
ToDrop = case QLen - Length of
N when N > 0 -> N;
_ -> 0
end,
State1 = lists:foldl(
fun (const, StateN = #state{backing_queue_state = BQSN}) ->
{{MsgId, AckTag}, BQSN1} = BQ:drop(AckRequired, BQSN),
maybe_store_ack(
AckRequired, MsgId, AckTag,
StateN #state { backing_queue_state = BQSN1 })
end, State, lists:duplicate(ToDrop, const)),
{ok, case AckRequired of
true -> State1;
false -> update_delta(ToDrop - Dropped, State1)
end};
process_instruction({ack, MsgIds},
State = #state { backing_queue = BQ,
backing_queue_state = BQS,
msg_id_ack = MA }) ->
{AckTags, MA1} = msg_ids_to_acktags(MsgIds, MA),
{MsgIds1, BQS1} = BQ:ack(AckTags, BQS),
[] = MsgIds1 -- MsgIds, %% ASSERTION
{ok, update_delta(length(MsgIds1) - length(MsgIds),
State #state { msg_id_ack = MA1,
backing_queue_state = BQS1 })};
process_instruction({requeue, MsgIds},
State = #state { backing_queue = BQ,
backing_queue_state = BQS,
msg_id_ack = MA }) ->
{AckTags, MA1} = msg_ids_to_acktags(MsgIds, MA),
{_MsgIds, BQS1} = BQ:requeue(AckTags, BQS),
{ok, State #state { msg_id_ack = MA1,
backing_queue_state = BQS1 }};
process_instruction({sender_death, ChPid},
State = #state { known_senders = KS }) ->
%% The channel will be monitored iff we have received a message
%% from it. In this case we just want to avoid doing work if we
%% never got any messages.
{ok, case pmon:is_monitored(ChPid, KS) of
false -> State;
true -> maybe_forget_sender(ChPid, down_from_gm, State)
end};
process_instruction({depth, Depth},
State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
{ok, set_delta(Depth - BQ:depth(BQS), State)};
process_instruction({delete_and_terminate, Reason},
State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
BQ:delete_and_terminate(Reason, BQS),
{stop, State #state { backing_queue_state = undefined }};
process_instruction({set_queue_mode, Mode},
State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
BQS1 = BQ:set_queue_mode(Mode, BQS),
{ok, State #state { backing_queue_state = BQS1 }}.
maybe_flow_ack(Sender, flow) -> credit_flow:ack(Sender);
maybe_flow_ack(_Sender, noflow) -> ok.
msg_ids_to_acktags(MsgIds, MA) ->
{AckTags, MA1} =
lists:foldl(
fun (MsgId, {Acc, MAN}) ->
case maps:find(MsgId, MA) of
error -> {Acc, MAN};
{ok, AckTag} -> {[AckTag | Acc], maps:remove(MsgId, MAN)}
end
end, {[], MA}, MsgIds),
{lists:reverse(AckTags), MA1}.
maybe_store_ack(false, _MsgId, _AckTag, State) ->
State;
maybe_store_ack(true, MsgId, AckTag, State = #state { msg_id_ack = MA }) ->
State #state { msg_id_ack = maps:put(MsgId, AckTag, MA) }.
set_delta(0, State = #state { depth_delta = undefined }) ->
ok = record_synchronised(State#state.q),
State #state { depth_delta = 0 };
set_delta(NewDelta, State = #state { depth_delta = undefined }) ->
true = NewDelta > 0, %% assertion
State #state { depth_delta = NewDelta };
set_delta(NewDelta, State = #state { depth_delta = Delta }) ->
update_delta(NewDelta - Delta, State).
update_delta(_DeltaChange, State = #state { depth_delta = undefined }) ->
State;
update_delta( DeltaChange, State = #state { depth_delta = 0 }) ->
0 = DeltaChange, %% assertion: we cannot become unsync'ed
State;
update_delta( DeltaChange, State = #state { depth_delta = Delta }) ->
true = DeltaChange =< 0, %% assertion: we cannot become 'less' sync'ed
set_delta(Delta + DeltaChange, State #state { depth_delta = undefined }).
update_ram_duration(BQ, BQS) ->
{RamDuration, BQS1} = BQ:ram_duration(BQS),
DesiredDuration =
rabbit_memory_monitor:report_ram_duration(self(), RamDuration),
BQ:set_ram_duration_target(DesiredDuration, BQS1).
record_synchronised(Q0) when ?is_amqqueue(Q0) ->
QName = amqqueue:get_name(Q0),
Self = self(),
F = fun () ->
case mnesia:read({rabbit_queue, QName}) of
[] ->
ok;
[Q1] when ?is_amqqueue(Q1) ->
SSPids = amqqueue:get_sync_slave_pids(Q1),
SSPids1 = [Self | SSPids],
Q2 = amqqueue:set_sync_slave_pids(Q1, SSPids1),
rabbit_mirror_queue_misc:store_updated_slaves(Q2),
{ok, Q2}
end
end,
case rabbit_misc:execute_mnesia_transaction(F) of
ok -> ok;
{ok, Q2} -> rabbit_mirror_queue_misc:maybe_drop_master_after_sync(Q2)
end.
| null | https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbit/src/rabbit_mirror_queue_slave.erl | erlang |
For general documentation of HA design, see
rabbit_mirror_queue_coordinator
messages can arrive either before or after the 'actual' message.
in which they're received.
----------------------------------------------------------------------------
milliseconds
Master depth - local depth
----------------------------------------------------------------------------
record. As a result:
never receive from publishers.
before or after the actual message. We need to be able to
above.
amqqueue_process traps exits too.
We ignore the DOWN message because we are also linked and
trapping exits, we just want to not get stuck and we will exit
later.
For crash recovery
The queue record vanished - we must have a master starting
concurrently with us. In that case we can safely decide to do
nothing here, and the master will start us in
Pending mirrors have been asked to stop by the master, but despite the node
being up these did not answer on the expected timeout. Stop local mirrors now.
Add to the end, so they are in descending order of age, see
rabbit_mirror_queue_misc:promote_slave/1
master hasn't changed
we've become master
master has changed to not us
see rabbitmq-server#914;
in which case we attempt to add mirrors on those nodes.
there is some traffic when a master dies, to
make sure all mirrors get informed of the
death. That is all process_death does, create
some traffic.
Potentially a duplicated mirror caused by a partial partition,
will stop as a new mirror could start unaware of our presence
Asynchronous, non-"mandatory", deliver mode.
We are acking messages to the channel process that sent us
the message delivery. See
rabbit_amqqueue_process:handle_ch_down for more info.
If message is rejected by the master, the publish will be nacked
even if mirrors confirm it. No need to check for length here.
During partial partitions, we might end up receiving messages expected by a master
Ignore them
Don't call noreply/1, we don't want to set timers
In the event of a short partition during sync we can detect the
master's 'death', drop out of sync, and then receive sync messages
which were still in flight. Ignore them.
do here.
See rabbit_mirror_queue_master:terminate/2
being deleted: it's just the node going down. Even though we're a
mirror, we have no idea whether or not we'll be the only copy coming
back up. Thus we must assume we will be, and preserve anything we
have on disk.
---------------------------------------------------------------------------
---------------------------------------------------------------------------
See rabbit_mirror_queue_coordinator:handle_pre_hibernate/1
This is only of value to the master
This is only of value to the master
We must not take any notice of the master death here since it
comes without ordering guarantees - there could still be
messages from the master we have yet to receive. When we get
members_changed, then there will be no more messages.
---------------------------------------------------------------------------
Others
---------------------------------------------------------------------------
Yes, this might look a little crazy, but see comments in
confirm_sender_death/1
This feature was used by `rabbit_amqqueue_process` and
upgrades to 3.8.x (i.e. mixed-version clusters), but it is a no-op
starting with that version.
We will never see 'discarded' here
If it needed confirming, it'll have
already been done.
Still not seen it from the channel, just
record that it's been confirmed.
confirm.
It's already been confirmed. This is
probably it's been both sync'd to disk
and then delivered and ack'd before we've
seen the publish from the
channel. Nothing to do here.
Everything that we're monitoring, we need to ensure our new
coordinator is monitoring.
We find all the messages that we've received from channels but
queue_process:init_with_backing_queue_state to be enqueued.
We also have to requeue messages which are pending acks: the
consumers from the master queue have been lost and so these
messages need requeuing. They might also be pending
confirmation, and indeed they might also be pending arrival of
the publication from the channel itself, if we received both
affect confirmations: if the message was previously pending a
confirmation then it still will be, under the same msg_id. So
as a master, we need to be prepared to filter out the
publication of said messages from the channel (is_duplicate
Then there are messages we already have in the queue, which are
not currently pending acknowledgement:
Filter out subsequent publication from channel through
validate_message. Might have to issue confirms then or
later, thus queue_process state will have to know that
there's a pending confirm.
Queue will have to deal with issuing confirms if necessary.
a) published:
channel, maybe pending confirm.
c) confirmed:
from channel.
d) discarded:
channel
The forms a, c and d only, need to go to the master state
The form b only, needs to go through to the queue_process
No messages that are enqueued from SQ at this point will have
those messages are then requeued. However, as discussed above,
We reset mandatory to false here because we will have sent the
mandatory_received already as soon as we got the message. We also
need to send an ack for these messages since the channel is waiting
The channel will be monitored iff we have received a delivery
from it but not heard about its death from the master. So if it
is monitored we need to point the death out to the master (see
essay).
We have to deal with the possibility that we'll be promoted to
master before this thing gets run. Consequently we set the
module to rabbit_mirror_queue_master so that if we do become a
rabbit_amqqueue_process before then, sane things will happen.
We're running still as a mirror
See comment in local_sender_death/2; we might have
received a sender_death in the meanwhile so check
again.
to us then we'd have set up monitoring of it then,
so this is now a noop.
channel - don't treat that as anything special.
Record and process lifetime events from channels. Forget all about a channel
must do this before confirms
We really are going to do the publish/discard right now, even
though we may not have seen it directly from the channel. But
we cannot issue confirms until the latter has happened. So we
the meantime.
we need to deal with confirms here.
The instruction was sent to us before we were
within the slave_pids within the #amqqueue{}
record. We'll never receive the message directly
from the channel. And the channel will not be
expecting any confirms from us.
ASSERTION
The channel will be monitored iff we have received a message
from it. In this case we just want to avoid doing work if we
never got any messages.
assertion
assertion: we cannot become unsync'ed
assertion: we cannot become 'less' sync'ed | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2010 - 2021 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_mirror_queue_slave).
We receive messages from GM and from publishers , and the gm
All instructions from the GM group must be processed in the order
-export([set_maximum_since_use/2, info/1, go/2]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
code_change/3, handle_pre_hibernate/1, prioritise_call/4,
prioritise_cast/3, prioritise_info/3, format_message_queue/2]).
-export([joined/2, members_changed/3, handle_msg/3, handle_terminate/2]).
-behaviour(gen_server2).
-behaviour(gm).
-include_lib("rabbit_common/include/rabbit.hrl").
-include("amqqueue.hrl").
-include("gm_specs.hrl").
-define(INFO_KEYS,
[pid,
name,
master_pid,
is_synchronised
]).
-define(RAM_DURATION_UPDATE_INTERVAL, 5000).
20 seconds
-record(state, { q,
gm,
backing_queue,
backing_queue_state,
sync_timer_ref,
rate_timer_ref,
: : Pid - > { Q Msg , Set MsgId , ChState }
: : MsgId - > AckTag
msg_id_status,
known_senders,
depth_delta
}).
set_maximum_since_use(QPid, Age) ->
gen_server2:cast(QPid, {set_maximum_since_use, Age}).
info(QPid) -> gen_server2:call(QPid, info, infinity).
init(Q) when ?is_amqqueue(Q) ->
QName = amqqueue:get_name(Q),
?store_proc_name(QName),
{ok, {not_started, Q}, hibernate,
{backoff, ?HIBERNATE_AFTER_MIN, ?HIBERNATE_AFTER_MIN,
?DESIRED_HIBERNATE}, ?MODULE}.
go(SPid, sync) -> gen_server2:call(SPid, go, infinity);
go(SPid, async) -> gen_server2:cast(SPid, go).
handle_go(Q0) when ?is_amqqueue(Q0) ->
QName = amqqueue:get_name(Q0),
We join the GM group before we add ourselves to the amqqueue
1 . We can receive msgs from GM that correspond to messages we will
2 . When we receive a message from publishers , we must receive a
message from the GM group for it .
3 . However , that instruction from the GM group can arrive either
distinguish between GM instructions arriving early , and case ( 1 )
{ok, GM} = gm:start_link(QName, ?MODULE, [self()],
fun rabbit_misc:execute_mnesia_transaction/1),
MRef = erlang:monitor(process, GM),
receive
{joined, GM} -> erlang:demonitor(MRef, [flush]),
ok;
{'DOWN', MRef, _, _, _} -> ok
end,
Self = self(),
Node = node(),
case rabbit_misc:execute_mnesia_transaction(
fun() -> init_it(Self, GM, Node, QName) end) of
{new, QPid, GMPids} ->
ok = file_handle_cache:register_callback(
rabbit_amqqueue, set_maximum_since_use, [Self]),
ok = rabbit_memory_monitor:register(
Self, {rabbit_amqqueue, set_ram_duration_target, [Self]}),
{ok, BQ} = application:get_env(backing_queue_module),
Q1 = amqqueue:set_pid(Q0, QPid),
BQS = bq_init(BQ, Q1, new),
State = #state { q = Q1,
gm = GM,
backing_queue = BQ,
backing_queue_state = BQS,
rate_timer_ref = undefined,
sync_timer_ref = undefined,
sender_queues = #{},
msg_id_ack = #{},
msg_id_status = #{},
known_senders = pmon:new(delegate),
depth_delta = undefined
},
ok = gm:broadcast(GM, request_depth),
ok = gm:validate_members(GM, [GM | [G || {G, _} <- GMPids]]),
rabbit_mirror_queue_misc:maybe_auto_sync(Q1),
{ok, State};
{stale, StalePid} ->
rabbit_mirror_queue_misc:log_warning(
QName, "Detected stale HA master: ~p~n", [StalePid]),
gm:leave(GM),
{error, {stale_master_pid, StalePid}};
duplicate_live_master ->
gm:leave(GM),
{error, {duplicate_live_master, Node}};
existing ->
gm:leave(GM),
{error, normal};
master_in_recovery ->
gm:leave(GM),
master : init_with_existing_bq/3
{error, normal}
end.
init_it(Self, GM, Node, QName) ->
case mnesia:read({rabbit_queue, QName}) of
[Q] when ?is_amqqueue(Q) ->
QPid = amqqueue:get_pid(Q),
SPids = amqqueue:get_slave_pids(Q),
GMPids = amqqueue:get_gm_pids(Q),
PSPids = amqqueue:get_slave_pids_pending_shutdown(Q),
case [Pid || Pid <- [QPid | SPids], node(Pid) =:= Node] of
[] -> stop_pending_slaves(QName, PSPids),
add_slave(Q, Self, GM),
{new, QPid, GMPids};
[QPid] -> case rabbit_mnesia:is_process_alive(QPid) of
true -> duplicate_live_master;
false -> {stale, QPid}
end;
[SPid] -> case rabbit_mnesia:is_process_alive(SPid) of
true -> existing;
false -> GMPids1 = [T || T = {_, S} <- GMPids, S =/= SPid],
SPids1 = SPids -- [SPid],
Q1 = amqqueue:set_slave_pids(Q, SPids1),
Q2 = amqqueue:set_gm_pids(Q1, GMPids1),
add_slave(Q2, Self, GM),
{new, QPid, GMPids1}
end
end;
[] ->
master_in_recovery
end.
stop_pending_slaves(QName, Pids) ->
[begin
rabbit_mirror_queue_misc:log_warning(
QName, "Detected a non-responsive classic queue mirror, stopping it: ~p~n", [Pid]),
case erlang:process_info(Pid, dictionary) of
undefined -> ok;
{dictionary, Dict} ->
Vhost = QName#resource.virtual_host,
{ok, AmqQSup} = rabbit_amqqueue_sup_sup:find_for_vhost(Vhost),
case proplists:get_value('$ancestors', Dict) of
[Sup, AmqQSup | _] ->
exit(Sup, kill),
exit(Pid, kill);
_ ->
ok
end
end
end || Pid <- Pids, node(Pid) =:= node(),
true =:= erlang:is_process_alive(Pid)].
add_slave(Q0, New, GM) when ?is_amqqueue(Q0) ->
SPids = amqqueue:get_slave_pids(Q0),
GMPids = amqqueue:get_gm_pids(Q0),
SPids1 = SPids ++ [New],
GMPids1 = [{GM, New} | GMPids],
Q1 = amqqueue:set_slave_pids(Q0, SPids1),
Q2 = amqqueue:set_gm_pids(Q1, GMPids1),
rabbit_mirror_queue_misc:store_updated_slaves(Q2).
handle_call(go, _From, {not_started, Q} = NotStarted) ->
case handle_go(Q) of
{ok, State} -> {reply, ok, State};
{error, Error} -> {stop, Error, NotStarted}
end;
handle_call({gm_deaths, DeadGMPids}, From,
State = #state{ gm = GM, q = Q,
backing_queue = BQ,
backing_queue_state = BQS}) when ?is_amqqueue(Q) ->
QName = amqqueue:get_name(Q),
MPid = amqqueue:get_pid(Q),
Self = self(),
case rabbit_mirror_queue_misc:remove_from_queue(QName, Self, DeadGMPids) of
{error, not_found} ->
gen_server2:reply(From, ok),
{stop, normal, State};
{error, {not_synced, _SPids}} ->
BQ:delete_and_terminate({error, not_synced}, BQS),
{stop, normal, State#state{backing_queue_state = undefined}};
{ok, Pid, DeadPids, ExtraNodes} ->
rabbit_mirror_queue_misc:report_deaths(Self, false, QName,
DeadPids),
case Pid of
MPid ->
gen_server2:reply(From, ok),
rabbit_mirror_queue_misc:add_mirrors(
QName, ExtraNodes, async),
noreply(State);
Self ->
QueueState = promote_me(From, State),
rabbit_mirror_queue_misc:add_mirrors(
QName, ExtraNodes, async),
{become, rabbit_amqqueue_process, QueueState, hibernate};
_ ->
gen_server2:reply(From, ok),
It 's not always guaranteed that we wo n't have ExtraNodes .
If gm alters , master can change to not us with extra nodes ,
case ExtraNodes of
[] -> void;
_ -> rabbit_mirror_queue_misc:add_mirrors(
QName, ExtraNodes, async)
end,
Since GM is by nature lazy we need to make sure
ok = gm:broadcast(GM, process_death),
Q1 = amqqueue:set_pid(Q, Pid),
State1 = State#state{q = Q1},
noreply(State1)
end
end;
handle_call(info, _From, State) ->
reply(infos(?INFO_KEYS, State), State).
handle_cast(go, {not_started, Q} = NotStarted) ->
case handle_go(Q) of
{ok, State} -> {noreply, State};
{error, Error} -> {stop, Error, NotStarted}
end;
handle_cast({run_backing_queue, Mod, Fun}, State) ->
noreply(run_backing_queue(Mod, Fun, State));
handle_cast({gm, Instruction}, State = #state{q = Q0}) when ?is_amqqueue(Q0) ->
QName = amqqueue:get_name(Q0),
case rabbit_amqqueue:lookup(QName) of
{ok, Q1} when ?is_amqqueue(Q1) ->
SPids = amqqueue:get_slave_pids(Q1),
case lists:member(self(), SPids) of
true ->
handle_process_result(process_instruction(Instruction, State));
false ->
{stop, shutdown, State}
end;
{error, not_found} ->
Would not expect this to happen after fixing # 953
{stop, shutdown, State}
end;
handle_cast({deliver, Delivery = #delivery{sender = Sender, flow = Flow}, true},
State) ->
maybe_flow_ack(Sender, Flow),
noreply(maybe_enqueue_message(Delivery, State));
handle_cast({sync_start, Ref, Syncer},
State = #state { depth_delta = DD,
backing_queue = BQ,
backing_queue_state = BQS }) ->
State1 = #state{rate_timer_ref = TRef} = ensure_rate_timer(State),
S = fun({MA, TRefN, BQSN}) ->
State1#state{depth_delta = undefined,
msg_id_ack = maps:from_list(MA),
rate_timer_ref = TRefN,
backing_queue_state = BQSN}
end,
case rabbit_mirror_queue_sync:slave(
DD, Ref, TRef, Syncer, BQ, BQS,
fun (BQN, BQSN) ->
BQSN1 = update_ram_duration(BQN, BQSN),
TRefN = rabbit_misc:send_after(?RAM_DURATION_UPDATE_INTERVAL,
self(), update_ram_duration),
{TRefN, BQSN1}
end) of
denied -> noreply(State1);
{ok, Res} -> noreply(set_delta(0, S(Res)));
{failed, Res} -> noreply(S(Res));
{stop, Reason, Res} -> {stop, Reason, S(Res)}
end;
handle_cast({set_maximum_since_use, Age}, State) ->
ok = file_handle_cache:set_maximum_since_use(Age),
noreply(State);
handle_cast({set_ram_duration_target, Duration},
State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
BQS1 = BQ:set_ram_duration_target(Duration, BQS),
noreply(State #state { backing_queue_state = BQS1 });
handle_cast(policy_changed, State) ->
noreply(State).
handle_info(update_ram_duration, State = #state{backing_queue = BQ,
backing_queue_state = BQS}) ->
BQS1 = update_ram_duration(BQ, BQS),
{State1, Timeout} = next_state(State #state {
rate_timer_ref = undefined,
backing_queue_state = BQS1 }),
{noreply, State1, Timeout};
handle_info(sync_timeout, State) ->
noreply(backing_queue_timeout(
State #state { sync_timer_ref = undefined }));
handle_info(timeout, State) ->
noreply(backing_queue_timeout(State));
handle_info({'DOWN', _MonitorRef, process, ChPid, _Reason}, State) ->
local_sender_death(ChPid, State),
noreply(maybe_forget_sender(ChPid, down_from_ch, State));
handle_info({'EXIT', _Pid, Reason}, State) ->
{stop, Reason, State};
handle_info({bump_credit, Msg}, State) ->
credit_flow:handle_bump_msg(Msg),
noreply(State);
handle_info(bump_reduce_memory_use, State = #state{backing_queue = BQ,
backing_queue_state = BQS}) ->
BQS1 = BQ:handle_info(bump_reduce_memory_use, BQS),
BQS2 = BQ:resume(BQS1),
noreply(State#state{
backing_queue_state = BQS2
});
handle_info({sync_msg, _Ref, _Msg, _Props, _Unacked}, State) ->
noreply(State);
handle_info({sync_complete, _Ref}, State) ->
noreply(State);
handle_info(Msg, State) ->
{stop, {unexpected_info, Msg}, State}.
terminate(_Reason, {not_started, _Q}) ->
ok;
terminate(_Reason, #state { backing_queue_state = undefined }) ->
We 've received a delete_and_terminate from gm , thus nothing to
ok;
terminate({shutdown, dropped} = R, State = #state{backing_queue = BQ,
backing_queue_state = BQS}) ->
terminate_common(State),
BQ:delete_and_terminate(R, BQS);
terminate(shutdown, State) ->
terminate_shutdown(shutdown, State);
terminate({shutdown, _} = R, State) ->
terminate_shutdown(R, State);
terminate(Reason, State = #state{backing_queue = BQ,
backing_queue_state = BQS}) ->
terminate_common(State),
BQ:delete_and_terminate(Reason, BQS).
If the is shutdown , or { shutdown , _ } , it is not the queue
terminate_shutdown(Reason, State = #state{backing_queue = BQ,
backing_queue_state = BQS}) ->
terminate_common(State),
BQ:terminate(Reason, BQS).
terminate_common(State) ->
ok = rabbit_memory_monitor:deregister(self()),
stop_rate_timer(stop_sync_timer(State)).
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
handle_pre_hibernate({not_started, _Q} = State) ->
{hibernate, State};
handle_pre_hibernate(State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
{RamDuration, BQS1} = BQ:ram_duration(BQS),
DesiredDuration =
rabbit_memory_monitor:report_ram_duration(self(), RamDuration),
BQS2 = BQ:set_ram_duration_target(DesiredDuration, BQS1),
BQS3 = BQ:handle_pre_hibernate(BQS2),
{hibernate, stop_rate_timer(State #state { backing_queue_state = BQS3 })}.
prioritise_call(Msg, _From, _Len, _State) ->
case Msg of
info -> 9;
{gm_deaths, _Dead} -> 5;
_ -> 0
end.
prioritise_cast(Msg, _Len, _State) ->
case Msg of
{set_ram_duration_target, _Duration} -> 8;
{set_maximum_since_use, _Age} -> 8;
{run_backing_queue, _Mod, _Fun} -> 6;
{gm, _Msg} -> 5;
_ -> 0
end.
prioritise_info(Msg, _Len, _State) ->
case Msg of
update_ram_duration -> 8;
sync_timeout -> 6;
_ -> 0
end.
format_message_queue(Opt, MQ) -> rabbit_misc:format_message_queue(Opt, MQ).
GM
joined([SPid], _Members) -> SPid ! {joined, self()}, ok.
members_changed([_SPid], _Births, []) ->
ok;
members_changed([ SPid], _Births, Deaths) ->
case rabbit_misc:with_exit_handler(
rabbit_misc:const(ok),
fun() ->
gen_server2:call(SPid, {gm_deaths, Deaths}, infinity)
end) of
ok -> ok;
{promote, CPid} -> {become, rabbit_mirror_queue_coordinator, [CPid]}
end.
handle_msg([_SPid], _From, hibernate_heartbeat) ->
ok;
handle_msg([_SPid], _From, request_depth) ->
ok;
handle_msg([_SPid], _From, {ensure_monitoring, _Pid}) ->
ok;
handle_msg([_SPid], _From, process_death) ->
ok;
handle_msg([CPid], _From, {delete_and_terminate, _Reason} = Msg) ->
ok = gen_server2:cast(CPid, {gm, Msg}),
{stop, {shutdown, ring_shutdown}};
handle_msg([SPid], _From, {sync_start, Ref, Syncer, SPids}) ->
case lists:member(SPid, SPids) of
true -> gen_server2:cast(SPid, {sync_start, Ref, Syncer});
false -> ok
end;
handle_msg([SPid], _From, Msg) ->
ok = gen_server2:cast(SPid, {gm, Msg}).
handle_terminate([_SPid], _Reason) ->
ok.
infos(Items, State) -> [{Item, i(Item, State)} || Item <- Items].
i(pid, _State) ->
self();
i(name, #state{q = Q}) when ?is_amqqueue(Q) ->
amqqueue:get_name(Q);
i(master_pid, #state{q = Q}) when ?is_amqqueue(Q) ->
amqqueue:get_pid(Q);
i(is_synchronised, #state{depth_delta = DD}) ->
DD =:= 0;
i(Item, _State) ->
throw({bad_argument, Item}).
bq_init(BQ, Q, Recover) ->
Self = self(),
BQ:init(Q, Recover,
fun (Mod, Fun) ->
rabbit_amqqueue:run_backing_queue(Self, Mod, Fun)
end).
run_backing_queue(rabbit_mirror_queue_master, Fun, State) ->
Fun(?MODULE, State);
run_backing_queue(Mod, Fun, State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
State #state { backing_queue_state = BQ:invoke(Mod, Fun, BQS) }.
` rabbit_mirror_queue_slave ` up - to and including RabbitMQ 3.7.x . It is
unused in 3.8.x and thus deprecated . We keep it to support in - place
send_mandatory(#delivery{mandatory = false}) ->
ok;
send_mandatory(#delivery{mandatory = true,
sender = SenderPid,
msg_seq_no = MsgSeqNo}) ->
gen_server2:cast(SenderPid, {mandatory_received, MsgSeqNo}).
send_or_record_confirm(_, #delivery{ confirm = false }, MS, _State) ->
MS;
send_or_record_confirm(published, #delivery { sender = ChPid,
confirm = true,
msg_seq_no = MsgSeqNo,
message = #basic_message {
id = MsgId,
is_persistent = true } },
MS, #state{q = Q}) when ?amqqueue_is_durable(Q) ->
maps:put(MsgId, {published, ChPid, MsgSeqNo} , MS);
send_or_record_confirm(_Status, #delivery { sender = ChPid,
confirm = true,
msg_seq_no = MsgSeqNo },
MS, _State) ->
ok = rabbit_misc:confirm_to_sender(ChPid, [MsgSeqNo]),
MS.
confirm_messages(MsgIds, State = #state { msg_id_status = MS }) ->
{CMs, MS1} =
lists:foldl(
fun (MsgId, {CMsN, MSN} = Acc) ->
case maps:find(MsgId, MSN) of
error ->
Acc;
{ok, published} ->
{CMsN, maps:put(MsgId, confirmed, MSN)};
{ok, {published, ChPid, MsgSeqNo}} ->
Seen from both GM and Channel . Can now
{rabbit_misc:gb_trees_cons(ChPid, MsgSeqNo, CMsN),
maps:remove(MsgId, MSN)};
{ok, confirmed} ->
Acc
end
end, {gb_trees:empty(), MS}, MsgIds),
rabbit_misc:gb_trees_foreach(fun rabbit_misc:confirm_to_sender/2, CMs),
State #state { msg_id_status = MS1 }.
handle_process_result({ok, State}) -> noreply(State);
handle_process_result({stop, State}) -> {stop, normal, State}.
-spec promote_me({pid(), term()}, #state{}) -> no_return().
promote_me(From, #state { q = Q0,
gm = GM,
backing_queue = BQ,
backing_queue_state = BQS,
rate_timer_ref = RateTRef,
sender_queues = SQ,
msg_id_ack = MA,
msg_id_status = MS,
known_senders = KS}) when ?is_amqqueue(Q0) ->
QName = amqqueue:get_name(Q0),
rabbit_mirror_queue_misc:log_info(QName, "Promoting mirror ~s to master~n",
[rabbit_misc:pid_to_string(self())]),
Q1 = amqqueue:set_pid(Q0, self()),
DeathFun = rabbit_mirror_queue_master:sender_death_fun(),
DepthFun = rabbit_mirror_queue_master:depth_fun(),
{ok, CPid} = rabbit_mirror_queue_coordinator:start_link(Q1, GM, DeathFun, DepthFun),
true = unlink(GM),
gen_server2:reply(From, {promote, CPid}),
MPids = pmon:monitored(KS),
ok = rabbit_mirror_queue_coordinator:ensure_monitoring(CPid, MPids),
not from gm , and pass them to the
the publication and the fetch via gm first ! does n't
( thus such requeued messages must remain in the msg_id_status
( MS ) which becomes seen_status ( SS ) in the master ) ) .
1 . Messages we 've only received via gm :
2 . Messages received via both gm and channel :
MS contains the following three entry types :
published via gm only ; pending arrival of publication from
b ) { published , ChPid , } :
published via gm and channel ; pending confirm .
published via gm only , and confirmed ; pending publication
seen via gm only as discarded . Pending publication from
seen_status ( SS ) .
state to form the msg_id_to_channel mapping ( MTC ) .
entries in MS .
Messages that are extracted from MA may have entries in MS , and
this does not affect MS , nor which bits go through to SS in
Master , or MTC in queue_process .
St = [published, confirmed, discarded],
SS = maps:filter(fun (_MsgId, Status) -> lists:member(Status, St) end, MS),
AckTags = [AckTag || {_MsgId, AckTag} <- maps:to_list(MA)],
MasterState = rabbit_mirror_queue_master:promote_backing_queue_state(
QName, CPid, BQ, BQS, GM, AckTags, SS, MPids),
MTC = maps:fold(fun (MsgId, {published, ChPid, MsgSeqNo}, MTC0) ->
maps:put(MsgId, {ChPid, MsgSeqNo}, MTC0);
(_Msgid, _Status, MTC0) ->
MTC0
end, #{}, MS),
Deliveries = [promote_delivery(Delivery) ||
{_ChPid, {PubQ, _PendCh, _ChState}} <- maps:to_list(SQ),
Delivery <- queue:to_list(PubQ)],
AwaitGmDown = [ChPid || {ChPid, {_, _, down_from_ch}} <- maps:to_list(SQ)],
KS1 = lists:foldl(fun (ChPid0, KS0) ->
pmon:demonitor(ChPid0, KS0)
end, KS, AwaitGmDown),
rabbit_misc:store_proc_name(rabbit_amqqueue_process, QName),
rabbit_amqqueue_process:init_with_backing_queue_state(
Q1, rabbit_mirror_queue_master, MasterState, RateTRef, Deliveries, KS1,
MTC).
for one for the via - GM case and we will not now receive one .
promote_delivery(Delivery = #delivery{sender = Sender, flow = Flow}) ->
maybe_flow_ack(Sender, Flow),
Delivery#delivery{mandatory = false}.
noreply(State) ->
{NewState, Timeout} = next_state(State),
{noreply, ensure_rate_timer(NewState), Timeout}.
reply(Reply, State) ->
{NewState, Timeout} = next_state(State),
{reply, Reply, ensure_rate_timer(NewState), Timeout}.
next_state(State = #state{backing_queue = BQ, backing_queue_state = BQS}) ->
{MsgIds, BQS1} = BQ:drain_confirmed(BQS),
State1 = confirm_messages(MsgIds,
State #state { backing_queue_state = BQS1 }),
case BQ:needs_timeout(BQS1) of
false -> {stop_sync_timer(State1), hibernate };
idle -> {stop_sync_timer(State1), ?SYNC_INTERVAL};
timed -> {ensure_sync_timer(State1), 0 }
end.
backing_queue_timeout(State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
State#state{backing_queue_state = BQ:timeout(BQS)}.
ensure_sync_timer(State) ->
rabbit_misc:ensure_timer(State, #state.sync_timer_ref,
?SYNC_INTERVAL, sync_timeout).
stop_sync_timer(State) -> rabbit_misc:stop_timer(State, #state.sync_timer_ref).
ensure_rate_timer(State) ->
rabbit_misc:ensure_timer(State, #state.rate_timer_ref,
?RAM_DURATION_UPDATE_INTERVAL,
update_ram_duration).
stop_rate_timer(State) -> rabbit_misc:stop_timer(State, #state.rate_timer_ref).
ensure_monitoring(ChPid, State = #state { known_senders = KS }) ->
State #state { known_senders = pmon:monitor(ChPid, KS) }.
local_sender_death(ChPid, #state { known_senders = KS }) ->
ok = case pmon:is_monitored(ChPid, KS) of
false -> ok;
true -> confirm_sender_death(ChPid)
end.
confirm_sender_death(Pid) ->
Fun =
fun (?MODULE, State = #state { known_senders = KS,
gm = GM }) ->
ok = case pmon:is_monitored(Pid, KS) of
false -> ok;
true -> gm:broadcast(GM, {ensure_monitoring, [Pid]}),
confirm_sender_death(Pid)
end,
State;
(rabbit_mirror_queue_master, State) ->
We 've become a master . State is now opaque to
us . When we became master , if Pid was still known
State
end,
Note that we do not remove our knowledge of this ChPid until we
get the sender_death from GM as well as a DOWN notification .
{ok, _TRef} = timer:apply_after(
?DEATH_TIMEOUT, rabbit_amqqueue, run_backing_queue,
[self(), rabbit_mirror_queue_master, Fun]),
ok.
forget_sender(_, running) -> false;
[ 1 ]
forget_sender(down_from_ch, down_from_ch) -> false;
forget_sender(Down1, Down2) when Down1 =/= Down2 -> true.
[ 1 ] If another mirror goes through confirm_sender_death/1 before we
do we can get two GM sender_death messages in a row for the same
only when down notifications are received from both the channel and from gm .
maybe_forget_sender(ChPid, ChState, State = #state { sender_queues = SQ,
msg_id_status = MS,
known_senders = KS }) ->
case maps:find(ChPid, SQ) of
error ->
State;
{ok, {MQ, PendCh, ChStateRecord}} ->
case forget_sender(ChState, ChStateRecord) of
true ->
credit_flow:peer_down(ChPid),
State #state { sender_queues = maps:remove(ChPid, SQ),
msg_id_status = lists:foldl(
fun maps:remove/2,
MS, sets:to_list(PendCh)),
known_senders = pmon:demonitor(ChPid, KS) };
false ->
SQ1 = maps:put(ChPid, {MQ, PendCh, ChState}, SQ),
State #state { sender_queues = SQ1 }
end
end.
maybe_enqueue_message(
Delivery = #delivery { message = #basic_message { id = MsgId },
sender = ChPid },
State = #state { sender_queues = SQ, msg_id_status = MS }) ->
State1 = ensure_monitoring(ChPid, State),
We will never see { published , ChPid , } here .
case maps:find(MsgId, MS) of
error ->
{MQ, PendingCh, ChState} = get_sender_queue(ChPid, SQ),
MQ1 = queue:in(Delivery, MQ),
SQ1 = maps:put(ChPid, {MQ1, PendingCh, ChState}, SQ),
State1 #state { sender_queues = SQ1 };
{ok, Status} ->
MS1 = send_or_record_confirm(
Status, Delivery, maps:remove(MsgId, MS), State1),
SQ1 = remove_from_pending_ch(MsgId, ChPid, SQ),
State1 #state { msg_id_status = MS1,
sender_queues = SQ1 }
end.
get_sender_queue(ChPid, SQ) ->
case maps:find(ChPid, SQ) of
error -> {queue:new(), sets:new(), running};
{ok, Val} -> Val
end.
remove_from_pending_ch(MsgId, ChPid, SQ) ->
case maps:find(ChPid, SQ) of
error ->
SQ;
{ok, {MQ, PendingCh, ChState}} ->
maps:put(ChPid, {MQ, sets:del_element(MsgId, PendingCh), ChState},
SQ)
end.
publish_or_discard(Status, ChPid, MsgId,
State = #state { sender_queues = SQ, msg_id_status = MS }) ->
need to keep track of the MsgId and its confirmation status in
State1 = ensure_monitoring(ChPid, State),
{MQ, PendingCh, ChState} = get_sender_queue(ChPid, SQ),
{MQ1, PendingCh1, MS1} =
case queue:out(MQ) of
{empty, _MQ2} ->
{MQ, sets:add_element(MsgId, PendingCh),
maps:put(MsgId, Status, MS)};
{{value, Delivery = #delivery {
message = #basic_message { id = MsgId } }}, MQ2} ->
{MQ2, PendingCh,
We received the msg from the channel first . Thus
send_or_record_confirm(Status, Delivery, MS, State1)};
{{value, #delivery {}}, _MQ2} ->
{MQ, PendingCh, MS}
end,
SQ1 = maps:put(ChPid, {MQ1, PendingCh1, ChState}, SQ),
State1 #state { sender_queues = SQ1, msg_id_status = MS1 }.
process_instruction({publish, ChPid, Flow, MsgProps,
Msg = #basic_message { id = MsgId }}, State) ->
maybe_flow_ack(ChPid, Flow),
State1 = #state { backing_queue = BQ, backing_queue_state = BQS } =
publish_or_discard(published, ChPid, MsgId, State),
BQS1 = BQ:publish(Msg, MsgProps, true, ChPid, Flow, BQS),
{ok, State1 #state { backing_queue_state = BQS1 }};
process_instruction({batch_publish, ChPid, Flow, Publishes}, State) ->
maybe_flow_ack(ChPid, Flow),
State1 = #state { backing_queue = BQ, backing_queue_state = BQS } =
lists:foldl(fun ({#basic_message { id = MsgId },
_MsgProps, _IsDelivered}, St) ->
publish_or_discard(published, ChPid, MsgId, St)
end, State, Publishes),
BQS1 = BQ:batch_publish(Publishes, ChPid, Flow, BQS),
{ok, State1 #state { backing_queue_state = BQS1 }};
process_instruction({publish_delivered, ChPid, Flow, MsgProps,
Msg = #basic_message { id = MsgId }}, State) ->
maybe_flow_ack(ChPid, Flow),
State1 = #state { backing_queue = BQ, backing_queue_state = BQS } =
publish_or_discard(published, ChPid, MsgId, State),
true = BQ:is_empty(BQS),
{AckTag, BQS1} = BQ:publish_delivered(Msg, MsgProps, ChPid, Flow, BQS),
{ok, maybe_store_ack(true, MsgId, AckTag,
State1 #state { backing_queue_state = BQS1 })};
process_instruction({batch_publish_delivered, ChPid, Flow, Publishes}, State) ->
maybe_flow_ack(ChPid, Flow),
{MsgIds,
State1 = #state { backing_queue = BQ, backing_queue_state = BQS }} =
lists:foldl(fun ({#basic_message { id = MsgId }, _MsgProps},
{MsgIds, St}) ->
{[MsgId | MsgIds],
publish_or_discard(published, ChPid, MsgId, St)}
end, {[], State}, Publishes),
true = BQ:is_empty(BQS),
{AckTags, BQS1} = BQ:batch_publish_delivered(Publishes, ChPid, Flow, BQS),
MsgIdsAndAcks = lists:zip(lists:reverse(MsgIds), AckTags),
State2 = lists:foldl(
fun ({MsgId, AckTag}, St) ->
maybe_store_ack(true, MsgId, AckTag, St)
end, State1 #state { backing_queue_state = BQS1 },
MsgIdsAndAcks),
{ok, State2};
process_instruction({discard, ChPid, Flow, MsgId}, State) ->
maybe_flow_ack(ChPid, Flow),
State1 = #state { backing_queue = BQ, backing_queue_state = BQS } =
publish_or_discard(discarded, ChPid, MsgId, State),
BQS1 = BQ:discard(MsgId, ChPid, Flow, BQS),
{ok, State1 #state { backing_queue_state = BQS1 }};
process_instruction({drop, Length, Dropped, AckRequired},
State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
QLen = BQ:len(BQS),
ToDrop = case QLen - Length of
N when N > 0 -> N;
_ -> 0
end,
State1 = lists:foldl(
fun (const, StateN = #state{backing_queue_state = BQSN}) ->
{{MsgId, AckTag}, BQSN1} = BQ:drop(AckRequired, BQSN),
maybe_store_ack(
AckRequired, MsgId, AckTag,
StateN #state { backing_queue_state = BQSN1 })
end, State, lists:duplicate(ToDrop, const)),
{ok, case AckRequired of
true -> State1;
false -> update_delta(ToDrop - Dropped, State1)
end};
process_instruction({ack, MsgIds},
State = #state { backing_queue = BQ,
backing_queue_state = BQS,
msg_id_ack = MA }) ->
{AckTags, MA1} = msg_ids_to_acktags(MsgIds, MA),
{MsgIds1, BQS1} = BQ:ack(AckTags, BQS),
{ok, update_delta(length(MsgIds1) - length(MsgIds),
State #state { msg_id_ack = MA1,
backing_queue_state = BQS1 })};
process_instruction({requeue, MsgIds},
State = #state { backing_queue = BQ,
backing_queue_state = BQS,
msg_id_ack = MA }) ->
{AckTags, MA1} = msg_ids_to_acktags(MsgIds, MA),
{_MsgIds, BQS1} = BQ:requeue(AckTags, BQS),
{ok, State #state { msg_id_ack = MA1,
backing_queue_state = BQS1 }};
process_instruction({sender_death, ChPid},
State = #state { known_senders = KS }) ->
{ok, case pmon:is_monitored(ChPid, KS) of
false -> State;
true -> maybe_forget_sender(ChPid, down_from_gm, State)
end};
process_instruction({depth, Depth},
State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
{ok, set_delta(Depth - BQ:depth(BQS), State)};
process_instruction({delete_and_terminate, Reason},
State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
BQ:delete_and_terminate(Reason, BQS),
{stop, State #state { backing_queue_state = undefined }};
process_instruction({set_queue_mode, Mode},
State = #state { backing_queue = BQ,
backing_queue_state = BQS }) ->
BQS1 = BQ:set_queue_mode(Mode, BQS),
{ok, State #state { backing_queue_state = BQS1 }}.
maybe_flow_ack(Sender, flow) -> credit_flow:ack(Sender);
maybe_flow_ack(_Sender, noflow) -> ok.
msg_ids_to_acktags(MsgIds, MA) ->
{AckTags, MA1} =
lists:foldl(
fun (MsgId, {Acc, MAN}) ->
case maps:find(MsgId, MA) of
error -> {Acc, MAN};
{ok, AckTag} -> {[AckTag | Acc], maps:remove(MsgId, MAN)}
end
end, {[], MA}, MsgIds),
{lists:reverse(AckTags), MA1}.
maybe_store_ack(false, _MsgId, _AckTag, State) ->
State;
maybe_store_ack(true, MsgId, AckTag, State = #state { msg_id_ack = MA }) ->
State #state { msg_id_ack = maps:put(MsgId, AckTag, MA) }.
set_delta(0, State = #state { depth_delta = undefined }) ->
ok = record_synchronised(State#state.q),
State #state { depth_delta = 0 };
set_delta(NewDelta, State = #state { depth_delta = undefined }) ->
State #state { depth_delta = NewDelta };
set_delta(NewDelta, State = #state { depth_delta = Delta }) ->
update_delta(NewDelta - Delta, State).
update_delta(_DeltaChange, State = #state { depth_delta = undefined }) ->
State;
update_delta( DeltaChange, State = #state { depth_delta = 0 }) ->
State;
update_delta( DeltaChange, State = #state { depth_delta = Delta }) ->
set_delta(Delta + DeltaChange, State #state { depth_delta = undefined }).
update_ram_duration(BQ, BQS) ->
{RamDuration, BQS1} = BQ:ram_duration(BQS),
DesiredDuration =
rabbit_memory_monitor:report_ram_duration(self(), RamDuration),
BQ:set_ram_duration_target(DesiredDuration, BQS1).
record_synchronised(Q0) when ?is_amqqueue(Q0) ->
QName = amqqueue:get_name(Q0),
Self = self(),
F = fun () ->
case mnesia:read({rabbit_queue, QName}) of
[] ->
ok;
[Q1] when ?is_amqqueue(Q1) ->
SSPids = amqqueue:get_sync_slave_pids(Q1),
SSPids1 = [Self | SSPids],
Q2 = amqqueue:set_sync_slave_pids(Q1, SSPids1),
rabbit_mirror_queue_misc:store_updated_slaves(Q2),
{ok, Q2}
end
end,
case rabbit_misc:execute_mnesia_transaction(F) of
ok -> ok;
{ok, Q2} -> rabbit_mirror_queue_misc:maybe_drop_master_after_sync(Q2)
end.
|
a4f15177f6c95527f5c93f8ce6640d8ab5f4a5797ea43e8e8812d5de8490858c | hedgehogqa/haskell-hedgehog-classes | Bifunctor.hs | module Spec.Bifunctor (testBifunctor) where
import Data.Functor.Const (Const(..))
import Hedgehog
import Hedgehog.Classes
import qualified Hedgehog.Gen as Gen
import Prelude hiding (either, const)
testBifunctor :: [(String, [Laws])]
testBifunctor =
[ ("Either", lawsEither)
, ("Const", lawsConst)
]
lawsEither :: [Laws]
lawsEither = [bifunctorLaws either]
lawsConst :: [Laws]
lawsConst = [bifunctorLaws const]
const :: MonadGen m => m a -> m b -> m (Const a b)
const genA _genB = fmap Const genA
either :: MonadGen m => m e -> m a -> m (Either e a)
either genE genA =
Gen.sized $ \n ->
Gen.frequency [
(2, Left <$> genE)
, (1 + fromIntegral n, Right <$> genA)
] | null | https://raw.githubusercontent.com/hedgehogqa/haskell-hedgehog-classes/4d97b000e915de8ba590818f551bce7bd862e7d4/test/Spec/Bifunctor.hs | haskell | module Spec.Bifunctor (testBifunctor) where
import Data.Functor.Const (Const(..))
import Hedgehog
import Hedgehog.Classes
import qualified Hedgehog.Gen as Gen
import Prelude hiding (either, const)
testBifunctor :: [(String, [Laws])]
testBifunctor =
[ ("Either", lawsEither)
, ("Const", lawsConst)
]
lawsEither :: [Laws]
lawsEither = [bifunctorLaws either]
lawsConst :: [Laws]
lawsConst = [bifunctorLaws const]
const :: MonadGen m => m a -> m b -> m (Const a b)
const genA _genB = fmap Const genA
either :: MonadGen m => m e -> m a -> m (Either e a)
either genE genA =
Gen.sized $ \n ->
Gen.frequency [
(2, Left <$> genE)
, (1 + fromIntegral n, Right <$> genA)
] |
|
aa1fe47792081d642c66a8d3968a56b4358101e2041b50b17c6a7ddee5b16851 | manuel-serrano/bigloo | specialize.scm | ;*=====================================================================*/
* ... /prgm / project / bigloo / / comptime / Cfa / specialize.scm * /
;* ------------------------------------------------------------- */
;* Author : SERRANO Manuel */
* Creation : Fri Apr 11 13:18:21 1997 * /
* Last change : We d Jun 16 15:57:38 2021 ( serrano ) * /
* Copyright : 1997 - 2021 , see LICENSE file * /
;* ------------------------------------------------------------- */
* This module implements an optimization asked by * /
* < > . What it does is , for each generic * /
* operation ( e.g. + , , ... ) if a specialized operation exists , * /
;* regarding Cfa type informations, the generic operation is */
;* replaced by the specific one. */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module cfa_specialize
(include "Tools/trace.sch"
"Cfa/specialize.sch")
(import engine_param
type_type
type_cache
type_typeof
tools_shape
tools_speek
tools_error
backend_backend
ast_var
ast_node
ast_env
inline_inline
inline_walk)
(static (wide-class specialized-global::global
fix))
(export (specialize! globals)
(arithmetic-operator? ::global)
(arithmetic-spec-types ::global)))
;*---------------------------------------------------------------------*/
;* specialize! ... */
;*---------------------------------------------------------------------*/
(define (specialize! globals)
(when (specialize-optimization?)
(trace (cfa 4) "============= specialize arithmetic ===============\n")
(for-each install-specialize! (get-specializations))
(patch-tree! globals)
(show-specialize)
(uninstall-specializes!))
globals)
;*---------------------------------------------------------------------*/
;* arithmetic-operator? ... */
;*---------------------------------------------------------------------*/
(define (arithmetic-operator? global)
(with-access::global global (id module)
(let ((cell (assq id (get-specializations))))
(and (pair? cell) (eq? (cadr (cadr cell)) module)))))
;*---------------------------------------------------------------------*/
;* arithmetic-spec-types ... */
;* ------------------------------------------------------------- */
;* In order to find the types an arithmetic operator is specialized */
;* for, we inspect which modules defines its specialized versions. */
;*---------------------------------------------------------------------*/
(define (arithmetic-spec-types global)
(with-access::global global (id module)
(let ((cell (assq id (get-specializations))))
(if (not (pair? cell))
'()
(let loop ((spec (cddr cell))
(types '()))
(cond
((null? spec)
types)
((and *optim-cfa-fixnum-arithmetic?*
(eq? (cadr (car spec)) '__r4_numbers_6_5_fixnum))
(loop (cdr spec) (cons *long* types)))
((and *optim-cfa-flonum-arithmetic?*
(eq? (cadr (car spec)) '__r4_numbers_6_5_flonum))
(loop (cdr spec) (cons *real* types)))
(else
(loop (cdr spec) types))))))))
;*---------------------------------------------------------------------*/
;* get-specializations ... */
;*---------------------------------------------------------------------*/
(define (get-specializations)
(cond
(*specializations*
;;; already computed
*specializations*)
(*arithmetic-overflow*
;;; compilation in a safe fixnum arithmetic mode
(set! *specializations* *specializations-sans-overflow*)
*specializations*)
(else
;;; don't check fixnum overflow, deploy more aggressive optimizations
(set! *specializations*
(append *specializations-overflow* *specializations-sans-overflow*))
*specializations*)))
;*---------------------------------------------------------------------*/
;* *specializations* ... */
;*---------------------------------------------------------------------*/
(define *specializations* #f)
;*---------------------------------------------------------------------*/
;* *specializations-sans-overflow* ... */
;*---------------------------------------------------------------------*/
(define *specializations-sans-overflow*
'((2+ (2+ __r4_numbers_6_5)
(+fl __r4_numbers_6_5_flonum))
(2- (2- __r4_numbers_6_5)
(-fl __r4_numbers_6_5_flonum))
(2* (2* __r4_numbers_6_5)
(*fl __r4_numbers_6_5_flonum))
(2/ (2/ __r4_numbers_6_5)
(/fl __r4_numbers_6_5_flonum))
(abs (abs __r4_numbers_6_5)
(absfl __r4_numbers_6_5_flonum))
(c-eq? (c-eq? foreign)
(=fx __r4_numbers_6_5_fixnum)
(=fl __r4_numbers_6_5_flonum))
(2= (2= __r4_numbers_6_5)
(=fx __r4_numbers_6_5_fixnum)
(=fl __r4_numbers_6_5_flonum))
(2< (2< __r4_numbers_6_5)
(<fx __r4_numbers_6_5_fixnum)
(<fl __r4_numbers_6_5_flonum))
(2> (2> __r4_numbers_6_5)
(>fx __r4_numbers_6_5_fixnum)
(>fl __r4_numbers_6_5_flonum))
(2<= (2<= __r4_numbers_6_5)
(<=fx __r4_numbers_6_5_fixnum)
(<=fl __r4_numbers_6_5_flonum))
(2>= (2>= __r4_numbers_6_5)
(>=fx __r4_numbers_6_5_fixnum)
(>=fl __r4_numbers_6_5_flonum))
(zero? (zero? __r4_numbers_6_5)
(zerofx? __r4_numbers_6_5_fixnum)
(zerofl? __r4_numbers_6_5_flonum))
(positive? (positive? __r4_numbers_6_5)
(positivefx? __r4_numbers_6_5_fixnum)
(positivefl? __r4_numbers_6_5_flonum))
(negative? (negative? __r4_numbers_6_5)
(negativefx? __r4_numbers_6_5_fixnum)
(negativefl? __r4_numbers_6_5_flonum))
(log (log __r4_numbers_6_5)
(logfl __r4_numbers_6_5_flonum))
(exp (exp __r4_numbers_6_5)
(expfl __r4_numbers_6_5_flonum))
(sin (sin __r4_numbers_6_5)
(sinfl __r4_numbers_6_5_flonum))
(cos (cos __r4_numbers_6_5)
(cosfl __r4_numbers_6_5_flonum))
(tan (tan __r4_numbers_6_5)
(tanfl __r4_numbers_6_5_flonum))
(atan (atan __r4_numbers_6_5)
(atanfl __r4_numbers_6_5_flonum))
(asin (asin __r4_numbers_6_5)
(asinfl __r4_numbers_6_5_flonum))
(acos (acos __r4_numbers_6_5)
(acosfl __r4_numbers_6_5_flonum))
(sqrt (sqrt __r4_numbers_6_5)
(sqrtfl __r4_numbers_6_5_flonum))))
(define *specializations-overflow*
'((2+ (2+ __r4_numbers_6_5)
(+fl __r4_numbers_6_5_flonum)
(+fx __r4_numbers_6_5_fixnum))
(2- (2- __r4_numbers_6_5)
(-fl __r4_numbers_6_5_flonum)
(-fx __r4_numbers_6_5_fixnum))
(2* (2* __r4_numbers_6_5)
(*fl __r4_numbers_6_5_flonum)
(*fx __r4_numbers_6_5_fixnum))
(abs (abs __r4_numbers_6_5)
(absfl __r4_numbers_6_5_flonum)
(absfx __r4_numbers_6_5_fixnum))))
(define *c-eq?* #unspecified)
;*---------------------------------------------------------------------*/
;* specialize-optimization? ... */
;*---------------------------------------------------------------------*/
(define (specialize-optimization?)
(and (>=fx *optim* 1) (not *lib-mode*)))
;*---------------------------------------------------------------------*/
;* show-specialize ... */
;*---------------------------------------------------------------------*/
(define (show-specialize)
(verbose 1 " . Specializing" #\newline)
(for-each (lambda (type-num)
(if (>fx (cdr type-num) 0)
(verbose 2 " (-> " (shape (car type-num))
": " (cdr type-num) #")\n")))
*specialized-types*)
(for-each (lambda (type-num)
(if (>fx (cdr type-num) 0)
(verbose 2 " (eq? " (shape (car type-num))
": " (cdr type-num) #")\n")))
*specialized-eq-types*))
;*---------------------------------------------------------------------*/
;* *specialize* ... */
;*---------------------------------------------------------------------*/
(define *specialize* '())
(define *specialized-types* '())
(define *specialized-eq-types* '())
(define *boxed-eq?* #unspecified)
;*---------------------------------------------------------------------*/
;* install-specialized-type! ... */
;*---------------------------------------------------------------------*/
(define (install-specialized-type! type)
(unless (pair? (assq type *specialized-types*))
(set! *specialized-types* (cons (cons type 0) *specialized-types*))
(set! *boxed-eq?* (find-global 'c-boxed-eq? 'foreign))
(set! *c-eq?* (find-global 'c-eq? 'foreign))))
;*---------------------------------------------------------------------*/
;* add-specialized-type! ... */
;*---------------------------------------------------------------------*/
(define (add-specialized-type! type)
(let ((cell (assq type *specialized-types*)))
(if (not (pair? cell))
(internal-error
"add-specialized-type!" "Unspecialized type" (shape type))
(set-cdr! cell (+fx 1 (cdr cell))))))
;*---------------------------------------------------------------------*/
;* add-specialized-eq-type! ... */
;*---------------------------------------------------------------------*/
(define (add-specialized-eq-type! type)
(let ((cell (assq type *specialized-eq-types*)))
(if (not (pair? cell))
(set! *specialized-eq-types*
(cons (cons type 1) *specialized-eq-types*))
(set-cdr! cell (+fx 1 (cdr cell))))))
;*---------------------------------------------------------------------*/
;* install-specialize! ... */
;*---------------------------------------------------------------------*/
(define (install-specialize! spec)
(let* ((gen (cadr spec))
(fixes (cddr spec))
(gen-id (car gen))
(gen-mod (cadr gen))
(generic (find-global/module gen-id gen-mod)))
(if (global? generic)
(let loop ((fixes fixes)
(res '()))
(if (null? fixes)
(if (specialized-global? generic)
(with-access::specialized-global generic (fix)
(set! fix (append fix res)))
(begin
(widen!::specialized-global generic
(fix res))
(set! *specialize* (cons generic *specialize*))))
(let* ((fix (car fixes))
(id (car fix))
(mod (cadr fix))
(global (find-global/module id mod)))
(if (global? global)
(let ((val (global-value global)))
(cond
((and (sfun? val) (pair? (sfun-args val)))
(let ((type (let ((v (car (sfun-args val))))
(cond
((type? v)
v)
((local? v)
(local-type v))
(else
(internal-error
"install-specialize"
"Illegal argument"
(global-id global)))))))
(install-specialized-type! type)
(loop (cdr fixes)
(cons (cons type global) res))))
((and (cfun? val) (pair? (cfun-args-type val)))
(let ((type (car (cfun-args-type val))))
(install-specialized-type! type)
(loop (cdr fixes)
(cons (cons type global) res))))))
(begin
(warning "install-specialize!"
"Can't find global"
" -- "
(cons id mod))
(loop (cdr fixes) res))))))
(warning "install-specialize!"
"Can't find global"
" -- "
(cons gen-id gen-mod)))))
;*---------------------------------------------------------------------*/
;* uninstall-specializes! ... */
;*---------------------------------------------------------------------*/
(define (uninstall-specializes!)
(set! *specialized-types* '())
(for-each (lambda (o) (shrink! o)) *specialize*)
(set! *specialize* '()))
;*---------------------------------------------------------------------*/
;* patch-tree! ... */
;*---------------------------------------------------------------------*/
(define (patch-tree! globals)
(for-each patch-fun! globals))
;*---------------------------------------------------------------------*/
;* patch-fun! ... */
;*---------------------------------------------------------------------*/
(define (patch-fun! variable)
(let ((fun (variable-value variable)))
(sfun-body-set! fun (patch! (sfun-body fun)))))
;*---------------------------------------------------------------------*/
;* patch! ... */
;*---------------------------------------------------------------------*/
(define-generic (patch! node::node))
;*---------------------------------------------------------------------*/
;* patch! ::atom ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::atom)
node)
;*---------------------------------------------------------------------*/
;* patch! ::kwote ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::kwote)
node)
;*---------------------------------------------------------------------*/
;* patch! ::var ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::var)
node)
;*---------------------------------------------------------------------*/
;* patch! ::closure ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::closure)
(internal-error "patch!" "Unexpected closure" (shape node)))
;*---------------------------------------------------------------------*/
;* patch! ::sequence ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::sequence)
(with-access::sequence node (type nodes)
(patch*! nodes)
(when (eq? type *obj*)
(set! type *_*)
(set! type (get-type node #f)))
node))
;*---------------------------------------------------------------------*/
;* patch! ::sync ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::sync)
(with-access::sync node (type body mutex prelock)
(set! mutex (patch! mutex))
(set! prelock (patch! prelock))
(set! body (patch! body))
(when (eq? type *obj*)
(set! type *_*)
(set! type (get-type node #f)))
node))
;*---------------------------------------------------------------------*/
;* patch! ::app-ly ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::app-ly)
(with-access::app-ly node (fun arg)
(set! fun (patch! fun))
(set! arg (patch! arg))
node))
;*---------------------------------------------------------------------*/
;* patch! ::funcall ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::funcall)
(with-access::funcall node (fun args)
(set! fun (patch! fun))
(patch*! args)
node))
;*---------------------------------------------------------------------*/
;* patch! ::extern ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::extern)
(with-access::extern node (expr* type)
(patch*! expr*)
node))
;*---------------------------------------------------------------------*/
;* patch! ::cast ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::cast)
(with-access::cast node (arg)
(patch! arg)
node))
;*---------------------------------------------------------------------*/
;* patch! ::setq ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::setq)
(with-access::setq node (var value)
(set! value (patch! value))
(set! var (patch! var))
node))
;*---------------------------------------------------------------------*/
;* patch! ::conditional ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::conditional)
(with-access::conditional node (type test true false)
(set! test (patch! test))
(set! true (patch! true))
(set! false (patch! false))
(when (eq? type *obj*)
(set! type *_*)
(set! type (get-type node #f)))
node))
;*---------------------------------------------------------------------*/
;* patch! ::fail ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::fail)
(with-access::fail node (proc msg obj)
(set! proc (patch! proc))
(set! msg (patch! msg))
(set! obj (patch! obj))
node))
;*---------------------------------------------------------------------*/
;* patch! ::switch ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::switch)
(with-access::switch node (clauses test)
(set! test (patch! test))
(for-each (lambda (clause)
(set-cdr! clause (patch! (cdr clause))))
clauses)
node))
;*---------------------------------------------------------------------*/
;* patch! ::let-fun ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::let-fun)
(with-access::let-fun node (type body locals)
(for-each patch-fun! locals)
(set! body (patch! body))
(when (eq? type *obj*)
(set! type *_*)
(set! type (get-type node #f)))
node))
;*---------------------------------------------------------------------*/
;* patch! ::let-var ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::let-var)
(with-access::let-var node (type body bindings)
(for-each (lambda (binding)
(let ((val (cdr binding)))
(set-cdr! binding (patch! val))))
bindings)
(set! body (patch! body))
(when (eq? type *obj*)
(set! type *_*)
(set! type (get-type node #f)))
node))
;*---------------------------------------------------------------------*/
;* patch! ::set-ex-it ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::set-ex-it)
(with-access::set-ex-it node (var body onexit)
(set! body (patch! body))
(set! onexit (patch! onexit))
(patch! var)
node))
;*---------------------------------------------------------------------*/
;* patch! ::jump-ex-it ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::jump-ex-it)
(with-access::jump-ex-it node (exit value)
(set! exit (patch! exit))
(set! value (patch! value))
node))
;*---------------------------------------------------------------------*/
;* patch! ::make-box ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::make-box)
(with-access::make-box node (value)
(set! value (patch! value))
node))
;*---------------------------------------------------------------------*/
;* patch! ::box-set! ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::box-set!)
(with-access::box-set! node (var value)
(set! var (patch! var))
(set! value (patch! value))
node))
;*---------------------------------------------------------------------*/
;* patch! ::box-ref ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::box-ref)
(with-access::box-ref node (var)
(set! var (patch! var))
node))
;*---------------------------------------------------------------------*/
;* patch*! ... */
;*---------------------------------------------------------------------*/
(define (patch*! node*)
(let loop ((node* node*))
(if (null? node*)
'done
(begin
(set-car! node* (patch! (car node*)))
(loop (cdr node*))))))
;*---------------------------------------------------------------------*/
;* patch! ::app ... */
;*---------------------------------------------------------------------*/
(define-method (patch! node::app)
(with-access::app node (fun args)
(patch*! args)
(set! fun (patch! fun))
(let ((v (var-variable fun)))
(cond
((specialized-global? v)
(specialize-app! node))
(else
node)))))
;*---------------------------------------------------------------------*/
;* specialize-app! ... */
;*---------------------------------------------------------------------*/
(define (specialize-app!::app node::app)
(define (normalize-get-type val)
(let ((ty (get-type val #f)))
(if (eq? ty *int*)
*long*
ty)))
(with-access::app node (fun args)
(if (null? args)
node
;; we check if the type of all the arguments
;; is either fixnum or flonum
(let* ((type (normalize-get-type (car args)))
(glo (var-variable fun))
(spec (assq type (specialized-global-fix glo))))
(if (pair? spec)
(let loop ((args (cdr args)))
(cond
((null? args)
(add-specialized-type! type)
(var-variable-set! fun (cdr spec))
(let ((nt (variable-type (var-variable fun))))
(node-type-set! node (strict-node-type nt type)))
node)
((eq? (normalize-get-type (car args)) type)
(loop (cdr args)))
(else
;; sorry, it fails
(specialize-eq? node))))
(specialize-eq? node))))))
;*---------------------------------------------------------------------*/
;* specialize-eq? ... */
;* ------------------------------------------------------------- */
;* For the JVM back-end it is important to use a kind of non */
* fully - polymorph definition of EQ ? as soon as one of the * /
;* argument is known not to be an integer. */
;*---------------------------------------------------------------------*/
(define (specialize-eq? node)
(with-access::app node (fun args)
(define (boxed-eq! node type)
(when (global? *boxed-eq?*)
(var-variable-set! fun *boxed-eq?*)
(add-specialized-eq-type! type)))
;; arguments type have been erase, we have to restore them now
(if (and (eq? (var-variable fun) *c-eq?*)
(backend-typed-eq (the-backend)))
;; here we are...
(let ((t1 (get-type (car args) #f))
(t2 (get-type (cadr args) #f)))
(cond
((and (eq? t1 *obj*) (eq? t2 *obj*))
#unspecified)
((eq? t1 *bint*)
(if (eq? t2 *bint*)
;; we specialize for an boxed integers eq?
(boxed-eq! node *bint*)))
((eq? t2 *bint*)
#unspecified)
((eq? t1 *breal*)
(if (eq? t2 *breal*)
;; we specialize for an boxed reals eq?
(boxed-eq! node *breal*)))
((eq? t2 *breal*)
#unspecified)
((eq? t2 *bint*)
#unspecified)
((eq? t1 *bchar*)
(if (eq? t2 *bchar*)
;; we specialize for an boxed chars eq?
(boxed-eq! node *bchar*)))
((eq? t2 *bchar*)
#unspecified)
((and (bigloo-type? t1) (bigloo-type? t2))
;; we specialize with a boxed eq?
(boxed-eq! node (if (eq? t1 *obj*) t2 t1)))
(else
#unspecified))
node)
node)))
<
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/fdeac39af72d5119d01818815b0f395f2907d6da/comptime/Cfa/specialize.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* Author : SERRANO Manuel */
* ------------------------------------------------------------- */
* regarding Cfa type informations, the generic operation is */
* replaced by the specific one. */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* specialize! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* arithmetic-operator? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* arithmetic-spec-types ... */
* ------------------------------------------------------------- */
* In order to find the types an arithmetic operator is specialized */
* for, we inspect which modules defines its specialized versions. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* get-specializations ... */
*---------------------------------------------------------------------*/
already computed
compilation in a safe fixnum arithmetic mode
don't check fixnum overflow, deploy more aggressive optimizations
*---------------------------------------------------------------------*/
* *specializations* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *specializations-sans-overflow* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* specialize-optimization? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* show-specialize ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *specialize* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* install-specialized-type! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* add-specialized-type! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* add-specialized-eq-type! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* install-specialize! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* uninstall-specializes! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch-tree! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch-fun! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::atom ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::kwote ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::var ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::closure ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::sequence ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::sync ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::app-ly ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::funcall ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::extern ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::cast ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::setq ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::conditional ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::fail ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::switch ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::let-fun ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::let-var ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::set-ex-it ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::jump-ex-it ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::make-box ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::box-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::box-ref ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch*! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* patch! ::app ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* specialize-app! ... */
*---------------------------------------------------------------------*/
we check if the type of all the arguments
is either fixnum or flonum
sorry, it fails
*---------------------------------------------------------------------*/
* specialize-eq? ... */
* ------------------------------------------------------------- */
* For the JVM back-end it is important to use a kind of non */
* argument is known not to be an integer. */
*---------------------------------------------------------------------*/
arguments type have been erase, we have to restore them now
here we are...
we specialize for an boxed integers eq?
we specialize for an boxed reals eq?
we specialize for an boxed chars eq?
we specialize with a boxed eq? | * ... /prgm / project / bigloo / / comptime / Cfa / specialize.scm * /
* Creation : Fri Apr 11 13:18:21 1997 * /
* Last change : We d Jun 16 15:57:38 2021 ( serrano ) * /
* Copyright : 1997 - 2021 , see LICENSE file * /
* This module implements an optimization asked by * /
* < > . What it does is , for each generic * /
* operation ( e.g. + , , ... ) if a specialized operation exists , * /
(module cfa_specialize
(include "Tools/trace.sch"
"Cfa/specialize.sch")
(import engine_param
type_type
type_cache
type_typeof
tools_shape
tools_speek
tools_error
backend_backend
ast_var
ast_node
ast_env
inline_inline
inline_walk)
(static (wide-class specialized-global::global
fix))
(export (specialize! globals)
(arithmetic-operator? ::global)
(arithmetic-spec-types ::global)))
(define (specialize! globals)
(when (specialize-optimization?)
(trace (cfa 4) "============= specialize arithmetic ===============\n")
(for-each install-specialize! (get-specializations))
(patch-tree! globals)
(show-specialize)
(uninstall-specializes!))
globals)
(define (arithmetic-operator? global)
(with-access::global global (id module)
(let ((cell (assq id (get-specializations))))
(and (pair? cell) (eq? (cadr (cadr cell)) module)))))
(define (arithmetic-spec-types global)
(with-access::global global (id module)
(let ((cell (assq id (get-specializations))))
(if (not (pair? cell))
'()
(let loop ((spec (cddr cell))
(types '()))
(cond
((null? spec)
types)
((and *optim-cfa-fixnum-arithmetic?*
(eq? (cadr (car spec)) '__r4_numbers_6_5_fixnum))
(loop (cdr spec) (cons *long* types)))
((and *optim-cfa-flonum-arithmetic?*
(eq? (cadr (car spec)) '__r4_numbers_6_5_flonum))
(loop (cdr spec) (cons *real* types)))
(else
(loop (cdr spec) types))))))))
(define (get-specializations)
(cond
(*specializations*
*specializations*)
(*arithmetic-overflow*
(set! *specializations* *specializations-sans-overflow*)
*specializations*)
(else
(set! *specializations*
(append *specializations-overflow* *specializations-sans-overflow*))
*specializations*)))
(define *specializations* #f)
(define *specializations-sans-overflow*
'((2+ (2+ __r4_numbers_6_5)
(+fl __r4_numbers_6_5_flonum))
(2- (2- __r4_numbers_6_5)
(-fl __r4_numbers_6_5_flonum))
(2* (2* __r4_numbers_6_5)
(*fl __r4_numbers_6_5_flonum))
(2/ (2/ __r4_numbers_6_5)
(/fl __r4_numbers_6_5_flonum))
(abs (abs __r4_numbers_6_5)
(absfl __r4_numbers_6_5_flonum))
(c-eq? (c-eq? foreign)
(=fx __r4_numbers_6_5_fixnum)
(=fl __r4_numbers_6_5_flonum))
(2= (2= __r4_numbers_6_5)
(=fx __r4_numbers_6_5_fixnum)
(=fl __r4_numbers_6_5_flonum))
(2< (2< __r4_numbers_6_5)
(<fx __r4_numbers_6_5_fixnum)
(<fl __r4_numbers_6_5_flonum))
(2> (2> __r4_numbers_6_5)
(>fx __r4_numbers_6_5_fixnum)
(>fl __r4_numbers_6_5_flonum))
(2<= (2<= __r4_numbers_6_5)
(<=fx __r4_numbers_6_5_fixnum)
(<=fl __r4_numbers_6_5_flonum))
(2>= (2>= __r4_numbers_6_5)
(>=fx __r4_numbers_6_5_fixnum)
(>=fl __r4_numbers_6_5_flonum))
(zero? (zero? __r4_numbers_6_5)
(zerofx? __r4_numbers_6_5_fixnum)
(zerofl? __r4_numbers_6_5_flonum))
(positive? (positive? __r4_numbers_6_5)
(positivefx? __r4_numbers_6_5_fixnum)
(positivefl? __r4_numbers_6_5_flonum))
(negative? (negative? __r4_numbers_6_5)
(negativefx? __r4_numbers_6_5_fixnum)
(negativefl? __r4_numbers_6_5_flonum))
(log (log __r4_numbers_6_5)
(logfl __r4_numbers_6_5_flonum))
(exp (exp __r4_numbers_6_5)
(expfl __r4_numbers_6_5_flonum))
(sin (sin __r4_numbers_6_5)
(sinfl __r4_numbers_6_5_flonum))
(cos (cos __r4_numbers_6_5)
(cosfl __r4_numbers_6_5_flonum))
(tan (tan __r4_numbers_6_5)
(tanfl __r4_numbers_6_5_flonum))
(atan (atan __r4_numbers_6_5)
(atanfl __r4_numbers_6_5_flonum))
(asin (asin __r4_numbers_6_5)
(asinfl __r4_numbers_6_5_flonum))
(acos (acos __r4_numbers_6_5)
(acosfl __r4_numbers_6_5_flonum))
(sqrt (sqrt __r4_numbers_6_5)
(sqrtfl __r4_numbers_6_5_flonum))))
(define *specializations-overflow*
'((2+ (2+ __r4_numbers_6_5)
(+fl __r4_numbers_6_5_flonum)
(+fx __r4_numbers_6_5_fixnum))
(2- (2- __r4_numbers_6_5)
(-fl __r4_numbers_6_5_flonum)
(-fx __r4_numbers_6_5_fixnum))
(2* (2* __r4_numbers_6_5)
(*fl __r4_numbers_6_5_flonum)
(*fx __r4_numbers_6_5_fixnum))
(abs (abs __r4_numbers_6_5)
(absfl __r4_numbers_6_5_flonum)
(absfx __r4_numbers_6_5_fixnum))))
(define *c-eq?* #unspecified)
(define (specialize-optimization?)
(and (>=fx *optim* 1) (not *lib-mode*)))
(define (show-specialize)
(verbose 1 " . Specializing" #\newline)
(for-each (lambda (type-num)
(if (>fx (cdr type-num) 0)
(verbose 2 " (-> " (shape (car type-num))
": " (cdr type-num) #")\n")))
*specialized-types*)
(for-each (lambda (type-num)
(if (>fx (cdr type-num) 0)
(verbose 2 " (eq? " (shape (car type-num))
": " (cdr type-num) #")\n")))
*specialized-eq-types*))
(define *specialize* '())
(define *specialized-types* '())
(define *specialized-eq-types* '())
(define *boxed-eq?* #unspecified)
(define (install-specialized-type! type)
(unless (pair? (assq type *specialized-types*))
(set! *specialized-types* (cons (cons type 0) *specialized-types*))
(set! *boxed-eq?* (find-global 'c-boxed-eq? 'foreign))
(set! *c-eq?* (find-global 'c-eq? 'foreign))))
(define (add-specialized-type! type)
(let ((cell (assq type *specialized-types*)))
(if (not (pair? cell))
(internal-error
"add-specialized-type!" "Unspecialized type" (shape type))
(set-cdr! cell (+fx 1 (cdr cell))))))
(define (add-specialized-eq-type! type)
(let ((cell (assq type *specialized-eq-types*)))
(if (not (pair? cell))
(set! *specialized-eq-types*
(cons (cons type 1) *specialized-eq-types*))
(set-cdr! cell (+fx 1 (cdr cell))))))
(define (install-specialize! spec)
(let* ((gen (cadr spec))
(fixes (cddr spec))
(gen-id (car gen))
(gen-mod (cadr gen))
(generic (find-global/module gen-id gen-mod)))
(if (global? generic)
(let loop ((fixes fixes)
(res '()))
(if (null? fixes)
(if (specialized-global? generic)
(with-access::specialized-global generic (fix)
(set! fix (append fix res)))
(begin
(widen!::specialized-global generic
(fix res))
(set! *specialize* (cons generic *specialize*))))
(let* ((fix (car fixes))
(id (car fix))
(mod (cadr fix))
(global (find-global/module id mod)))
(if (global? global)
(let ((val (global-value global)))
(cond
((and (sfun? val) (pair? (sfun-args val)))
(let ((type (let ((v (car (sfun-args val))))
(cond
((type? v)
v)
((local? v)
(local-type v))
(else
(internal-error
"install-specialize"
"Illegal argument"
(global-id global)))))))
(install-specialized-type! type)
(loop (cdr fixes)
(cons (cons type global) res))))
((and (cfun? val) (pair? (cfun-args-type val)))
(let ((type (car (cfun-args-type val))))
(install-specialized-type! type)
(loop (cdr fixes)
(cons (cons type global) res))))))
(begin
(warning "install-specialize!"
"Can't find global"
" -- "
(cons id mod))
(loop (cdr fixes) res))))))
(warning "install-specialize!"
"Can't find global"
" -- "
(cons gen-id gen-mod)))))
(define (uninstall-specializes!)
(set! *specialized-types* '())
(for-each (lambda (o) (shrink! o)) *specialize*)
(set! *specialize* '()))
(define (patch-tree! globals)
(for-each patch-fun! globals))
(define (patch-fun! variable)
(let ((fun (variable-value variable)))
(sfun-body-set! fun (patch! (sfun-body fun)))))
(define-generic (patch! node::node))
(define-method (patch! node::atom)
node)
(define-method (patch! node::kwote)
node)
(define-method (patch! node::var)
node)
(define-method (patch! node::closure)
(internal-error "patch!" "Unexpected closure" (shape node)))
(define-method (patch! node::sequence)
(with-access::sequence node (type nodes)
(patch*! nodes)
(when (eq? type *obj*)
(set! type *_*)
(set! type (get-type node #f)))
node))
(define-method (patch! node::sync)
(with-access::sync node (type body mutex prelock)
(set! mutex (patch! mutex))
(set! prelock (patch! prelock))
(set! body (patch! body))
(when (eq? type *obj*)
(set! type *_*)
(set! type (get-type node #f)))
node))
(define-method (patch! node::app-ly)
(with-access::app-ly node (fun arg)
(set! fun (patch! fun))
(set! arg (patch! arg))
node))
(define-method (patch! node::funcall)
(with-access::funcall node (fun args)
(set! fun (patch! fun))
(patch*! args)
node))
(define-method (patch! node::extern)
(with-access::extern node (expr* type)
(patch*! expr*)
node))
(define-method (patch! node::cast)
(with-access::cast node (arg)
(patch! arg)
node))
(define-method (patch! node::setq)
(with-access::setq node (var value)
(set! value (patch! value))
(set! var (patch! var))
node))
(define-method (patch! node::conditional)
(with-access::conditional node (type test true false)
(set! test (patch! test))
(set! true (patch! true))
(set! false (patch! false))
(when (eq? type *obj*)
(set! type *_*)
(set! type (get-type node #f)))
node))
(define-method (patch! node::fail)
(with-access::fail node (proc msg obj)
(set! proc (patch! proc))
(set! msg (patch! msg))
(set! obj (patch! obj))
node))
(define-method (patch! node::switch)
(with-access::switch node (clauses test)
(set! test (patch! test))
(for-each (lambda (clause)
(set-cdr! clause (patch! (cdr clause))))
clauses)
node))
(define-method (patch! node::let-fun)
(with-access::let-fun node (type body locals)
(for-each patch-fun! locals)
(set! body (patch! body))
(when (eq? type *obj*)
(set! type *_*)
(set! type (get-type node #f)))
node))
(define-method (patch! node::let-var)
(with-access::let-var node (type body bindings)
(for-each (lambda (binding)
(let ((val (cdr binding)))
(set-cdr! binding (patch! val))))
bindings)
(set! body (patch! body))
(when (eq? type *obj*)
(set! type *_*)
(set! type (get-type node #f)))
node))
(define-method (patch! node::set-ex-it)
(with-access::set-ex-it node (var body onexit)
(set! body (patch! body))
(set! onexit (patch! onexit))
(patch! var)
node))
(define-method (patch! node::jump-ex-it)
(with-access::jump-ex-it node (exit value)
(set! exit (patch! exit))
(set! value (patch! value))
node))
(define-method (patch! node::make-box)
(with-access::make-box node (value)
(set! value (patch! value))
node))
(define-method (patch! node::box-set!)
(with-access::box-set! node (var value)
(set! var (patch! var))
(set! value (patch! value))
node))
(define-method (patch! node::box-ref)
(with-access::box-ref node (var)
(set! var (patch! var))
node))
(define (patch*! node*)
(let loop ((node* node*))
(if (null? node*)
'done
(begin
(set-car! node* (patch! (car node*)))
(loop (cdr node*))))))
(define-method (patch! node::app)
(with-access::app node (fun args)
(patch*! args)
(set! fun (patch! fun))
(let ((v (var-variable fun)))
(cond
((specialized-global? v)
(specialize-app! node))
(else
node)))))
(define (specialize-app!::app node::app)
(define (normalize-get-type val)
(let ((ty (get-type val #f)))
(if (eq? ty *int*)
*long*
ty)))
(with-access::app node (fun args)
(if (null? args)
node
(let* ((type (normalize-get-type (car args)))
(glo (var-variable fun))
(spec (assq type (specialized-global-fix glo))))
(if (pair? spec)
(let loop ((args (cdr args)))
(cond
((null? args)
(add-specialized-type! type)
(var-variable-set! fun (cdr spec))
(let ((nt (variable-type (var-variable fun))))
(node-type-set! node (strict-node-type nt type)))
node)
((eq? (normalize-get-type (car args)) type)
(loop (cdr args)))
(else
(specialize-eq? node))))
(specialize-eq? node))))))
* fully - polymorph definition of EQ ? as soon as one of the * /
(define (specialize-eq? node)
(with-access::app node (fun args)
(define (boxed-eq! node type)
(when (global? *boxed-eq?*)
(var-variable-set! fun *boxed-eq?*)
(add-specialized-eq-type! type)))
(if (and (eq? (var-variable fun) *c-eq?*)
(backend-typed-eq (the-backend)))
(let ((t1 (get-type (car args) #f))
(t2 (get-type (cadr args) #f)))
(cond
((and (eq? t1 *obj*) (eq? t2 *obj*))
#unspecified)
((eq? t1 *bint*)
(if (eq? t2 *bint*)
(boxed-eq! node *bint*)))
((eq? t2 *bint*)
#unspecified)
((eq? t1 *breal*)
(if (eq? t2 *breal*)
(boxed-eq! node *breal*)))
((eq? t2 *breal*)
#unspecified)
((eq? t2 *bint*)
#unspecified)
((eq? t1 *bchar*)
(if (eq? t2 *bchar*)
(boxed-eq! node *bchar*)))
((eq? t2 *bchar*)
#unspecified)
((and (bigloo-type? t1) (bigloo-type? t2))
(boxed-eq! node (if (eq? t1 *obj*) t2 t1)))
(else
#unspecified))
node)
node)))
<
|
d68fbe2cf1fa8d226b7148ec462842391531b2cd64e4092d24d1dab2a4a7e29d | spawnfest/eep49ers | base64_SUITE.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2007 - 2017 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
-module(base64_SUITE).
-include_lib("common_test/include/ct.hrl").
%% Test server specific exports
-export([all/0, suite/0, groups/0, group/1]).
%% Test cases must be exported.
-export([base64_encode/1, base64_decode/1, base64_otp_5635/1,
base64_otp_6279/1, big/1, illegal/1, mime_decode/1,
mime_decode_to_string/1,
roundtrip_1/1, roundtrip_2/1, roundtrip_3/1, roundtrip_4/1]).
%%-------------------------------------------------------------------------
%% Test cases starts here.
%%-------------------------------------------------------------------------
suite() ->
[{ct_hooks,[ts_install_cth]},
{timetrap,{minutes,4}}].
all() ->
[base64_encode, base64_decode, base64_otp_5635,
base64_otp_6279, big, illegal, mime_decode, mime_decode_to_string,
{group, roundtrip}].
groups() ->
[{roundtrip, [parallel],
[roundtrip_1, roundtrip_2, roundtrip_3, roundtrip_4]}].
group(roundtrip) ->
%% valgrind needs a lot of time
[{timetrap,{minutes,10}}].
%%-------------------------------------------------------------------------
%% Test base64:encode/1.
base64_encode(Config) when is_list(Config) ->
Two pads
<<"QWxhZGRpbjpvcGVuIHNlc2FtZQ==">> =
base64:encode("Aladdin:open sesame"),
One pad
<<"SGVsbG8gV29ybGQ=">> = base64:encode(<<"Hello World">>),
%% No pad
"QWxhZGRpbjpvcGVuIHNlc2Ft" =
base64:encode_to_string("Aladdin:open sesam"),
"MDEyMzQ1Njc4OSFAIzBeJiooKTs6PD4sLiBbXXt9" =
base64:encode_to_string(<<"0123456789!@#0^&*();:<>,. []{}">>),
ok.
%%-------------------------------------------------------------------------
%% Test base64:decode/1.
base64_decode(Config) when is_list(Config) ->
Two pads
<<"Aladdin:open sesame">> =
base64:decode("QWxhZGRpbjpvcGVuIHNlc2FtZQ=="),
One pad
<<"Hello World">> = base64:decode(<<"SGVsbG8gV29ybGQ=">>),
%% No pad
<<"Aladdin:open sesam">> =
base64:decode("QWxhZGRpbjpvcGVuIHNlc2Ft"),
Alphabet = list_to_binary(lists:seq(0, 255)),
Alphabet = base64:decode(base64:encode(Alphabet)),
Encoded base 64 strings may be divided by non base 64 chars .
%% In this cases whitespaces.
"0123456789!@#0^&*();:<>,. []{}" =
base64:decode_to_string(
"MDEy MzQ1Njc4 \tOSFAIzBeJ \niooKTs6 PD4sLi \r\nBbXXt9"),
"0123456789!@#0^&*();:<>,. []{}" =
base64:decode_to_string(
<<"MDEy MzQ1Njc4 \tOSFAIzBeJ \niooKTs6 PD4sLi \r\nBbXXt9">>),
ok.
%%-------------------------------------------------------------------------
%% OTP-5635: Some data doesn't pass through base64:decode/1 correctly.
base64_otp_5635(Config) when is_list(Config) ->
<<"===">> = base64:decode(base64:encode("===")),
ok.
%%-------------------------------------------------------------------------
%% OTP-6279: Make sure illegal characters are rejected when decoding.
base64_otp_6279(Config) when is_list(Config) ->
{'EXIT',_} = (catch base64:decode("dGVzda==a")),
ok.
%%-------------------------------------------------------------------------
%% Encode and decode big binaries.
big(Config) when is_list(Config) ->
Big = make_big_binary(300000),
B = base64:encode(Big),
true = is_binary(B),
400000 = byte_size(B),
Big = base64:decode(B),
Big = base64:mime_decode(B),
ok.
%%-------------------------------------------------------------------------
%% Make sure illegal characters are rejected when decoding.
illegal(Config) when is_list(Config) ->
%% A few samples with different error reasons. Nothing can be
%% assumed about the reason for the crash.
{'EXIT',_} = (catch base64:decode("()")),
{'EXIT',_} = (catch base64:decode(<<19:8,20:8,21:8,22:8>>)),
{'EXIT',_} = (catch base64:decode([19,20,21,22])),
{'EXIT',_} = (catch base64:decode_to_string(<<19:8,20:8,21:8,22:8>>)),
{'EXIT',_} = (catch base64:decode_to_string([19,20,21,22])),
ok.
%%-------------------------------------------------------------------------
%% mime_decode and mime_decode_to_string have different implementations
%% so test both with the same input separately.
%%
Test base64 : .
mime_decode(Config) when is_list(Config) ->
MimeDecode = fun(In) ->
Out = base64:mime_decode(In),
Out = base64:mime_decode(binary_to_list(In))
end,
%% Test correct padding
<<"one">> = MimeDecode(<<"b25l">>),
<<"on">> = MimeDecode(<<"b24=">>),
<<"o">> = MimeDecode(<<"bw==">>),
Test 1 extra padding
<<"one">> = MimeDecode(<<"b25l= =">>),
<<"on">> = MimeDecode(<<"b24== =">>),
<<"o">> = MimeDecode(<<"bw=== =">>),
Test 2 extra padding
<<"one">> = MimeDecode(<<"b25l===">>),
<<"on">> = MimeDecode(<<"b24====">>),
<<"o">> = MimeDecode(<<"bw=====">>),
%% Test misc embedded padding
<<"one">> = MimeDecode(<<"b2=5l===">>),
<<"on">> = MimeDecode(<<"b=24====">>),
<<"o">> = MimeDecode(<<"b=w=====">>),
%% Test misc white space and illegals with embedded padding
<<"one">> = MimeDecode(<<" b~2=\r\n5()l===">>),
<<"on">> = MimeDecode(<<"\tb =2\"¤4=¤= ==">>),
<<"o">> = MimeDecode(<<"\nb=w=====">>),
Two pads
<<"Aladdin:open sesame">> =
MimeDecode(<<"QWxhZGRpbjpvc()GVuIHNlc2FtZQ==">>),
One pad to ignore , followed by more text
<<"Hello World!!">> = MimeDecode(<<"SGVsb)(G8gV29ybGQ=h IQ= =">>),
%% No pad
<<"Aladdin:open sesam">> =
MimeDecode(<<"QWxhZGRpbjpvcG¤\")(VuIHNlc2Ft">>),
Encoded base 64 strings may be divided by non base 64 chars .
%% In this cases whitespaces.
<<"0123456789!@#0^&*();:<>,. []{}">> =
MimeDecode(
<<"MDEy MzQ1Njc4 \tOSFAIzBeJ \nio)(oKTs6 PD4sLi \r\nBbXXt9">>),
Zeroes
<<"012">> = MimeDecode(<<"\000M\000D\000E\000y=\000">>),
<<"o">> = MimeDecode(<<"bw==\000">>),
<<"o">> = MimeDecode(<<"bw=\000=">>),
ok.
%%-------------------------------------------------------------------------
%% Repeat of mime_decode() tests
%% Test base64:mime_decode_to_string/1.
mime_decode_to_string(Config) when is_list(Config) ->
MimeDecodeToString =
fun(In) ->
Out = base64:mime_decode_to_string(In),
Out = base64:mime_decode_to_string(binary_to_list(In))
end,
%% Test correct padding
"one" = MimeDecodeToString(<<"b25l">>),
"on" = MimeDecodeToString(<<"b24=">>),
"o" = MimeDecodeToString(<<"bw==">>),
Test 1 extra padding
"one" = MimeDecodeToString(<<"b25l= =">>),
"on" = MimeDecodeToString(<<"b24== =">>),
"o" = MimeDecodeToString(<<"bw=== =">>),
Test 2 extra padding
"one" = MimeDecodeToString(<<"b25l===">>),
"on" = MimeDecodeToString(<<"b24====">>),
"o" = MimeDecodeToString(<<"bw=====">>),
%% Test misc embedded padding
"one" = MimeDecodeToString(<<"b2=5l===">>),
"on" = MimeDecodeToString(<<"b=24====">>),
"o" = MimeDecodeToString(<<"b=w=====">>),
%% Test misc white space and illegals with embedded padding
"one" = MimeDecodeToString(<<" b~2=\r\n5()l===">>),
"on" = MimeDecodeToString(<<"\tb =2\"¤4=¤= ==">>),
"o" = MimeDecodeToString(<<"\nb=w=====">>),
Two pads
"Aladdin:open sesame" =
MimeDecodeToString(<<"QWxhZGRpbjpvc()GVuIHNlc2FtZQ==">>),
One pad to ignore , followed by more text
"Hello World!!" = MimeDecodeToString(<<"SGVsb)(G8gV29ybGQ=h IQ= =">>),
%% No pad
"Aladdin:open sesam" =
MimeDecodeToString(<<"QWxhZGRpbjpvcG¤\")(VuIHNlc2Ft">>),
Encoded base 64 strings may be divided by non base 64 chars .
%% In this cases whitespaces.
"0123456789!@#0^&*();:<>,. []{}" =
MimeDecodeToString(
<<"MDEy MzQ1Njc4 \tOSFAIzBeJ \nio)(oKTs6 PD4sLi \r\nBbXXt9">>),
Zeroes
"012" = MimeDecodeToString(<<"\000M\000D\000E\000y=\000">>),
"o" = MimeDecodeToString(<<"bw==\000">>),
"o" = MimeDecodeToString(<<"bw=\000=">>),
ok.
%%-------------------------------------------------------------------------
roundtrip_1(Config) when is_list(Config) ->
do_roundtrip(1).
roundtrip_2(Config) when is_list(Config) ->
do_roundtrip(2).
roundtrip_3(Config) when is_list(Config) ->
do_roundtrip(3).
roundtrip_4(Config) when is_list(Config) ->
do_roundtrip(4).
do_roundtrip(Offset) ->
Sizes = lists:seq(Offset, 255, 4) ++ lists:seq(2400-6+Offset, 2440, 4),
do_roundtrip_1(Sizes, []).
do_roundtrip_1([NextSize|Sizes], Current) ->
Len = length(Current),
io:format("~p", [Len]),
do_roundtrip_2(Current),
Next = random_byte_list(NextSize - Len, Current),
do_roundtrip_1(Sizes, Next);
do_roundtrip_1([], Last) ->
io:format("~p", [length(Last)]),
do_roundtrip_2(Last).
do_roundtrip_2(List) ->
Bin = list_to_binary(List),
Base64Bin = base64:encode(List),
Base64Bin = base64:encode(Bin),
Base64List = base64:encode_to_string(List),
Base64Bin = list_to_binary(Base64List),
Bin = base64:decode(Base64Bin),
List = base64:decode_to_string(Base64Bin),
Bin = base64:mime_decode(Base64Bin),
List = base64:mime_decode_to_string(Base64Bin),
append_roundtrip(8, Bin, List, Base64Bin),
prepend_roundtrip(8, Bin, List, Base64List),
interleaved_ws_roundtrip(Bin, List, Base64List).
append_roundtrip(0, _, _, _) -> ok;
append_roundtrip(N, Bin, List, Base64Bin0) ->
Base64Bin = <<Base64Bin0/binary,"\n">>,
Bin = base64:decode(Base64Bin),
List = base64:decode_to_string(Base64Bin),
Bin = base64:mime_decode(Base64Bin),
List = base64:mime_decode_to_string(Base64Bin),
Base64List = binary_to_list(Base64Bin),
Bin = base64:decode(Base64List),
List = base64:decode_to_string(Base64List),
Bin = base64:mime_decode(Base64List),
List = base64:mime_decode_to_string(Base64List),
append_roundtrip(N-1, Bin, List, Base64Bin).
prepend_roundtrip(0, _, _, _) -> ok;
prepend_roundtrip(N, Bin, List, Base64List0) ->
Base64List = [$\s|Base64List0],
Bin = base64:decode(Base64List),
List = base64:decode_to_string(Base64List),
Bin = base64:mime_decode(Base64List),
List = base64:mime_decode_to_string(Base64List),
Base64Bin = list_to_binary(Base64List),
Bin = base64:decode(Base64Bin),
List = base64:decode_to_string(Base64Bin),
Bin = base64:mime_decode(Base64Bin),
List = base64:mime_decode_to_string(Base64Bin),
prepend_roundtrip(N-1, Bin, List, Base64List).
%% Do an exhaustive test of interleaving whitespace (for short strings).
interleaved_ws_roundtrip(Bin, List, Base64List) when byte_size(Bin) =< 6 ->
interleaved_ws_roundtrip_1(lists:reverse(Base64List), [], Bin, List);
interleaved_ws_roundtrip(_, _, _) -> ok.
interleaved_ws_roundtrip_1([H|T], Tail, Bin, List) ->
interleaved_ws_roundtrip_1(T, [H|Tail], Bin, List),
interleaved_ws_roundtrip_1(T, [H,$\s|Tail], Bin, List),
interleaved_ws_roundtrip_1(T, [H,$\s,$\t|Tail], Bin, List),
interleaved_ws_roundtrip_1(T, [H,$\n,$\t|Tail], Bin, List);
interleaved_ws_roundtrip_1([], Base64List, Bin, List) ->
Bin = base64:decode(Base64List),
List = base64:decode_to_string(Base64List),
Bin = base64:mime_decode(Base64List),
List = base64:mime_decode_to_string(Base64List),
Base64Bin = list_to_binary(Base64List),
Bin = base64:decode(Base64Bin),
List = base64:decode_to_string(Base64Bin),
Bin = base64:mime_decode(Base64Bin),
List = base64:mime_decode_to_string(Base64Bin),
ok.
random_byte_list(0, Acc) ->
Acc;
random_byte_list(N, Acc) ->
random_byte_list(N-1, [rand:uniform(255)|Acc]).
make_big_binary(N) ->
list_to_binary(mbb(N, [])).
mbb(N, Acc) when N > 256 ->
B = list_to_binary(lists:seq(0, 255)),
mbb(N - 256, [B | Acc]);
mbb(N, Acc) ->
B = list_to_binary(lists:seq(0, N-1)),
lists:reverse(Acc, B).
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/stdlib/test/base64_SUITE.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
Test server specific exports
Test cases must be exported.
-------------------------------------------------------------------------
Test cases starts here.
-------------------------------------------------------------------------
valgrind needs a lot of time
-------------------------------------------------------------------------
Test base64:encode/1.
No pad
-------------------------------------------------------------------------
Test base64:decode/1.
No pad
In this cases whitespaces.
-------------------------------------------------------------------------
OTP-5635: Some data doesn't pass through base64:decode/1 correctly.
-------------------------------------------------------------------------
OTP-6279: Make sure illegal characters are rejected when decoding.
-------------------------------------------------------------------------
Encode and decode big binaries.
-------------------------------------------------------------------------
Make sure illegal characters are rejected when decoding.
A few samples with different error reasons. Nothing can be
assumed about the reason for the crash.
-------------------------------------------------------------------------
mime_decode and mime_decode_to_string have different implementations
so test both with the same input separately.
Test correct padding
Test misc embedded padding
Test misc white space and illegals with embedded padding
No pad
In this cases whitespaces.
-------------------------------------------------------------------------
Repeat of mime_decode() tests
Test base64:mime_decode_to_string/1.
Test correct padding
Test misc embedded padding
Test misc white space and illegals with embedded padding
No pad
In this cases whitespaces.
-------------------------------------------------------------------------
Do an exhaustive test of interleaving whitespace (for short strings). | Copyright Ericsson AB 2007 - 2017 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(base64_SUITE).
-include_lib("common_test/include/ct.hrl").
-export([all/0, suite/0, groups/0, group/1]).
-export([base64_encode/1, base64_decode/1, base64_otp_5635/1,
base64_otp_6279/1, big/1, illegal/1, mime_decode/1,
mime_decode_to_string/1,
roundtrip_1/1, roundtrip_2/1, roundtrip_3/1, roundtrip_4/1]).
suite() ->
[{ct_hooks,[ts_install_cth]},
{timetrap,{minutes,4}}].
all() ->
[base64_encode, base64_decode, base64_otp_5635,
base64_otp_6279, big, illegal, mime_decode, mime_decode_to_string,
{group, roundtrip}].
groups() ->
[{roundtrip, [parallel],
[roundtrip_1, roundtrip_2, roundtrip_3, roundtrip_4]}].
group(roundtrip) ->
[{timetrap,{minutes,10}}].
base64_encode(Config) when is_list(Config) ->
Two pads
<<"QWxhZGRpbjpvcGVuIHNlc2FtZQ==">> =
base64:encode("Aladdin:open sesame"),
One pad
<<"SGVsbG8gV29ybGQ=">> = base64:encode(<<"Hello World">>),
"QWxhZGRpbjpvcGVuIHNlc2Ft" =
base64:encode_to_string("Aladdin:open sesam"),
"MDEyMzQ1Njc4OSFAIzBeJiooKTs6PD4sLiBbXXt9" =
base64:encode_to_string(<<"0123456789!@#0^&*();:<>,. []{}">>),
ok.
base64_decode(Config) when is_list(Config) ->
Two pads
<<"Aladdin:open sesame">> =
base64:decode("QWxhZGRpbjpvcGVuIHNlc2FtZQ=="),
One pad
<<"Hello World">> = base64:decode(<<"SGVsbG8gV29ybGQ=">>),
<<"Aladdin:open sesam">> =
base64:decode("QWxhZGRpbjpvcGVuIHNlc2Ft"),
Alphabet = list_to_binary(lists:seq(0, 255)),
Alphabet = base64:decode(base64:encode(Alphabet)),
Encoded base 64 strings may be divided by non base 64 chars .
"0123456789!@#0^&*();:<>,. []{}" =
base64:decode_to_string(
"MDEy MzQ1Njc4 \tOSFAIzBeJ \niooKTs6 PD4sLi \r\nBbXXt9"),
"0123456789!@#0^&*();:<>,. []{}" =
base64:decode_to_string(
<<"MDEy MzQ1Njc4 \tOSFAIzBeJ \niooKTs6 PD4sLi \r\nBbXXt9">>),
ok.
base64_otp_5635(Config) when is_list(Config) ->
<<"===">> = base64:decode(base64:encode("===")),
ok.
base64_otp_6279(Config) when is_list(Config) ->
{'EXIT',_} = (catch base64:decode("dGVzda==a")),
ok.
big(Config) when is_list(Config) ->
Big = make_big_binary(300000),
B = base64:encode(Big),
true = is_binary(B),
400000 = byte_size(B),
Big = base64:decode(B),
Big = base64:mime_decode(B),
ok.
illegal(Config) when is_list(Config) ->
{'EXIT',_} = (catch base64:decode("()")),
{'EXIT',_} = (catch base64:decode(<<19:8,20:8,21:8,22:8>>)),
{'EXIT',_} = (catch base64:decode([19,20,21,22])),
{'EXIT',_} = (catch base64:decode_to_string(<<19:8,20:8,21:8,22:8>>)),
{'EXIT',_} = (catch base64:decode_to_string([19,20,21,22])),
ok.
Test base64 : .
mime_decode(Config) when is_list(Config) ->
MimeDecode = fun(In) ->
Out = base64:mime_decode(In),
Out = base64:mime_decode(binary_to_list(In))
end,
<<"one">> = MimeDecode(<<"b25l">>),
<<"on">> = MimeDecode(<<"b24=">>),
<<"o">> = MimeDecode(<<"bw==">>),
Test 1 extra padding
<<"one">> = MimeDecode(<<"b25l= =">>),
<<"on">> = MimeDecode(<<"b24== =">>),
<<"o">> = MimeDecode(<<"bw=== =">>),
Test 2 extra padding
<<"one">> = MimeDecode(<<"b25l===">>),
<<"on">> = MimeDecode(<<"b24====">>),
<<"o">> = MimeDecode(<<"bw=====">>),
<<"one">> = MimeDecode(<<"b2=5l===">>),
<<"on">> = MimeDecode(<<"b=24====">>),
<<"o">> = MimeDecode(<<"b=w=====">>),
<<"one">> = MimeDecode(<<" b~2=\r\n5()l===">>),
<<"on">> = MimeDecode(<<"\tb =2\"¤4=¤= ==">>),
<<"o">> = MimeDecode(<<"\nb=w=====">>),
Two pads
<<"Aladdin:open sesame">> =
MimeDecode(<<"QWxhZGRpbjpvc()GVuIHNlc2FtZQ==">>),
One pad to ignore , followed by more text
<<"Hello World!!">> = MimeDecode(<<"SGVsb)(G8gV29ybGQ=h IQ= =">>),
<<"Aladdin:open sesam">> =
MimeDecode(<<"QWxhZGRpbjpvcG¤\")(VuIHNlc2Ft">>),
Encoded base 64 strings may be divided by non base 64 chars .
<<"0123456789!@#0^&*();:<>,. []{}">> =
MimeDecode(
<<"MDEy MzQ1Njc4 \tOSFAIzBeJ \nio)(oKTs6 PD4sLi \r\nBbXXt9">>),
Zeroes
<<"012">> = MimeDecode(<<"\000M\000D\000E\000y=\000">>),
<<"o">> = MimeDecode(<<"bw==\000">>),
<<"o">> = MimeDecode(<<"bw=\000=">>),
ok.
mime_decode_to_string(Config) when is_list(Config) ->
MimeDecodeToString =
fun(In) ->
Out = base64:mime_decode_to_string(In),
Out = base64:mime_decode_to_string(binary_to_list(In))
end,
"one" = MimeDecodeToString(<<"b25l">>),
"on" = MimeDecodeToString(<<"b24=">>),
"o" = MimeDecodeToString(<<"bw==">>),
Test 1 extra padding
"one" = MimeDecodeToString(<<"b25l= =">>),
"on" = MimeDecodeToString(<<"b24== =">>),
"o" = MimeDecodeToString(<<"bw=== =">>),
Test 2 extra padding
"one" = MimeDecodeToString(<<"b25l===">>),
"on" = MimeDecodeToString(<<"b24====">>),
"o" = MimeDecodeToString(<<"bw=====">>),
"one" = MimeDecodeToString(<<"b2=5l===">>),
"on" = MimeDecodeToString(<<"b=24====">>),
"o" = MimeDecodeToString(<<"b=w=====">>),
"one" = MimeDecodeToString(<<" b~2=\r\n5()l===">>),
"on" = MimeDecodeToString(<<"\tb =2\"¤4=¤= ==">>),
"o" = MimeDecodeToString(<<"\nb=w=====">>),
Two pads
"Aladdin:open sesame" =
MimeDecodeToString(<<"QWxhZGRpbjpvc()GVuIHNlc2FtZQ==">>),
One pad to ignore , followed by more text
"Hello World!!" = MimeDecodeToString(<<"SGVsb)(G8gV29ybGQ=h IQ= =">>),
"Aladdin:open sesam" =
MimeDecodeToString(<<"QWxhZGRpbjpvcG¤\")(VuIHNlc2Ft">>),
Encoded base 64 strings may be divided by non base 64 chars .
"0123456789!@#0^&*();:<>,. []{}" =
MimeDecodeToString(
<<"MDEy MzQ1Njc4 \tOSFAIzBeJ \nio)(oKTs6 PD4sLi \r\nBbXXt9">>),
Zeroes
"012" = MimeDecodeToString(<<"\000M\000D\000E\000y=\000">>),
"o" = MimeDecodeToString(<<"bw==\000">>),
"o" = MimeDecodeToString(<<"bw=\000=">>),
ok.
roundtrip_1(Config) when is_list(Config) ->
do_roundtrip(1).
roundtrip_2(Config) when is_list(Config) ->
do_roundtrip(2).
roundtrip_3(Config) when is_list(Config) ->
do_roundtrip(3).
roundtrip_4(Config) when is_list(Config) ->
do_roundtrip(4).
do_roundtrip(Offset) ->
Sizes = lists:seq(Offset, 255, 4) ++ lists:seq(2400-6+Offset, 2440, 4),
do_roundtrip_1(Sizes, []).
do_roundtrip_1([NextSize|Sizes], Current) ->
Len = length(Current),
io:format("~p", [Len]),
do_roundtrip_2(Current),
Next = random_byte_list(NextSize - Len, Current),
do_roundtrip_1(Sizes, Next);
do_roundtrip_1([], Last) ->
io:format("~p", [length(Last)]),
do_roundtrip_2(Last).
do_roundtrip_2(List) ->
Bin = list_to_binary(List),
Base64Bin = base64:encode(List),
Base64Bin = base64:encode(Bin),
Base64List = base64:encode_to_string(List),
Base64Bin = list_to_binary(Base64List),
Bin = base64:decode(Base64Bin),
List = base64:decode_to_string(Base64Bin),
Bin = base64:mime_decode(Base64Bin),
List = base64:mime_decode_to_string(Base64Bin),
append_roundtrip(8, Bin, List, Base64Bin),
prepend_roundtrip(8, Bin, List, Base64List),
interleaved_ws_roundtrip(Bin, List, Base64List).
append_roundtrip(0, _, _, _) -> ok;
append_roundtrip(N, Bin, List, Base64Bin0) ->
Base64Bin = <<Base64Bin0/binary,"\n">>,
Bin = base64:decode(Base64Bin),
List = base64:decode_to_string(Base64Bin),
Bin = base64:mime_decode(Base64Bin),
List = base64:mime_decode_to_string(Base64Bin),
Base64List = binary_to_list(Base64Bin),
Bin = base64:decode(Base64List),
List = base64:decode_to_string(Base64List),
Bin = base64:mime_decode(Base64List),
List = base64:mime_decode_to_string(Base64List),
append_roundtrip(N-1, Bin, List, Base64Bin).
prepend_roundtrip(0, _, _, _) -> ok;
prepend_roundtrip(N, Bin, List, Base64List0) ->
Base64List = [$\s|Base64List0],
Bin = base64:decode(Base64List),
List = base64:decode_to_string(Base64List),
Bin = base64:mime_decode(Base64List),
List = base64:mime_decode_to_string(Base64List),
Base64Bin = list_to_binary(Base64List),
Bin = base64:decode(Base64Bin),
List = base64:decode_to_string(Base64Bin),
Bin = base64:mime_decode(Base64Bin),
List = base64:mime_decode_to_string(Base64Bin),
prepend_roundtrip(N-1, Bin, List, Base64List).
interleaved_ws_roundtrip(Bin, List, Base64List) when byte_size(Bin) =< 6 ->
interleaved_ws_roundtrip_1(lists:reverse(Base64List), [], Bin, List);
interleaved_ws_roundtrip(_, _, _) -> ok.
interleaved_ws_roundtrip_1([H|T], Tail, Bin, List) ->
interleaved_ws_roundtrip_1(T, [H|Tail], Bin, List),
interleaved_ws_roundtrip_1(T, [H,$\s|Tail], Bin, List),
interleaved_ws_roundtrip_1(T, [H,$\s,$\t|Tail], Bin, List),
interleaved_ws_roundtrip_1(T, [H,$\n,$\t|Tail], Bin, List);
interleaved_ws_roundtrip_1([], Base64List, Bin, List) ->
Bin = base64:decode(Base64List),
List = base64:decode_to_string(Base64List),
Bin = base64:mime_decode(Base64List),
List = base64:mime_decode_to_string(Base64List),
Base64Bin = list_to_binary(Base64List),
Bin = base64:decode(Base64Bin),
List = base64:decode_to_string(Base64Bin),
Bin = base64:mime_decode(Base64Bin),
List = base64:mime_decode_to_string(Base64Bin),
ok.
random_byte_list(0, Acc) ->
Acc;
random_byte_list(N, Acc) ->
random_byte_list(N-1, [rand:uniform(255)|Acc]).
make_big_binary(N) ->
list_to_binary(mbb(N, [])).
mbb(N, Acc) when N > 256 ->
B = list_to_binary(lists:seq(0, 255)),
mbb(N - 256, [B | Acc]);
mbb(N, Acc) ->
B = list_to_binary(lists:seq(0, N-1)),
lists:reverse(Acc, B).
|
4199d6bd3745feb87eeb189e7539bb629237ab2aaaff509a2693586172192de4 | input-output-hk/hydra | CardanoClient.hs | -- | A cardano-node client used in end-to-end tests and benchmarks.
--
-- This modules contains some more functions besides the re-exported basic
-- querying of hydra-node's 'Hydra.Chain.CardanoClient'.
module CardanoClient (
module Hydra.Chain.CardanoClient,
module CardanoClient,
) where
import Hydra.Prelude
import Hydra.Cardano.Api hiding (Block)
import Hydra.Chain.CardanoClient
import qualified Cardano.Api.UTxO as UTxO
import qualified Data.Map as Map
import qualified Hydra.Chain.CardanoClient as CardanoClient
TODO(SN ): DRY with Hydra . Cardano . Api
-- | Build an address give a key.
--
-- From <runAddressBuild -output-hk/cardano-node/blob/master/cardano-cli/src/Cardano/CLI/Shelley/Run/Address.hs#L106>
-- Throws 'CardanoClientException' if the query fails.
buildAddress :: VerificationKey PaymentKey -> NetworkId -> Address ShelleyAddr
buildAddress vKey networkId =
makeShelleyAddress networkId (PaymentCredentialByKey $ verificationKeyHash vKey) NoStakeAddress
buildScriptAddress :: Script -> NetworkId -> Address ShelleyAddr
buildScriptAddress script networkId =
let hashed = hashScript script
in makeShelleyAddress networkId (PaymentCredentialByScript hashed) NoStakeAddress
-- | Build a "raw" transaction from a bunch of inputs, outputs and fees.
buildRaw :: [TxIn] -> [TxOut CtxTx] -> Lovelace -> Either TxBodyError TxBody
buildRaw ins outs fee =
makeTransactionBody bodyContent
where
noProtocolParameters = Nothing
bodyContent =
TxBodyContent
(map (,BuildTxWith $ KeyWitness KeyWitnessForSpending) ins)
TxInsCollateralNone
TxInsReferenceNone
outs
TxTotalCollateralNone
TxReturnCollateralNone
(TxFeeExplicit fee)
(TxValidityNoLowerBound, TxValidityNoUpperBound)
TxMetadataNone
TxAuxScriptsNone
TxExtraKeyWitnessesNone
(BuildTxWith noProtocolParameters)
TxWithdrawalsNone
TxCertificatesNone
TxUpdateProposalNone
TxMintValueNone
TxScriptValidityNone
calculateMinFee :: NetworkId -> TxBody -> Sizes -> ProtocolParameters -> Lovelace
calculateMinFee networkId body Sizes{inputs, outputs, witnesses} pparams =
let tx = makeSignedTransaction [] body
noByronWitnesses = 0
in estimateTransactionFee
networkId
(protocolParamTxFeeFixed pparams)
(protocolParamTxFeePerByte pparams)
tx
inputs
outputs
noByronWitnesses
witnesses
data Sizes = Sizes
{ inputs :: Int
, outputs :: Int
, witnesses :: Int
}
deriving (Eq, Show)
defaultSizes :: Sizes
defaultSizes = Sizes{inputs = 0, outputs = 0, witnesses = 0}
-- | Sign a transaction body with given signing key.
sign :: SigningKey PaymentKey -> TxBody -> Tx
sign signingKey body =
makeSignedTransaction
[makeShelleyKeyWitness body (WitnessPaymentKey signingKey)]
body
waitForPayment ::
NetworkId ->
FilePath ->
Lovelace ->
Address ShelleyAddr ->
IO UTxO
waitForPayment networkId socket amount addr =
go
where
go = do
utxo <- queryUTxO networkId socket QueryTip [addr]
let expectedPayment = selectPayment utxo
if expectedPayment /= mempty
then pure $ UTxO expectedPayment
else threadDelay 1 >> go
selectPayment (UTxO utxo) =
Map.filter ((== amount) . selectLovelace . txOutValue) utxo
waitForUTxO ::
NetworkId ->
FilePath ->
UTxO ->
IO ()
waitForUTxO networkId nodeSocket utxo =
forM_ (snd <$> UTxO.pairs utxo) forEachUTxO
where
forEachUTxO :: TxOut CtxUTxO -> IO ()
forEachUTxO = \case
TxOut (ShelleyAddressInEra addr@ShelleyAddress{}) value _ _ -> do
void $
waitForPayment
networkId
nodeSocket
(selectLovelace value)
addr
txOut ->
error $ "Unexpected TxOut " <> show txOut
mkGenesisTx ::
NetworkId ->
ProtocolParameters ->
-- | Owner of the 'initialFund'.
SigningKey PaymentKey ->
-- | Amount of initialFunds
Lovelace ->
-- | Recipients and amounts to pay in this transaction.
[(VerificationKey PaymentKey, Lovelace)] ->
Tx
mkGenesisTx networkId pparams signingKey initialAmount recipients =
case buildRaw [initialInput] (recipientOutputs <> [changeOutput]) fee of
Left err -> error $ "Fail to build genesis transations: " <> show err
Right tx -> sign signingKey tx
where
initialInput =
genesisUTxOPseudoTxIn
networkId
(unsafeCastHash $ verificationKeyHash $ getVerificationKey signingKey)
fee = calculateMinFee networkId rawTx Sizes{inputs = 1, outputs = length recipients + 1, witnesses = 1} pparams
rawTx = case buildRaw [initialInput] [] 0 of
Left err -> error $ "Fail to build genesis transactions: " <> show err
Right tx -> tx
totalSent = foldMap snd recipients
changeAddr = mkVkAddress networkId (getVerificationKey signingKey)
changeOutput =
TxOut
changeAddr
(lovelaceToValue $ initialAmount - totalSent - fee)
TxOutDatumNone
ReferenceScriptNone
recipientOutputs =
flip map recipients $ \(vk, ll) ->
TxOut
(mkVkAddress networkId vk)
(lovelaceToValue ll)
TxOutDatumNone
ReferenceScriptNone
| null | https://raw.githubusercontent.com/input-output-hk/hydra/97a5650cd24b264837ddf7c0ea233ace7f7d55e0/hydra-cluster/src/CardanoClient.hs | haskell | | A cardano-node client used in end-to-end tests and benchmarks.
This modules contains some more functions besides the re-exported basic
querying of hydra-node's 'Hydra.Chain.CardanoClient'.
| Build an address give a key.
From <runAddressBuild -output-hk/cardano-node/blob/master/cardano-cli/src/Cardano/CLI/Shelley/Run/Address.hs#L106>
Throws 'CardanoClientException' if the query fails.
| Build a "raw" transaction from a bunch of inputs, outputs and fees.
| Sign a transaction body with given signing key.
| Owner of the 'initialFund'.
| Amount of initialFunds
| Recipients and amounts to pay in this transaction. | module CardanoClient (
module Hydra.Chain.CardanoClient,
module CardanoClient,
) where
import Hydra.Prelude
import Hydra.Cardano.Api hiding (Block)
import Hydra.Chain.CardanoClient
import qualified Cardano.Api.UTxO as UTxO
import qualified Data.Map as Map
import qualified Hydra.Chain.CardanoClient as CardanoClient
TODO(SN ): DRY with Hydra . Cardano . Api
buildAddress :: VerificationKey PaymentKey -> NetworkId -> Address ShelleyAddr
buildAddress vKey networkId =
makeShelleyAddress networkId (PaymentCredentialByKey $ verificationKeyHash vKey) NoStakeAddress
buildScriptAddress :: Script -> NetworkId -> Address ShelleyAddr
buildScriptAddress script networkId =
let hashed = hashScript script
in makeShelleyAddress networkId (PaymentCredentialByScript hashed) NoStakeAddress
buildRaw :: [TxIn] -> [TxOut CtxTx] -> Lovelace -> Either TxBodyError TxBody
buildRaw ins outs fee =
makeTransactionBody bodyContent
where
noProtocolParameters = Nothing
bodyContent =
TxBodyContent
(map (,BuildTxWith $ KeyWitness KeyWitnessForSpending) ins)
TxInsCollateralNone
TxInsReferenceNone
outs
TxTotalCollateralNone
TxReturnCollateralNone
(TxFeeExplicit fee)
(TxValidityNoLowerBound, TxValidityNoUpperBound)
TxMetadataNone
TxAuxScriptsNone
TxExtraKeyWitnessesNone
(BuildTxWith noProtocolParameters)
TxWithdrawalsNone
TxCertificatesNone
TxUpdateProposalNone
TxMintValueNone
TxScriptValidityNone
calculateMinFee :: NetworkId -> TxBody -> Sizes -> ProtocolParameters -> Lovelace
calculateMinFee networkId body Sizes{inputs, outputs, witnesses} pparams =
let tx = makeSignedTransaction [] body
noByronWitnesses = 0
in estimateTransactionFee
networkId
(protocolParamTxFeeFixed pparams)
(protocolParamTxFeePerByte pparams)
tx
inputs
outputs
noByronWitnesses
witnesses
data Sizes = Sizes
{ inputs :: Int
, outputs :: Int
, witnesses :: Int
}
deriving (Eq, Show)
defaultSizes :: Sizes
defaultSizes = Sizes{inputs = 0, outputs = 0, witnesses = 0}
sign :: SigningKey PaymentKey -> TxBody -> Tx
sign signingKey body =
makeSignedTransaction
[makeShelleyKeyWitness body (WitnessPaymentKey signingKey)]
body
waitForPayment ::
NetworkId ->
FilePath ->
Lovelace ->
Address ShelleyAddr ->
IO UTxO
waitForPayment networkId socket amount addr =
go
where
go = do
utxo <- queryUTxO networkId socket QueryTip [addr]
let expectedPayment = selectPayment utxo
if expectedPayment /= mempty
then pure $ UTxO expectedPayment
else threadDelay 1 >> go
selectPayment (UTxO utxo) =
Map.filter ((== amount) . selectLovelace . txOutValue) utxo
waitForUTxO ::
NetworkId ->
FilePath ->
UTxO ->
IO ()
waitForUTxO networkId nodeSocket utxo =
forM_ (snd <$> UTxO.pairs utxo) forEachUTxO
where
forEachUTxO :: TxOut CtxUTxO -> IO ()
forEachUTxO = \case
TxOut (ShelleyAddressInEra addr@ShelleyAddress{}) value _ _ -> do
void $
waitForPayment
networkId
nodeSocket
(selectLovelace value)
addr
txOut ->
error $ "Unexpected TxOut " <> show txOut
mkGenesisTx ::
NetworkId ->
ProtocolParameters ->
SigningKey PaymentKey ->
Lovelace ->
[(VerificationKey PaymentKey, Lovelace)] ->
Tx
mkGenesisTx networkId pparams signingKey initialAmount recipients =
case buildRaw [initialInput] (recipientOutputs <> [changeOutput]) fee of
Left err -> error $ "Fail to build genesis transations: " <> show err
Right tx -> sign signingKey tx
where
initialInput =
genesisUTxOPseudoTxIn
networkId
(unsafeCastHash $ verificationKeyHash $ getVerificationKey signingKey)
fee = calculateMinFee networkId rawTx Sizes{inputs = 1, outputs = length recipients + 1, witnesses = 1} pparams
rawTx = case buildRaw [initialInput] [] 0 of
Left err -> error $ "Fail to build genesis transactions: " <> show err
Right tx -> tx
totalSent = foldMap snd recipients
changeAddr = mkVkAddress networkId (getVerificationKey signingKey)
changeOutput =
TxOut
changeAddr
(lovelaceToValue $ initialAmount - totalSent - fee)
TxOutDatumNone
ReferenceScriptNone
recipientOutputs =
flip map recipients $ \(vk, ll) ->
TxOut
(mkVkAddress networkId vk)
(lovelaceToValue ll)
TxOutDatumNone
ReferenceScriptNone
|
50ebbb9f99c2deff7dc3ca29c7ed0a976426ab4cc8671b023ea7ab515014f23b | phoe/wordnet | representation.lisp | CommonLisp interface to WordNet
1995 ,
Artificial Intelligence Laboratory
Massachusetts Institute of Technology
Representation of WordNet data . Uses the lower layers defined in
;;; "wordnet-database-files" and "parse-wordnet-data" to extract data from the
WordNet database files and then constructs an object oriented
;;; representation.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Representation
(in-package #:wordnet)
(defclass wordnet-object () ())
(defclass wordnet-index-entry (wordnet-object)
((word :initarg :word :reader index-entry-word)
(part-of-speech :initarg :part-of-speech
:reader part-of-speech)
(synset-offsets :initarg :synset-offsets
:reader index-entry-synset-offsets)))
(defmethod print-object ((object wordnet-index-entry) stream)
(print-unreadable-object (object stream :type t :identity t)
(format stream "~a ~a"
(ignore-errors (part-of-speech object))
(ignore-errors (index-entry-word object)))))
(defclass wordnet-synset-entry (wordnet-object)
((part-of-speech :initarg :part-of-speech :reader part-of-speech)
(offset :initarg :offset :reader synset-offset)
(words :initarg :words :initform nil :reader synset-words)
(raw-pointers :initarg :pointers :initform nil)
(pointers)
(gloss :initarg :gloss :initform nil :reader synset-gloss)))
(defmethod print-object ((object wordnet-synset-entry) stream)
(print-unreadable-object (object stream :type t :identity t)
(dolist (w (ignore-errors (synset-words object)))
(format stream "~a " (car w)))))
(defclass wordnet-noun-entry (wordnet-synset-entry) ())
(defclass wordnet-adjective-entry (wordnet-synset-entry) ())
(defclass wordnet-adverb-entry (wordnet-synset-entry) ())
(defclass wordnet-verb-entry (wordnet-synset-entry)
((verb-frames :initarg :verb-frames :initform nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; constructing the objects
;;; The objects we've made are kept in a cache so that if we ever get a request
;;; for the same object again, we can fetch the existing one rather than read
the WordNet files again and make a new one .
(defvar *wordnet-index-cache*
(mapcar #'(lambda (pos) (list pos (make-hash-table :test #+Genera 'string=
#-Genera 'equal)))
(parts-of-speech)))
(defvar *wordnet-synset-cache*
(mapcar #'(lambda (pos)
(list pos (make-hash-table :test 'equal)))
(parts-of-speech)))
(defun cached-index-lookup (word part-of-speech)
"Looks up the entries for word (a string or a symbol) for the specified
part-of-speech."
(let* ((table (second (assoc part-of-speech *wordnet-index-cache*)))
(index-cache-entry (gethash word table)))
(unless index-cache-entry
(multiple-value-bind (word part-of-speech poly_cnt pointer-types synset-offsets)
(parse-index-file-entry
(index-entry-for-word part-of-speech word))
(declare (ignore poly_cnt pointer-types))
(when word
(setq index-cache-entry (make-instance 'wordnet-index-entry
:word word
:part-of-speech part-of-speech
:synset-offsets synset-offsets))
(setf (gethash word table) index-cache-entry))))
index-cache-entry))
(defun cached-data-lookup (synset-index part-of-speech)
(let* ((table (second (assoc part-of-speech *wordnet-synset-cache*)))
(synset-entry (gethash synset-index table)))
(unless synset-entry
(multiple-value-bind (part-of-speech words pointers gloss verb-frames)
(parse-data-file-entry (read-data-file-entry part-of-speech synset-index))
(setq synset-entry
(apply #'make-instance
(ecase part-of-speech
(:noun 'wordnet-noun-entry)
(:verb 'wordnet-verb-entry)
(:adjective 'wordnet-adjective-entry)
(:adverb 'wordnet-adverb-entry))
:offset synset-index
:part-of-speech part-of-speech
:words words
:pointers pointers
:gloss gloss
(when (eq part-of-speech :verb)
(list :verb-frames verb-frames)))))
(setf (gethash synset-index table) synset-entry))
synset-entry))
(defun index-entry-synsets (index-entry)
(when index-entry
(mapcar #'(lambda (offset)
(cached-data-lookup offset (part-of-speech index-entry)))
(index-entry-synset-offsets index-entry))))
(defun morphology-exception-lookup (word part-of-speech)
(parse-exception-file-entry (exception-entry-for-word part-of-speech word)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Relationships among words and synsets
I do n't have a good idea about what the best way to represent WordNet
;;; pointers is. Let's try this.
(defclass wordnet-pointer (wordnet-object)
((type :initarg :type
:reader wordnet-pointer-type)
(from-synset :initarg :from
:reader wordnet-pointer-from-synset)
(from-word-index :initarg :from-index
:reader wordnet-pointer-from-synset-index)
(to-synset :initarg :to
:reader wordnet-pointer-to-synset)
(to-word-index :initarg :to-index
:reader wordnet-pointer-to-synset-index)))
(defmethod print-object ((object wordnet-pointer) stream)
(print-unreadable-object (object stream :type t :identity t)
(format stream "~a" (ignore-errors (wordnet-pointer-type object)))))
(defmethod transitive-relation-p ((pointer wordnet-pointer))
(transitive-relation-p (wordnet-pointer-type pointer)))
(defmethod relation-direction ((pointer wordnet-pointer))
(relation-direction (wordnet-pointer-type pointer)))
(defmethod wordnet-pointer-from-word ((pointer wordnet-pointer))
(with-slots (from-synset from-word-index) pointer
(if (zerop from-word-index)
from-synset
(elt (synset-words from-synset) (1- from-word-index)))))
(defmethod wordnet-pointer-to-word ((pointer wordnet-pointer))
(with-slots (to-synset to-word-index) pointer
(if (zerop to-word-index)
to-synset
(elt (synset-words to-synset) (1- to-word-index)))))
(defmethod reify-pointers ((synset wordnet-synset-entry))
(with-slots (raw-pointers pointers) synset
(let ((new-pointers nil))
(dolist (p raw-pointers)
(destructuring-bind (pointer-type target part-of-speech
source-index target-index) p
(let ((to-synset (cached-data-lookup target part-of-speech)))
(unless to-synset
(error "Pointer ~s has invalid target" p))
(push (make-instance 'wordnet-pointer
:type pointer-type
:from synset
:from-index source-index
:to to-synset
:to-index target-index)
new-pointers))))
(setq pointers (nreverse new-pointers)))))
(defmethod wordnet-pointers ((synset wordnet-synset-entry))
(unless (slot-boundp synset 'pointers)
(reify-pointers synset))
(slot-value synset 'pointers))
(defmacro do-synset-pointers ((pointer-var synset &optional (pointer-types nil pt?))
&body body)
(assert (symbolp pointer-var))
`(dolist (,pointer-var (wordnet-pointers ,synset))
(when ,@(if pt?
`((member (wordnet-pointer-type ,pointer-var)
,pointer-types))
t)
,@body)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; fancy printing
(defun pretty-print-synset (stream synset &key (word-index 0) gloss word-sense-tags)
(flet ((call-with-text-face (stream face function)
#+Genera
(typecase stream
(clim-internals::output-protocol-mixin
(clim:with-text-face (stream face)
(funcall function stream)))
(t (scl:with-character-face (face stream)
(funcall function stream))))
#-Genera
(funcall function stream))
(print-pos (stream)
(write-string
(ecase (part-of-speech synset)
(:noun "n") (:verb "v") (:adjective "adj") (:adverb "adv"))
stream))
(print-word+sense (word+sense stream)
(if word-sense-tags
(write-string (first word+sense) stream)
(format stream "~a:~d" (first word+sense) (second word+sense)))))
(call-with-text-face stream :italic #'print-pos)
(write-char #\{ stream)
(do* ((words (synset-words synset) (cdr words))
(word+sense (car words) (car words))
(index 1 (1+ index)))
((null words))
(if (= index word-index)
(call-with-text-face stream :bold
#'(lambda (stream)
(print-word+sense word+sense stream)))
(print-word+sense word+sense stream))
(unless (null words)
(write-char #\space stream)))
(when gloss
(let ((gloss (synset-gloss synset)))
(when gloss
(format stream " | ~a" gloss))))
(write-char #\} stream))
synset)
| null | https://raw.githubusercontent.com/phoe/wordnet/e8434f3f5113967dc1868aabaf8fd1fbf0cd8533/representation.lisp | lisp | "wordnet-database-files" and "parse-wordnet-data" to extract data from the
representation.
Representation
constructing the objects
The objects we've made are kept in a cache so that if we ever get a request
for the same object again, we can fetch the existing one rather than read
Relationships among words and synsets
pointers is. Let's try this.
fancy printing | CommonLisp interface to WordNet
1995 ,
Artificial Intelligence Laboratory
Massachusetts Institute of Technology
Representation of WordNet data . Uses the lower layers defined in
WordNet database files and then constructs an object oriented
(in-package #:wordnet)
(defclass wordnet-object () ())
(defclass wordnet-index-entry (wordnet-object)
((word :initarg :word :reader index-entry-word)
(part-of-speech :initarg :part-of-speech
:reader part-of-speech)
(synset-offsets :initarg :synset-offsets
:reader index-entry-synset-offsets)))
(defmethod print-object ((object wordnet-index-entry) stream)
(print-unreadable-object (object stream :type t :identity t)
(format stream "~a ~a"
(ignore-errors (part-of-speech object))
(ignore-errors (index-entry-word object)))))
(defclass wordnet-synset-entry (wordnet-object)
((part-of-speech :initarg :part-of-speech :reader part-of-speech)
(offset :initarg :offset :reader synset-offset)
(words :initarg :words :initform nil :reader synset-words)
(raw-pointers :initarg :pointers :initform nil)
(pointers)
(gloss :initarg :gloss :initform nil :reader synset-gloss)))
(defmethod print-object ((object wordnet-synset-entry) stream)
(print-unreadable-object (object stream :type t :identity t)
(dolist (w (ignore-errors (synset-words object)))
(format stream "~a " (car w)))))
(defclass wordnet-noun-entry (wordnet-synset-entry) ())
(defclass wordnet-adjective-entry (wordnet-synset-entry) ())
(defclass wordnet-adverb-entry (wordnet-synset-entry) ())
(defclass wordnet-verb-entry (wordnet-synset-entry)
((verb-frames :initarg :verb-frames :initform nil)))
the WordNet files again and make a new one .
(defvar *wordnet-index-cache*
(mapcar #'(lambda (pos) (list pos (make-hash-table :test #+Genera 'string=
#-Genera 'equal)))
(parts-of-speech)))
(defvar *wordnet-synset-cache*
(mapcar #'(lambda (pos)
(list pos (make-hash-table :test 'equal)))
(parts-of-speech)))
(defun cached-index-lookup (word part-of-speech)
"Looks up the entries for word (a string or a symbol) for the specified
part-of-speech."
(let* ((table (second (assoc part-of-speech *wordnet-index-cache*)))
(index-cache-entry (gethash word table)))
(unless index-cache-entry
(multiple-value-bind (word part-of-speech poly_cnt pointer-types synset-offsets)
(parse-index-file-entry
(index-entry-for-word part-of-speech word))
(declare (ignore poly_cnt pointer-types))
(when word
(setq index-cache-entry (make-instance 'wordnet-index-entry
:word word
:part-of-speech part-of-speech
:synset-offsets synset-offsets))
(setf (gethash word table) index-cache-entry))))
index-cache-entry))
(defun cached-data-lookup (synset-index part-of-speech)
(let* ((table (second (assoc part-of-speech *wordnet-synset-cache*)))
(synset-entry (gethash synset-index table)))
(unless synset-entry
(multiple-value-bind (part-of-speech words pointers gloss verb-frames)
(parse-data-file-entry (read-data-file-entry part-of-speech synset-index))
(setq synset-entry
(apply #'make-instance
(ecase part-of-speech
(:noun 'wordnet-noun-entry)
(:verb 'wordnet-verb-entry)
(:adjective 'wordnet-adjective-entry)
(:adverb 'wordnet-adverb-entry))
:offset synset-index
:part-of-speech part-of-speech
:words words
:pointers pointers
:gloss gloss
(when (eq part-of-speech :verb)
(list :verb-frames verb-frames)))))
(setf (gethash synset-index table) synset-entry))
synset-entry))
(defun index-entry-synsets (index-entry)
(when index-entry
(mapcar #'(lambda (offset)
(cached-data-lookup offset (part-of-speech index-entry)))
(index-entry-synset-offsets index-entry))))
(defun morphology-exception-lookup (word part-of-speech)
(parse-exception-file-entry (exception-entry-for-word part-of-speech word)))
I do n't have a good idea about what the best way to represent WordNet
(defclass wordnet-pointer (wordnet-object)
((type :initarg :type
:reader wordnet-pointer-type)
(from-synset :initarg :from
:reader wordnet-pointer-from-synset)
(from-word-index :initarg :from-index
:reader wordnet-pointer-from-synset-index)
(to-synset :initarg :to
:reader wordnet-pointer-to-synset)
(to-word-index :initarg :to-index
:reader wordnet-pointer-to-synset-index)))
(defmethod print-object ((object wordnet-pointer) stream)
(print-unreadable-object (object stream :type t :identity t)
(format stream "~a" (ignore-errors (wordnet-pointer-type object)))))
(defmethod transitive-relation-p ((pointer wordnet-pointer))
(transitive-relation-p (wordnet-pointer-type pointer)))
(defmethod relation-direction ((pointer wordnet-pointer))
(relation-direction (wordnet-pointer-type pointer)))
(defmethod wordnet-pointer-from-word ((pointer wordnet-pointer))
(with-slots (from-synset from-word-index) pointer
(if (zerop from-word-index)
from-synset
(elt (synset-words from-synset) (1- from-word-index)))))
(defmethod wordnet-pointer-to-word ((pointer wordnet-pointer))
(with-slots (to-synset to-word-index) pointer
(if (zerop to-word-index)
to-synset
(elt (synset-words to-synset) (1- to-word-index)))))
(defmethod reify-pointers ((synset wordnet-synset-entry))
(with-slots (raw-pointers pointers) synset
(let ((new-pointers nil))
(dolist (p raw-pointers)
(destructuring-bind (pointer-type target part-of-speech
source-index target-index) p
(let ((to-synset (cached-data-lookup target part-of-speech)))
(unless to-synset
(error "Pointer ~s has invalid target" p))
(push (make-instance 'wordnet-pointer
:type pointer-type
:from synset
:from-index source-index
:to to-synset
:to-index target-index)
new-pointers))))
(setq pointers (nreverse new-pointers)))))
(defmethod wordnet-pointers ((synset wordnet-synset-entry))
(unless (slot-boundp synset 'pointers)
(reify-pointers synset))
(slot-value synset 'pointers))
(defmacro do-synset-pointers ((pointer-var synset &optional (pointer-types nil pt?))
&body body)
(assert (symbolp pointer-var))
`(dolist (,pointer-var (wordnet-pointers ,synset))
(when ,@(if pt?
`((member (wordnet-pointer-type ,pointer-var)
,pointer-types))
t)
,@body)))
(defun pretty-print-synset (stream synset &key (word-index 0) gloss word-sense-tags)
(flet ((call-with-text-face (stream face function)
#+Genera
(typecase stream
(clim-internals::output-protocol-mixin
(clim:with-text-face (stream face)
(funcall function stream)))
(t (scl:with-character-face (face stream)
(funcall function stream))))
#-Genera
(funcall function stream))
(print-pos (stream)
(write-string
(ecase (part-of-speech synset)
(:noun "n") (:verb "v") (:adjective "adj") (:adverb "adv"))
stream))
(print-word+sense (word+sense stream)
(if word-sense-tags
(write-string (first word+sense) stream)
(format stream "~a:~d" (first word+sense) (second word+sense)))))
(call-with-text-face stream :italic #'print-pos)
(write-char #\{ stream)
(do* ((words (synset-words synset) (cdr words))
(word+sense (car words) (car words))
(index 1 (1+ index)))
((null words))
(if (= index word-index)
(call-with-text-face stream :bold
#'(lambda (stream)
(print-word+sense word+sense stream)))
(print-word+sense word+sense stream))
(unless (null words)
(write-char #\space stream)))
(when gloss
(let ((gloss (synset-gloss synset)))
(when gloss
(format stream " | ~a" gloss))))
(write-char #\} stream))
synset)
|
1a97c6bf2884dede5549b7b876d0e27921897747712cad68da4c210506ce522c | GaloisInc/jvm-parser | Parser.hs | |
Module : Language . JVM.Parser
Copyright : Galois , Inc. 2012 - 2014
License : :
Stability : stable
Portability : portable
for the JVM bytecode format .
Module : Language.JVM.Parser
Copyright : Galois, Inc. 2012-2014
License : BSD3
Maintainer :
Stability : stable
Portability : portable
Parser for the JVM bytecode format.
-}
# LANGUAGE LambdaCase #
module Language.JVM.Parser (
-- * Class declarations
Class
, className
, superClass
, classIsPublic
, classIsFinal
, classIsInterface
, classIsAbstract
, classHasSuperAttribute
, classInterfaces
, classFields
, classMethods
, classAttributes
, loadClass
, lookupMethod
, showClass
, getClass
-- * Field declarations
, Field
, Visibility(..)
, Attribute(..)
, fieldName
, fieldType
, fieldVisibility
, fieldIsStatic
, fieldIsFinal
, fieldIsVolatile
, fieldIsTransient
, fieldConstantValue
, fieldIsSynthetic
, fieldIsDeprecated
, fieldIsEnum
, fieldSignature
, fieldAttributes
-- * Method declarations
, Method
, methodName
, methodParameterTypes
, methodParameterIndexes
, localIndexOfParameter
, methodReturnType
, methodMaxLocals
, methodIsNative
, methodIsAbstract
, methodBody
, MethodBody(..)
, methodExceptionTable
, methodKey
, methodIsStatic
, MethodKey(..)
, makeMethodKey
-- ** Instruction declarations
, LocalVariableIndex
, LocalVariableTableEntry(..)
, PC
, lookupInstruction
, nextPc
-- ** Exception table declarations
, ExceptionTableEntry
, catchType
, startPc
, endPc
, handlerPc
-- ** Misc utility functions/values
, byteArrayTy
, charArrayTy
, getElemTy
, intArrayTy
, stringTy
, unparseMethodDescriptor
, mainKey
-- * Debugging information
, hasDebugInfo
, classSourceFile
, sourceLineNumberInfo
, sourceLineNumberOrPrev
, lookupLineStartPC
, lookupLineMethodStartPC
, localVariableEntries
, lookupLocalVariableByIdx
, lookupLocalVariableByName
, ppInst
, slashesToDots
, cfgToDot
-- * Re-exports
-- ** Types
, Type(..)
, isIValue
, isPrimitiveType
, stackWidth
, isFloatType
, isRefType
-- ** Instructions
, FieldId(..)
, Instruction(..)
-- ** Class names
, ClassName
, mkClassName
, unClassName
, ConstantPoolValue(..)
) where
import Control.Exception (assert)
import Control.Monad
import Data.Array (Array, (!), listArray)
import Data.Binary
import Data.Binary.Get
import Data.Bits (Bits(..))
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import Data.Char
import Data.Int
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import Prelude hiding(read)
import System.IO
import Language.JVM.CFG
import Language.JVM.Common
-- | Indicate parse failure with the given error message. Note that
-- failure in the 'Get' monad already tracks the number of bytes
-- consumed, so it is not necessary to include position information in
-- the error message.
failure :: String -> Get a
failure msg = fail msg
-- | Run an inner parser on a bytestring, passing along any failures.
subParser :: Get a -> L.ByteString -> Get a
subParser g l =
case runGetOrFail g l of
Left (_, pos, msg) ->
failure ("Sub-parser failed at position " ++ show pos ++ ": " ++ msg)
Right (_, _, x) ->
pure x
-- Version of replicate with arguments convoluted for parser.
replicateN :: (Integral b, Monad m) => m a -> b -> m [a]
replicateN fn i = sequence (replicate (fromIntegral i) fn)
showOnNewLines :: Int -> [String] -> String
showOnNewLines n [] = replicate n ' ' ++ "None"
showOnNewLines n [a] = replicate n ' ' ++ a
showOnNewLines n (a : rest) = replicate n ' ' ++ a ++ "\n" ++ showOnNewLines n rest
----------------------------------------------------------------------
-- Type
parseTypeDescriptor :: String -> Maybe (Type, String)
parseTypeDescriptor str =
case str of
('B' : rest) -> Just (ByteType, rest)
('C' : rest) -> Just (CharType, rest)
('D' : rest) -> Just (DoubleType, rest)
('F' : rest) -> Just (FloatType, rest)
('I' : rest) -> Just (IntType, rest)
('J' : rest) -> Just (LongType, rest)
('S' : rest) -> Just (ShortType, rest)
('Z' : rest) -> Just (BooleanType, rest)
('L' : rest) -> split rest []
('[' : rest) ->
do (tp, result) <- parseTypeDescriptor rest
Just (ArrayType tp, result)
_ -> Nothing
where
split (';' : rest') result = Just (ClassType (mkClassName (reverse result)), rest')
split (ch : rest') result = split rest' (ch : result)
split _ _ = Nothing
----------------------------------------------------------------------
-- Visibility
-- | Visibility of a field.
data Visibility = Default | Private | Protected | Public
deriving Eq
instance Show Visibility where
show Default = "default"
show Private = "private"
show Protected = "protected"
show Public = "public"
----------------------------------------------------------------------
-- Method descriptors
parseMethodDescriptor :: String -> Maybe (Maybe Type, [Type])
parseMethodDescriptor str =
case str of
('(' : rest) -> impl rest []
_ -> Nothing
where
impl ")V" types = Just (Nothing, reverse types)
impl (')' : rest') types =
case parseTypeDescriptor rest' of
Just (tp, "") -> Just (Just tp, reverse types)
_ -> Nothing
impl text types =
do (tp, rest') <- parseTypeDescriptor text
impl rest' (tp : types)
unparseMethodDescriptor :: MethodKey -> String
unparseMethodDescriptor (MethodKey _ paramTys retTy) =
"(" ++ concatMap tyToDesc paramTys ++ ")" ++ maybe "V" tyToDesc retTy
where
tyToDesc (ArrayType ty) = "[" ++ tyToDesc ty
tyToDesc BooleanType = "Z"
tyToDesc ByteType = "B"
tyToDesc CharType = "C"
tyToDesc (ClassType cn) = "L" ++ unClassName cn ++ ";"
tyToDesc DoubleType = "D"
tyToDesc FloatType = "F"
tyToDesc IntType = "I"
tyToDesc LongType = "J"
tyToDesc ShortType = "S"
-- | Returns method key with the given name and descriptor.
makeMethodKey :: String -- ^ Method name
-> String -- ^ Method descriptor
-> MethodKey
makeMethodKey name descriptor = MethodKey name parameters returnType
where (returnType, parameters) =
fromMaybe (error "Invalid method descriptor") $ parseMethodDescriptor descriptor
mainKey :: MethodKey
mainKey = makeMethodKey "main" "([Ljava/lang/String;)V"
----------------------------------------------------------------------
ConstantPool
data ConstantPoolInfo
= ConstantClass Word16
| FieldRef Word16 Word16
| MethodRef Word16 Word16
| InterfaceMethodRef Word16 Word16
| ConstantString Word16
| ConstantInteger Int32
| ConstantFloat Float
| ConstantLong Int64
| ConstantDouble Double
| NameAndType Word16 Word16
| Utf8 String
| MethodHandle Word8 Word16
| MethodType Word16
| InvokeDynamic Word16 Word16
-- | Used for gaps after Long and double entries
| Phantom
deriving (Show)
| Parse a string from a list of bytes , according to section 4.4.7
of the JVM spec : " String content is encoded in modified UTF-8 .
-- Modified UTF-8 strings are encoded so that code point sequences
-- that contain only non-null ASCII characters can be represented
using only 1 byte per code point , but all code points in the
-- Unicode codespace can be represented."
--
" There are two differences between this format and the " standard "
UTF-8 format . First , the null character ( char)0 is encoded using
the 2 - byte format rather than the 1 - byte format , so that modified
UTF-8 strings never have embedded nulls . Second , only the 1 - byte ,
2 - byte , and 3 - byte formats of standard UTF-8 are used . The Java
Virtual Machine does not recognize the four - byte format of standard
UTF-8 ; it uses its own two - times - three - byte format instead . "
parseJavaString :: [Word8] -> Maybe String
parseJavaString [] = Just []
parseJavaString (x : rest)
| (x .&. 0x80) == 0 = (:) (chr (fromIntegral x)) <$> parseJavaString rest
parseJavaString (x : y : rest)
| (x .&. 0xE0) == 0xC0 && ((y .&. 0xC0) == 0x80)
= (:) (chr i) <$> parseJavaString rest
where i = (fromIntegral x .&. 0x1F) `shift` 6 + (fromIntegral y .&. 0x3F)
parseJavaString (x : y : z : rest)
| (x .&. 0xF0) == 0xE0 && ((y .&. 0xC0) == 0x80) && ((z .&. 0xC0) == 0x80)
= (:) (chr i) <$> parseJavaString rest
where i = ((fromIntegral x .&. 0x0F) `shift` 12
+ (fromIntegral y .&. 0x3F) `shift` 6
+ (fromIntegral z .&. 0x3F))
parseJavaString _ = Nothing
getConstantPoolInfo :: Get [ConstantPoolInfo]
getConstantPoolInfo = do
tag <- getWord8
case tag of
CONSTANT_Utf8
1 -> do bytes <- replicateN getWord8 =<< getWord16be
case parseJavaString bytes of
Nothing -> failure "unable to parse byte array for Java string"
Just s -> return [Utf8 s]
---- CONSTANT_Integer
3 -> do val <- get
return [ConstantInteger val]
---- CONSTANT_Float
4 -> do v <- getFloatbe
return [ConstantFloat v]
5 -> do val <- get
return [Phantom, ConstantLong val]
---- CONSTANT_Double
6 -> do val <- getDoublebe
return [Phantom, ConstantDouble val]
-- CONSTANT_Class
7 -> do index <- getWord16be
return [ConstantClass index]
-- CONSTANT_String
8 -> do index <- getWord16be
return [ConstantString index]
-- CONSTANT_Fieldref
9 -> do classIndex <- getWord16be
nameTypeIndex <- getWord16be
return [FieldRef classIndex nameTypeIndex]
-- CONSTANT_Methodref
10 -> do classIndex <- getWord16be
nameTypeIndex <- getWord16be
return [MethodRef classIndex nameTypeIndex]
-- CONSTANT_InterfaceMethodref
11 -> do classIndex <- getWord16be
nameTypeIndex <- getWord16be
return [InterfaceMethodRef classIndex nameTypeIndex]
---- CONSTANT_NameAndType
12 -> do classIndex <- getWord16be
nameTypeIndex <- getWord16be
return [NameAndType classIndex nameTypeIndex]
---- CONSTANT_MethodHandle_info
15 -> do referenceKind <- getWord8
referenceIndex <- getWord16be
return [MethodHandle referenceKind referenceIndex]
--
16 -> do descriptorIndex <- getWord16be
return [MethodType descriptorIndex]
---- CONSTANT_InvokeDynamic_info
18 -> do bootstrapMethodIndex <- getWord16be
nameTypeIndex <- getWord16be
return [InvokeDynamic bootstrapMethodIndex nameTypeIndex]
_ -> do failure ("Unexpected constant " ++ show tag)
type ConstantPoolIndex = Word16
type ConstantPool = Array ConstantPoolIndex ConstantPoolInfo
Get monad that extract ConstantPool from input .
getConstantPool :: Get ConstantPool
getConstantPool = do
poolCount <- getWord16be
list <- parseList (poolCount - 1) []
return $ listArray (1, poolCount - 1) list
where parseList 0 result = return $ reverse result
parseList n result = do
info <- getConstantPoolInfo
parseList (n - fromIntegral (length info)) (info ++ result)
-- | Return the string at the given index in the constant pool, or
fail if the constant pool index is not a UTF-8 string .
poolUtf8 :: ConstantPool -> ConstantPoolIndex -> Get String
poolUtf8 cp i =
case cp ! i of
Utf8 s -> pure s
v -> failure $ "Index " ++ show i ++ " has value " ++ show v ++ " when string expected."
-- | Returns value at given index in constant pool or raises error
-- if constant pool index is not a value.
poolValue :: ConstantPool -> ConstantPoolIndex -> Get ConstantPoolValue
poolValue cp i =
case cp ! i of
ConstantClass j -> ClassRef . mkClassName <$> poolUtf8 cp j
ConstantDouble v -> pure $ Double v
ConstantFloat v -> pure $ Float v
ConstantInteger v -> pure $ Integer v
ConstantLong v -> pure $ Long v
ConstantString j -> String <$> poolUtf8 cp j
v -> failure ("Index " ++ show i ++ " has unexpected value " ++ show v
++ " when a constant was expected.")
parseType :: String -> Get Type
parseType s =
case parseTypeDescriptor s of
Just (tp, []) -> pure tp
_ -> failure ("Invalid type descriptor: " ++ show s)
| For instructions that are described in the JVM spec like this :
-- "The run-time constant pool item at the index must be a symbolic
-- reference to a class, array, or interface type."
poolClassType :: ConstantPool -> ConstantPoolIndex -> Get Type
poolClassType cp i =
case cp ! i of
ConstantClass j ->
do typeName <- poolUtf8 cp j
if head typeName == '['
then parseType typeName
else pure $ ClassType (mkClassName typeName)
_ ->
failure ("Index " ++ show i ++ " is not a class reference.")
poolClassName :: ConstantPool -> ConstantPoolIndex -> Get ClassName
poolClassName cp i =
case cp ! i of
ConstantClass j ->
do typeName <- poolUtf8 cp j
when (head typeName == '[') $
failure ("Index " ++ show i ++ " is an array type and not a class.")
pure $ mkClassName typeName
_ ->
failure ("Index " ++ show i ++ " is not a class reference.")
poolNameAndType :: ConstantPool -> ConstantPoolIndex -> Get (String, String)
poolNameAndType cp i =
case cp ! i of
NameAndType nameIndex typeIndex ->
(,) <$> poolUtf8 cp nameIndex <*> poolUtf8 cp typeIndex
_ -> failure ("Index " ++ show i ++ " is not a name and type reference.")
-- | Returns tuple containing field class, name, and type at given index.
poolFieldRef :: ConstantPool -> ConstantPoolIndex -> Get FieldId
poolFieldRef cp i =
case cp ! i of
FieldRef classIndex ntIndex ->
do (name, descriptor) <- poolNameAndType cp ntIndex
fldType <- parseType descriptor
cName <- poolClassName cp classIndex
pure $ FieldId cName name fldType
_ -> failure ("Index " ++ show i ++ " is not a field reference.")
poolInterfaceMethodRef :: ConstantPool -> ConstantPoolIndex -> Get (Type, MethodKey)
poolInterfaceMethodRef cp i =
case cp ! i of
InterfaceMethodRef classIndex ntIndex ->
poolTypeAndMethodKey cp classIndex ntIndex
_ -> failure ("Index " ++ show i ++ " is not an interface method reference.")
poolMethodRef :: ConstantPool -> ConstantPoolIndex -> Get (Type, MethodKey)
poolMethodRef cp i =
case cp ! i of
MethodRef classIndex ntIndex ->
poolTypeAndMethodKey cp classIndex ntIndex
_ -> failure ("Index " ++ show i ++ " is not a method reference.")
poolMethodOrInterfaceRef :: ConstantPool -> ConstantPoolIndex -> Get (Type, MethodKey)
poolMethodOrInterfaceRef cp i =
case cp ! i of
MethodRef classIndex ntIndex ->
poolTypeAndMethodKey cp classIndex ntIndex
InterfaceMethodRef classIndex ntIndex ->
poolTypeAndMethodKey cp classIndex ntIndex
_ -> failure ("Index " ++ show i ++ " is not a method or interface method reference.")
poolTypeAndMethodKey :: ConstantPool -> ConstantPoolIndex -> ConstantPoolIndex -> Get (Type, MethodKey)
poolTypeAndMethodKey cp classIndex ntIndex =
do (name, fieldDescriptor) <- poolNameAndType cp ntIndex
classType <- poolClassType cp classIndex
pure (classType, makeMethodKey name fieldDescriptor)
_uncurry3 :: (a -> b -> c -> d) -> (a,b,c) -> d
_uncurry3 fn (a,b,c) = fn a b c
( getInstruction cp addr ) returns a parser for the instruction
-- at the address addr.
getInstruction :: ConstantPool -> PC -> Get Instruction
getInstruction cp address = do
op <- getWord8
case op of
0x00 -> return Nop
0x01 -> return Aconst_null
0x02 -> return $ Ldc $ Integer (-1)
0x03 -> return $ Ldc $ Integer 0
0x04 -> return $ Ldc $ Integer 1
0x05 -> return $ Ldc $ Integer 2
0x06 -> return $ Ldc $ Integer 3
0x07 -> return $ Ldc $ Integer 4
0x08 -> return $ Ldc $ Integer 5
0x09 -> return $ Ldc $ Long 0
0x0A -> return $ Ldc $ Long 1
0x0B -> return $ Ldc $ Float 0.0
0x0C -> return $ Ldc $ Float 1.0
0x0D -> return $ Ldc $ Float 2.0
0x0E -> return $ Ldc $ Double 0.0
0x0F -> return $ Ldc $ Double 1.0
0x10 -> liftM (Ldc . Integer . fromIntegral) getInt8
0x11 -> liftM (Ldc . Integer . fromIntegral) getInt16be
0x12 -> liftM Ldc $ poolValue cp =<< liftM fromIntegral getWord8
0x13 -> liftM Ldc $ poolValue cp =<< getWord16be
0x14 -> liftM Ldc $ poolValue cp =<< getWord16be
0x15 -> liftM (Iload . fromIntegral) getWord8
0x16 -> liftM (Lload . fromIntegral) getWord8
0x17 -> liftM (Fload . fromIntegral) getWord8
0x18 -> liftM (Dload . fromIntegral) getWord8
0x19 -> liftM (Aload . fromIntegral) getWord8
0x1A -> return (Iload 0)
0x1B -> return (Iload 1)
0x1C -> return (Iload 2)
0x1D -> return (Iload 3)
0x1E -> return (Lload 0)
0x1F -> return (Lload 1)
0x20 -> return (Lload 2)
0x21 -> return (Lload 3)
0x22 -> return (Fload 0)
0x23 -> return (Fload 1)
0x24 -> return (Fload 2)
0x25 -> return (Fload 3)
0x26 -> return (Dload 0)
0x27 -> return (Dload 1)
0x28 -> return (Dload 2)
0x29 -> return (Dload 3)
0x2A -> return (Aload 0)
0x2B -> return (Aload 1)
0x2C -> return (Aload 2)
0x2D -> return (Aload 3)
0x2E -> return Iaload
0x2F -> return Laload
0x30 -> return Faload
0x31 -> return Daload
0x32 -> return Aaload
0x33 -> return Baload
0x34 -> return Caload
0x35 -> return Saload
0x36 -> liftM (Istore . fromIntegral) getWord8
0x37 -> liftM (Lstore . fromIntegral) getWord8
0x38 -> liftM (Fstore . fromIntegral) getWord8
0x39 -> liftM (Dstore . fromIntegral) getWord8
0x3A -> liftM (Astore . fromIntegral) getWord8
0x3B -> return (Istore 0)
0x3C -> return (Istore 1)
0x3D -> return (Istore 2)
0x3E -> return (Istore 3)
0x3F -> return (Lstore 0)
0x40 -> return (Lstore 1)
0x41 -> return (Lstore 2)
0x42 -> return (Lstore 3)
0x43 -> return (Fstore 0)
0x44 -> return (Fstore 1)
0x45 -> return (Fstore 2)
0x46 -> return (Fstore 3)
0x47 -> return (Dstore 0)
0x48 -> return (Dstore 1)
0x49 -> return (Dstore 2)
0x4A -> return (Dstore 3)
0x4B -> return (Astore 0)
0x4C -> return (Astore 1)
0x4D -> return (Astore 2)
0x4E -> return (Astore 3)
0x4F -> return Iastore
0x50 -> return Lastore
0x51 -> return Fastore
0x52 -> return Dastore
0x53 -> return Aastore
0x54 -> return Bastore
0x55 -> return Castore
0x56 -> return Sastore
0x57 -> return Pop
0x58 -> return Pop2
0x59 -> return Dup
0x5A -> return Dup_x1
0x5B -> return Dup_x2
0x5C -> return Dup2
0x5D -> return Dup2_x1
0x5E -> return Dup2_x2
0x5F -> return Swap
0x60 -> return Iadd
0x61 -> return Ladd
0x62 -> return Fadd
0x63 -> return Dadd
0x64 -> return Isub
0x65 -> return Lsub
0x66 -> return Fsub
0x67 -> return Dsub
0x68 -> return Imul
0x69 -> return Lmul
0x6A -> return Fmul
0x6B -> return Dmul
0x6C -> return Idiv
0x6D -> return Ldiv
0x6E -> return Fdiv
0x6F -> return Ddiv
0x70 -> return Irem
0x71 -> return Lrem
0x72 -> return Frem
0x73 -> return Drem
0x74 -> return Ineg
0x75 -> return Lneg
0x76 -> return Fneg
0x77 -> return Dneg
0x78 -> return Ishl
0x79 -> return Lshl
0x7A -> return Ishr
0x7B -> return Lshr
0x7C -> return Iushr
0x7D -> return Lushr
0x7E -> return Iand
0x7F -> return Land
0x80 -> return Ior
0x81 -> return Lor
0x82 -> return Ixor
0x83 -> return Lxor
0x84 -> do
index <- getWord8
constant <- getInt8
return (Iinc (fromIntegral index) (fromIntegral constant))
0x85 -> return I2l
0x86 -> return I2f
0x87 -> return I2d
0x88 -> return L2i
0x89 -> return L2f
0x8A -> return L2d
0x8B -> return F2i
0x8C -> return F2l
0x8D -> return F2d
0x8E -> return D2i
0x8F -> return D2l
0x90 -> return D2f
0x91 -> return I2b
0x92 -> return I2c
0x93 -> return I2s
0x94 -> return Lcmp
0x95 -> return Fcmpl
0x96 -> return Fcmpg
0x97 -> return Dcmpl
0x98 -> return Dcmpg
0x99 -> return . Ifeq . (address +) . fromIntegral =<< getInt16be
0x9A -> return . Ifne . (address +) . fromIntegral =<< getInt16be
0x9B -> return . Iflt . (address +) . fromIntegral =<< getInt16be
0x9C -> return . Ifge . (address +) . fromIntegral =<< getInt16be
0x9D -> return . Ifgt . (address +) . fromIntegral =<< getInt16be
0x9E -> return . Ifle . (address +) . fromIntegral =<< getInt16be
0x9F -> return . If_icmpeq . (address +) . fromIntegral =<< getInt16be
0xA0 -> return . If_icmpne . (address +) . fromIntegral =<< getInt16be
0xA1 -> return . If_icmplt . (address +) . fromIntegral =<< getInt16be
0xA2 -> return . If_icmpge . (address +) . fromIntegral =<< getInt16be
0xA3 -> return . If_icmpgt . (address +) . fromIntegral =<< getInt16be
0xA4 -> return . If_icmple . (address +) . fromIntegral =<< getInt16be
0xA5 -> return . If_acmpeq . (address +) . fromIntegral =<< getInt16be
0xA6 -> return . If_acmpne . (address +) . fromIntegral =<< getInt16be
0xA7 -> return . Goto . (address +) . fromIntegral =<< getInt16be
0xA8 -> return . Jsr . (address +) . fromIntegral =<< getInt16be
0xA9 -> liftM (Ret . fromIntegral) getWord8
0xAA -> do
read <- bytesRead
skip $ fromIntegral $ (4 - read `mod` 4) `mod` 4
defaultBranch <- return . (address +) . fromIntegral =<< getInt32be
low <- getInt32be
high <- getInt32be
offsets <- replicateN
(return . (address +) . fromIntegral =<< getInt32be)
(high - low + 1)
return $ Tableswitch defaultBranch low high offsets
0xAB -> do
read <- bytesRead
skip (fromIntegral ((4 - read `mod` 4) `mod` 4))
defaultBranch <- getInt32be
count <- getInt32be
pairs <- replicateM (fromIntegral count) $ do
v <- getInt32be
o <- getInt32be
return (v, ((address +) . fromIntegral) o)
return $ Lookupswitch (address + fromIntegral defaultBranch) pairs
0xAC -> return Ireturn
0xAD -> return Lreturn
0xAE -> return Freturn
0xAF -> return Dreturn
0xB0 -> return Areturn
0xB1 -> return Return
0xB2 -> Getstatic <$> (poolFieldRef cp =<< getWord16be)
0xB3 -> Putstatic <$> (poolFieldRef cp =<< getWord16be)
0xB4 -> Getfield <$> (poolFieldRef cp =<< getWord16be)
0xB5 -> Putfield <$> (poolFieldRef cp =<< getWord16be)
0xB6 -> do index <- getWord16be
(classType, key) <- poolMethodRef cp index
return $ Invokevirtual classType key
0xB7 -> do index <- getWord16be
(classType, key) <- poolMethodOrInterfaceRef cp index
return $ Invokespecial classType key
0xB8 -> do index <- getWord16be
(classType, key) <- poolMethodOrInterfaceRef cp index
cName <-
case classType of
ClassType cName -> pure cName
_ -> failure ("invokestatic: expected class type, found " ++ show classType)
pure $ Invokestatic cName key
0xB9 -> do index <- getWord16be
_ <- getWord8
_ <- getWord8
(classType, key) <- poolInterfaceMethodRef cp index
cName <-
case classType of
ClassType cName -> pure cName
_ -> failure ("invokeinterface: expected class type, found " ++ show classType)
pure $ Invokeinterface cName key
0xBA -> do index <- getWord16be
_ <- getWord8
_ <- getWord8
return $ Invokedynamic index
0xBB -> New <$> (poolClassName cp =<< getWord16be)
0xBC -> do typeCode <- getWord8
elementType <-
case typeCode of
4 -> pure BooleanType
5 -> pure CharType
6 -> pure FloatType
7 -> pure DoubleType
8 -> pure ByteType
9 -> pure ShortType
10 -> pure IntType
11 -> pure LongType
_ -> failure "internal: invalid type code encountered"
pure $ Newarray (ArrayType elementType)
0xBD -> Newarray . ArrayType <$> (poolClassType cp =<< getWord16be)
0xBE -> return Arraylength
0xBF -> return Athrow
0xC0 -> Checkcast <$> (poolClassType cp =<< getWord16be)
0xC1 -> Instanceof <$> (poolClassType cp =<< getWord16be)
0xC2 -> return Monitorenter
0xC3 -> return Monitorexit
-- Wide instruction
0xC4 -> do
embeddedOp <- getWord8
case embeddedOp of
0x15 -> liftM Iload getWord16be
0x16 -> liftM Lload getWord16be
0x17 -> liftM Fload getWord16be
0x18 -> liftM Dload getWord16be
0x19 -> liftM Aload getWord16be
0x36 -> liftM Istore getWord16be
0x37 -> liftM Lstore getWord16be
0x38 -> liftM Fstore getWord16be
0x39 -> liftM Dstore getWord16be
0x3A -> liftM Astore getWord16be
0x84 -> liftM2 Iinc getWord16be getInt16be
0xA9 -> liftM Ret getWord16be
_ -> do
position <- bytesRead
failure ("Unexpected wide op " ++ (show op) ++ " at position " ++ show (position - 2))
0xC5 -> Multianewarray <$> (poolClassType cp =<< getWord16be) <*> getWord8
0xC6 -> return . Ifnull . (address +) . fromIntegral =<< getInt16be
0xC7 -> return . Ifnonnull . (address +) . fromIntegral =<< getInt16be
0xC8 -> return . Goto . (address +) . fromIntegral =<< getInt32be
0xC9 -> return . Jsr . (address +) . fromIntegral =<< getInt32be
_ -> do
position <- bytesRead
failure ("Unexpected op " ++ (show op) ++ " at position " ++ show (position - 1))
----------------------------------------------------------------------
-- Attributes
-- | An uninterpreted user-defined attribute in the class file.
data Attribute = Attribute {
attributeName :: String
, attributeData :: B.ByteString
} deriving (Eq,Show)
-- Returns getter that parses attributes from stream and buckets them based on name.
splitAttributes :: ConstantPool -> [String] -> Get ([[L.ByteString]], [Attribute])
splitAttributes cp names = do
count <- getWord16be
impl count (replicate (length names) []) []
( appendAt list - of - lists index ) adds to front of list at
-- index i in list-of-lists
appendAt (l : rest) 0 a = (l ++ [a]) : rest
appendAt (first : rest) n a = first : appendAt rest (n - 1) a
appendAt [] _ _ = error "internal: appendAt expects non-empty list"
Parse values
impl 0 values rest = return (values, reverse rest)
impl n values rest = do
nameIndex <- getWord16be
len <- getWord32be
name <- poolUtf8 cp nameIndex
case elemIndex name names of
Just i ->
do bytes <- getLazyByteString (fromIntegral len)
impl (n - 1) (appendAt values i bytes) rest
Nothing ->
do bytes <- getByteString (fromIntegral len)
impl (n - 1) values (Attribute name bytes : rest)
----------------------------------------------------------------------
Field declarations
-- | A field of a class.
data Field = Field {
-- | Returns name of field.
fieldName :: String
-- | Returns type of field.
, fieldType :: Type
-- | Returns visibility of field.
, fieldVisibility :: Visibility
-- | Returns true if field is static.
, fieldIsStatic :: Bool
-- | Returns true if field is final.
, fieldIsFinal :: Bool
-- | Returns true if field is volatile.
, fieldIsVolatile :: Bool
-- | Returns true if field is transient.
, fieldIsTransient :: Bool
-- | Returns initial value of field or 'Nothing' if not assigned.
--
-- Only static fields may have a constant value.
, fieldConstantValue :: Maybe ConstantPoolValue
-- | Returns true if field is synthetic.
, fieldIsSynthetic :: Bool
-- | Returns true if field is deprecated.
, fieldIsDeprecated :: Bool
-- | Returns true if field is transient.
, fieldIsEnum :: Bool
, fieldSignature :: Maybe String
, fieldAttributes :: [Attribute]
} deriving (Show)
instance Show Field where
show ( Field ( FieldKey name tp )
-- visibility
-- isStatic
isFinal
-- isVolatile
-- isTransient
-- constantValue
-- isSynthetic
-- isDeprecated
-- isEnum
-- signature
-- attrs)
-- = show visibility ++ " "
-- ++ (if isStatic then "static " else "")
+ + ( if isFinal then " final " else " " )
-- ++ (if isVolatile then "volatile " else "")
-- ++ (if isTransient then "transient " else "")
-- ++ show tp ++ " "
-- ++ name
-- ++ case constantValue of
-- Nothing -> ""
-- Just (Long l) -> " = " ++ show l ++ " "
-- Just (Float f) -> " = " ++ show f ++ " "
-- Just (Double d) -> " = " ++ show d ++ " "
-- Just (Integer i) -> " = " ++ show i ++ " "
-- Just (String s) -> " = " ++ show s ++ " "
-- ++ (if isSynthetic then " synthetic " else "")
-- ++ (if isDeprecated then " deprecated " else "")
+ + show attrs
getField :: ConstantPool -> Get Field
getField cp = do
accessFlags <- getWord16be
name <- poolUtf8 cp =<< getWord16be
fldType <- parseType =<< poolUtf8 cp =<< getWord16be
([constantValue, synthetic, deprecated, signature], userAttrs)
<- splitAttributes cp ["ConstantValue", "Synthetic", "Deprecated", "Signature"]
constantVal <-
case constantValue of
[bytes] -> Just <$> (poolValue cp =<< subParser getWord16be bytes)
[] -> pure Nothing
_ -> failure "internal: unexpected constant value form"
sig <-
case signature of
[bytes] -> Just <$> (poolUtf8 cp =<< subParser getWord16be bytes)
[] -> pure Nothing
_ -> failure "internal: unexpected signature form"
visibility <-
case accessFlags .&. 0x7 of
0x0 -> pure Default
0x1 -> pure Public
0x2 -> pure Private
0x4 -> pure Protected
flags -> failure $ "Unexpected flags " ++ show flags
return $ Field name
fldType
-- Visibility
visibility
-- Static
((accessFlags .&. 0x0008) /= 0)
-- Final
((accessFlags .&. 0x0010) /= 0)
-- Volatile
((accessFlags .&. 0x0040) /= 0)
-- Transient
((accessFlags .&. 0x0080) /= 0)
-- Constant Value
constantVal
-- Check for synthetic bit in flags and buffer
((accessFlags .&. 0x1000) /= 0 || (not (null synthetic)))
-- Deprecated flag
(not (null deprecated))
-- Check for enum bit in flags
((accessFlags .&. 0x4000) /= 0)
Signature
sig
userAttrs
----------------------------------------------------------------------
-- Exception table
getExceptionTableEntry :: ConstantPool -> Get ExceptionTableEntry
getExceptionTableEntry cp = do
startPc' <- getWord16be
endPc' <- getWord16be
handlerPc' <- getWord16be
catchIndex <- getWord16be
catchType' <-
if catchIndex == 0
then pure Nothing
else Just <$> poolClassType cp catchIndex
return (ExceptionTableEntry startPc'
endPc'
handlerPc'
catchType')
-- Run Get Monad until end of string is reached and return list of results.
getInstructions :: ConstantPool -> PC -> Get InstructionStream
getInstructions cp count = do
read <- bytesRead
impl 0 read []
where impl pos prevRead result = do
if pos == (fromIntegral count)
then return (listArray (0, count - 1) (reverse result))
else do
inst <- getInstruction cp pos
newRead <- bytesRead
let dist = fromIntegral (newRead - prevRead)
padding = replicate (fromIntegral (dist - 1)) Nothing
in impl (pos + dist) newRead (padding ++ (Just inst : result))
-- Returns valid program counters in ascending order.
getValidPcs : : InstructionStream - > [ PC ]
getValidPcs = map fst . filter ( isJust . snd ) . assocs
where isJust Nothing = False
isJust _ = True
getValidPcs :: InstructionStream -> [PC]
getValidPcs = map fst . filter (isJust . snd) . assocs
where isJust Nothing = False
isJust _ = True
-}
----------------------------------------------------------------------
LineNumberTable
data LineNumberTable = LNT {
pcLineMap :: Map PC Word16
, linePCMap :: Map Word16 PC
} deriving (Eq,Show)
getLineNumberTableEntries :: Get [(PC, Word16)]
getLineNumberTableEntries = do
tableLength <- getWord16be
replicateM (fromIntegral tableLength)
(do startPc' <- getWord16be
lineNumber <- getWord16be
return (startPc', lineNumber))
parseLineNumberTable :: [L.ByteString] -> Get LineNumberTable
parseLineNumberTable buffers =
do l <- concat <$> traverse (subParser getLineNumberTableEntries) buffers
pure LNT { pcLineMap = Map.fromList l
, linePCMap = Map.fromListWith min [ (ln,pc) | (pc,ln) <- l ]
}
----------------------------------------------------------------------
-- LocalVariableTableEntry
data LocalVariableTableEntry
= LocalVariableTableEntry
{ localStart :: PC -- Start PC
, localExtent :: PC -- length
, localName :: String -- Name
, localType :: Type -- Type of local variable
, localIdx :: LocalVariableIndex -- Index of local variable
}
deriving (Eq,Show)
-- Maps pc and local variable index to name and type of variable in source.
type LocalVariableTable = [LocalVariableTableEntry]
getLocalVariableTableEntries :: ConstantPool -> Get [LocalVariableTableEntry]
getLocalVariableTableEntries cp = do
tableLength <- getWord16be
replicateM (fromIntegral tableLength)
(do startPc' <- getWord16be
len <- getWord16be
name <- getWord16be >>= poolUtf8 cp
ty <- getWord16be >>= poolUtf8 cp >>= parseType
index <- getWord16be
pure $ LocalVariableTableEntry startPc' len name ty index)
parseLocalVariableTable :: ConstantPool -> [L.ByteString] -> Get [LocalVariableTableEntry]
parseLocalVariableTable cp buffers =
concat <$> traverse (subParser (getLocalVariableTableEntries cp)) buffers
----------------------------------------------------------------------
-- Method body
data MethodBody
= Code Word16 -- maxStack
Word16 -- maxLocals
CFG
[ExceptionTableEntry] -- exception table
LineNumberTable -- Line number table entries (empty if information not provided)
LocalVariableTable -- Local variable table entries (optional)
[Attribute] -- Code attributes
| AbstractMethod
| NativeMethod
deriving (Eq,Show)
getCode :: ConstantPool -> Get MethodBody
getCode cp = do
maxStack <- getWord16be
maxLocals <- getWord16be
codeLength <- getWord32be
instructions <- getInstructions cp (fromIntegral codeLength)
exceptionTable <- getWord16be >>= replicateN (getExceptionTableEntry cp)
([lineNumberTables, localVariableTables], userAttrs)
<- splitAttributes cp ["LineNumberTable", "LocalVariableTable"]
lnt <- parseLineNumberTable lineNumberTables
lvt <- parseLocalVariableTable cp localVariableTables
return $ Code maxStack
maxLocals
(buildCFG exceptionTable instructions)
exceptionTable
lnt
lvt
userAttrs
----------------------------------------------------------------------
-- Method definitions
data Method = Method {
methodKey :: MethodKey
, _visibility :: Visibility
, methodIsStatic :: Bool
, _methodIsFinal :: Bool
, _isSynchronized :: Bool
, _isStrictFp :: Bool
, methodBody :: MethodBody
, _exceptions :: Maybe [Type]
, _isSynthetic :: Bool
, _isDeprecated :: Bool
, _attributes :: [Attribute]
} deriving (Eq,Show)
instance Ord Method where
compare m1 m2 = compare (methodKey m1) (methodKey m2)
-- instance Show Method where
show ( Method ( MethodKey name )
-- visibility
-- isStatic
isFinal
-- isSynchronized
-- isStrictFp
-- body
-- exceptions
-- isSynthetic
-- isDeprecated
attrs )
-- = show visibility ++ " "
-- ++ (if isStatic then "static" else "")
+ + ( if isFinal then " final " else " " )
-- ++ (if isSynchronized then "synchronized " else "")
-- ++ (case body of
-- AbstractMethod -> "abstract "
NativeMethod - > " native "
-- _ -> "")
-- ++ (if isStrictFp then "strict " else "")
-- ++ case returnType of
-- Just tp -> (show tp)
-- Nothing -> "void"
-- ++ " " ++ name
-- ++ "(" ++ showCommaSeparatedList parameterTypes ++ ")"
-- ++ show attrs ++ "\n"
-- ++ (if isSynthetic then " synthetic\n" else "")
-- ++ (if isDeprecated then " deprecated\n" else "")
-- ++ case body of
Code maxStack maxLocals is exceptions lineNumbers _ codeAttrs - >
" Max Stack : " + + show
+ + " Max Locals : " + + show maxLocals + + " \n "
+ + ( showOnNewLines 4
-- [ show i ++ ": " ++ show inst
-- ++ (case Map.lookup i lineNumbers of
-- Just l -> "(line " ++ show l ++ ")"
-- Nothing -> "")
-- | (i, Just inst) <- assocs is ])
-- ++ if null exceptions
-- then ""
-- else "\n Exceptions: " ++ show exceptions
+ + if null codeAttrs
-- then ""
else " \n Attributes : " + + show codeAttrs
-- _ -> ""
getExceptions :: ConstantPool -> Get [Type]
getExceptions cp = do
exceptionCount <- getWord16be
replicateN (getWord16be >>= poolClassType cp) exceptionCount
getMethod :: ConstantPool -> Get Method
getMethod cp = do
accessFlags <- getWord16be
name <- getWord16be >>= poolUtf8 cp
descriptor <- getWord16be >>= poolUtf8 cp
(returnType, parameterTypes) <-
maybe (failure "Invalid method descriptor") pure $ parseMethodDescriptor descriptor
([codeVal, exceptionsVal, syntheticVal, deprecatedVal], userAttrs)
<- splitAttributes cp ["Code", "Exceptions", "Synthetic", "Deprecated"]
visibility <-
case accessFlags .&. 0x7 of
0x0 -> pure Default
0x1 -> pure Public
0x2 -> pure Private
0x4 -> pure Protected
flags -> failure $ "Unexpected flags " ++ show flags
let isStatic' = (accessFlags .&. 0x008) /= 0
isFinal = (accessFlags .&. 0x010) /= 0
isSynchronized' = (accessFlags .&. 0x020) /= 0
isAbstract = (accessFlags .&. 0x400) /= 0
isStrictFp' = (accessFlags .&. 0x800) /= 0
body <-
if ((accessFlags .&. 0x100) /= 0) then pure NativeMethod else
if isAbstract then pure AbstractMethod else
case codeVal of
[bytes] -> subParser (getCode cp) bytes
_ -> failure "Could not find code attribute"
exceptions <-
case exceptionsVal of
[bytes] -> Just <$> subParser (getExceptions cp) bytes
[] -> pure Nothing
_ -> failure "internal: unexpected expectionsVal form"
return $
Method (MethodKey name parameterTypes returnType)
visibility
isStatic'
isFinal
isSynchronized'
isStrictFp'
body
exceptions
(not $ null syntheticVal)
(not $ null deprecatedVal)
userAttrs
methodIsNative :: Method -> Bool
methodIsNative m =
case methodBody m of
NativeMethod -> True
_ -> False
-- | Returns true if method is abstract.
methodIsAbstract :: Method -> Bool
methodIsAbstract m =
case methodBody m of
AbstractMethod -> True
_ -> False
-- | Returns the name of a method.
methodName :: Method -> String
methodName = methodKeyName . methodKey
-- | Returns parameter types for method.
methodParameterTypes :: Method -> [Type]
methodParameterTypes = methodKeyParameterTypes . methodKey
-- | Returns a list containing the local variable index that each
-- parameter is stored in when the method is invoked. Non-static
methods reserve index 0 for the @self@ parameter .
methodParameterIndexes :: Method -> [LocalVariableIndex]
methodParameterIndexes m = init $ scanl next start params
where
params = methodParameterTypes m
start = if methodIsStatic m then 0 else 1
next n DoubleType = n + 2
next n LongType = n + 2
next n _ = n + 1
-- | Returns the local variable index that the parameter is stored in when
-- the method is invoked.
localIndexOfParameter :: Method -> Int -> LocalVariableIndex
localIndexOfParameter m i = assert (0 <= i && i < length offsets) $ offsets !! i
where offsets = methodParameterIndexes m
-- | Return type of the method, or 'Nothing' for a void return type.
methodReturnType :: Method -> Maybe Type
methodReturnType = methodKeyReturnType . methodKey
-- (lookupInstruction method pc) returns instruction at pc in method.
lookupInstruction :: Method -> PC -> Instruction
lookupInstruction method pc =
case methodBody method of
Code _ _ cfg _ _ _ _ ->
case (cfgInstByPC cfg pc) of
Just i -> i
Nothing -> error "internal: failed to index inst stream"
_ -> error ("Method " ++ show method ++ " has no body")
-- Returns pc of next instruction.
nextPc :: Method -> PC -> PC
nextPc method pc =
-- trace ("nextPC: method = " ++ show method) $
case methodBody method of
Code _ _ cfg _ _ _ _ ->
-- nextPcPrim (toInstStream cfg) pc
case nextPC cfg pc of
Nothing -> error "JavaParser.nextPc: no next instruction"
Just npc -> npc
_ -> error "internal: unexpected method body form"
-- | Returns maximum number of local variables in method.
methodMaxLocals :: Method -> LocalVariableIndex
methodMaxLocals method =
case methodBody method of
Code _ c _ _ _ _ _ -> c
_ -> error "internal: unexpected method body form"
-- | Returns true if method has debug informaiton available.
hasDebugInfo :: Method -> Bool
hasDebugInfo method =
case methodBody method of
Code _ _ _ _ lns lvars _ -> not (Map.null (pcLineMap lns) && null lvars)
_ -> False
methodLineNumberTable :: Method -> Maybe LineNumberTable
methodLineNumberTable me = do
case methodBody me of
Code _ _ _ _ lns _ _ -> Just lns
_ -> Nothing
sourceLineNumberInfo :: Method -> [(Word16,PC)]
sourceLineNumberInfo me =
maybe [] (Map.toList . pcLineMap) $ methodLineNumberTable me
-- | Returns source line number of an instruction in a method at a given PC,
-- or the line number of the nearest predecessor instruction, or 'Nothing' if
-- neither is available.
sourceLineNumberOrPrev :: Method -> PC -> Maybe Word16
sourceLineNumberOrPrev me pc =
case methodBody me of
Code _ _ _ _ lns _ _ ->
case Map.splitLookup pc (pcLineMap lns) of
(prs, Nothing, _)
| not $ Map.null prs -> Just $ snd $ Map.findMax prs
| otherwise -> Nothing
(_, ln, _) -> ln
_ -> error "internal: unexpected method body form"
-- | Returns the starting PC for the source at the given line number.
lookupLineStartPC :: Method -> Word16 -> Maybe PC
lookupLineStartPC me ln = do
m <- methodLineNumberTable me
Map.lookup ln (linePCMap m)
-- | Returns the enclosing method and starting PC for the source at the given line number.
lookupLineMethodStartPC :: Class -> Word16 -> Maybe (Method, PC)
lookupLineMethodStartPC cl ln =
case results of
(p:_) -> return p
[] -> mzero
where results = do
me <- Map.elems . classMethodMap $ cl
case lookupLineStartPC me ln of
Just pc -> return (me, pc)
Nothing -> mzero
localVariableEntries :: Method -> PC -> [LocalVariableTableEntry]
localVariableEntries method pc =
case methodBody method of
Code _ _ _ _ _ lvars _ ->
let matches e = localStart e <= pc &&
pc - localStart e <= localExtent e
in filter matches lvars
_ -> []
-- | Returns local variable entry at given PC and local variable index or
-- 'Nothing' if no mapping is found.
lookupLocalVariableByIdx :: Method -> PC -> LocalVariableIndex
-> Maybe LocalVariableTableEntry
lookupLocalVariableByIdx method pc i =
find (\e -> localIdx e == i) (localVariableEntries method pc)
-- | Returns local variable entry at given PC and local variable string or
-- 'Nothing' if no mapping is found.
lookupLocalVariableByName :: Method -> PC -> String -> Maybe LocalVariableTableEntry
lookupLocalVariableByName method pc name =
find (\e -> localName e == name) (localVariableEntries method pc)
-- | Exception table entries for method.
methodExceptionTable :: Method -> [ExceptionTableEntry]
methodExceptionTable method =
case methodBody method of
Code _ _ _ table _ _ _ -> table
_ -> error "internal: unexpected method body form"
----------------------------------------------------------------------
-- Class declarations
-- | A JVM class or interface.
data Class = MkClass {
majorVersion :: Word16
, minorVersion :: Word16
, constantPool :: ConstantPool
-- | Returns true if the class is public.
, classIsPublic :: Bool
-- | Returns true if the class is final.
, classIsFinal :: Bool
-- | Returns true if the class was annotated with the @super@ attribute.
, classHasSuperAttribute :: Bool
-- | Returns true if the class is an interface.
, classIsInterface :: Bool
-- | Returns true if the class is abstract.
, classIsAbstract :: Bool
-- | Returns the name of the class.
, className :: ClassName
-- | Returns the name of the superclass of this class or 'Nothing'
-- if this class has no superclass.
, superClass :: Maybe ClassName
-- | Returns the list of interfaces this class implements.
, classInterfaces :: [ClassName]
-- | Returns the list of fields of the class.
, classFields :: [Field]
-- Maps method keys to method.
, classMethodMap :: Map MethodKey Method
-- | Returns the name of the source file where the class was
-- defined.
, classSourceFile :: Maybe String
-- | Returns the list of user-defined attributes of the class.
, classAttributes :: [Attribute]
} deriving (Show)
-- | Returns methods in class.
classMethods :: Class -> [Method]
classMethods = Map.elems . classMethodMap
showClass :: Class -> String
showClass cl
= "Major Version: " ++ show (majorVersion cl) ++ "\n"
++ "Minor Version: " ++ show (minorVersion cl) ++ "\n"
++ "Constant Pool:\n" ++ show (constantPool cl) ++ "\n"
++ (if classIsPublic cl then "public\n" else "")
++ (if classIsFinal cl then "final\n" else "")
++ (if classHasSuperAttribute cl then "super\n" else "")
++ (if classIsInterface cl then "interface\n" else "")
++ (if classIsAbstract cl then "abstract\n" else "")
++ "This Class: " ++ show (className cl) ++ "\n"
++ "Super Class: " ++ show (superClass cl) ++ "\n"
++ "Interfaces:\n" ++ showOnNewLines 2 (map show (classInterfaces cl)) ++ "\n"
++ "Fields:\n" ++ showOnNewLines 2 (map show (classFields cl)) ++ "\n"
++ "Methods:\n" ++ showOnNewLines 2 (map show $ classMethods cl) ++ "\n"
++ "Source file: " ++ show (classSourceFile cl) ++ "\n"
++ "Attributes:\n" ++ showOnNewLines 2 (map show $ classAttributes cl)
-- | Binary parser for classes.
getClass :: Get Class
getClass = do
magic <- getWord32be
(if magic /= 0xCAFEBABE
then failure "Unexpected magic value"
else return ())
minorVersion' <- getWord16be
majorVersion' <- getWord16be
cp <- getConstantPool
accessFlags <- getWord16be
thisClass <- getWord16be >>= poolClassName cp
superClassIndex <- getWord16be
superClass' <- if superClassIndex == 0 then pure Nothing else
Just <$> poolClassName cp superClassIndex
interfaces <- getWord16be >>= replicateN (getWord16be >>= poolClassName cp)
fields <- getWord16be >>= replicateN (getField cp)
methods <- getWord16be >>= replicateN (getMethod cp)
([sourceFile], userAttrs) <- splitAttributes cp ["SourceFile"]
sourceFile' <-
case sourceFile of
[bytes] -> Just <$> (poolUtf8 cp =<< subParser getWord16be bytes)
[] -> pure Nothing
_ -> failure "internal: unexpected source file form"
return $ MkClass majorVersion'
minorVersion'
cp
((accessFlags .&. 0x001) /= 0)
((accessFlags .&. 0x010) /= 0)
((accessFlags .&. 0x020) /= 0)
((accessFlags .&. 0x200) /= 0)
((accessFlags .&. 0x400) /= 0)
thisClass
superClass'
interfaces
fields
(Map.fromList (map (\m -> (methodKey m, m)) methods))
sourceFile'
userAttrs
-- | Returns method with given key in class or 'Nothing' if no method with that
-- key is found.
lookupMethod :: Class -> MethodKey -> Maybe Method
lookupMethod javaClass key = Map.lookup key (classMethodMap javaClass)
-- | Load and parse the class at the given path.
loadClass :: FilePath -> IO Class
loadClass path = do
handle <- openBinaryFile path ReadMode
contents <- L.hGetContents handle
case runGetOrFail getClass contents of
Left (_, pos, msg) -> fail $ "loadClass: parse failure at offset " ++ show pos ++ ": " ++ msg
Right (_, _, result) -> result `seq` (hClose handle >> pure result)
getElemTy :: Type -> Type
getElemTy (ArrayType t) = aux t
where aux (ArrayType t') = aux t'
aux t' = t'
getElemTy _ = error "getArrElemTy given non-array type"
| null | https://raw.githubusercontent.com/GaloisInc/jvm-parser/6cb3fce6c390d8b4963ca211d0a3ca88fb6ec2ca/src/Language/JVM/Parser.hs | haskell | * Class declarations
* Field declarations
* Method declarations
** Instruction declarations
** Exception table declarations
** Misc utility functions/values
* Debugging information
* Re-exports
** Types
** Instructions
** Class names
| Indicate parse failure with the given error message. Note that
failure in the 'Get' monad already tracks the number of bytes
consumed, so it is not necessary to include position information in
the error message.
| Run an inner parser on a bytestring, passing along any failures.
Version of replicate with arguments convoluted for parser.
--------------------------------------------------------------------
Type
--------------------------------------------------------------------
Visibility
| Visibility of a field.
--------------------------------------------------------------------
Method descriptors
| Returns method key with the given name and descriptor.
^ Method name
^ Method descriptor
--------------------------------------------------------------------
| Used for gaps after Long and double entries
Modified UTF-8 strings are encoded so that code point sequences
that contain only non-null ASCII characters can be represented
Unicode codespace can be represented."
-- CONSTANT_Integer
-- CONSTANT_Float
-- CONSTANT_Double
CONSTANT_Class
CONSTANT_String
CONSTANT_Fieldref
CONSTANT_Methodref
CONSTANT_InterfaceMethodref
-- CONSTANT_NameAndType
-- CONSTANT_MethodHandle_info
-- CONSTANT_InvokeDynamic_info
| Return the string at the given index in the constant pool, or
| Returns value at given index in constant pool or raises error
if constant pool index is not a value.
"The run-time constant pool item at the index must be a symbolic
reference to a class, array, or interface type."
| Returns tuple containing field class, name, and type at given index.
at the address addr.
Wide instruction
--------------------------------------------------------------------
Attributes
| An uninterpreted user-defined attribute in the class file.
Returns getter that parses attributes from stream and buckets them based on name.
index i in list-of-lists
--------------------------------------------------------------------
| A field of a class.
| Returns name of field.
| Returns type of field.
| Returns visibility of field.
| Returns true if field is static.
| Returns true if field is final.
| Returns true if field is volatile.
| Returns true if field is transient.
| Returns initial value of field or 'Nothing' if not assigned.
Only static fields may have a constant value.
| Returns true if field is synthetic.
| Returns true if field is deprecated.
| Returns true if field is transient.
visibility
isStatic
isVolatile
isTransient
constantValue
isSynthetic
isDeprecated
isEnum
signature
attrs)
= show visibility ++ " "
++ (if isStatic then "static " else "")
++ (if isVolatile then "volatile " else "")
++ (if isTransient then "transient " else "")
++ show tp ++ " "
++ name
++ case constantValue of
Nothing -> ""
Just (Long l) -> " = " ++ show l ++ " "
Just (Float f) -> " = " ++ show f ++ " "
Just (Double d) -> " = " ++ show d ++ " "
Just (Integer i) -> " = " ++ show i ++ " "
Just (String s) -> " = " ++ show s ++ " "
++ (if isSynthetic then " synthetic " else "")
++ (if isDeprecated then " deprecated " else "")
Visibility
Static
Final
Volatile
Transient
Constant Value
Check for synthetic bit in flags and buffer
Deprecated flag
Check for enum bit in flags
--------------------------------------------------------------------
Exception table
Run Get Monad until end of string is reached and return list of results.
Returns valid program counters in ascending order.
--------------------------------------------------------------------
--------------------------------------------------------------------
LocalVariableTableEntry
Start PC
length
Name
Type of local variable
Index of local variable
Maps pc and local variable index to name and type of variable in source.
--------------------------------------------------------------------
Method body
maxStack
maxLocals
exception table
Line number table entries (empty if information not provided)
Local variable table entries (optional)
Code attributes
--------------------------------------------------------------------
Method definitions
instance Show Method where
visibility
isStatic
isSynchronized
isStrictFp
body
exceptions
isSynthetic
isDeprecated
= show visibility ++ " "
++ (if isStatic then "static" else "")
++ (if isSynchronized then "synchronized " else "")
++ (case body of
AbstractMethod -> "abstract "
_ -> "")
++ (if isStrictFp then "strict " else "")
++ case returnType of
Just tp -> (show tp)
Nothing -> "void"
++ " " ++ name
++ "(" ++ showCommaSeparatedList parameterTypes ++ ")"
++ show attrs ++ "\n"
++ (if isSynthetic then " synthetic\n" else "")
++ (if isDeprecated then " deprecated\n" else "")
++ case body of
[ show i ++ ": " ++ show inst
++ (case Map.lookup i lineNumbers of
Just l -> "(line " ++ show l ++ ")"
Nothing -> "")
| (i, Just inst) <- assocs is ])
++ if null exceptions
then ""
else "\n Exceptions: " ++ show exceptions
then ""
_ -> ""
| Returns true if method is abstract.
| Returns the name of a method.
| Returns parameter types for method.
| Returns a list containing the local variable index that each
parameter is stored in when the method is invoked. Non-static
| Returns the local variable index that the parameter is stored in when
the method is invoked.
| Return type of the method, or 'Nothing' for a void return type.
(lookupInstruction method pc) returns instruction at pc in method.
Returns pc of next instruction.
trace ("nextPC: method = " ++ show method) $
nextPcPrim (toInstStream cfg) pc
| Returns maximum number of local variables in method.
| Returns true if method has debug informaiton available.
| Returns source line number of an instruction in a method at a given PC,
or the line number of the nearest predecessor instruction, or 'Nothing' if
neither is available.
| Returns the starting PC for the source at the given line number.
| Returns the enclosing method and starting PC for the source at the given line number.
| Returns local variable entry at given PC and local variable index or
'Nothing' if no mapping is found.
| Returns local variable entry at given PC and local variable string or
'Nothing' if no mapping is found.
| Exception table entries for method.
--------------------------------------------------------------------
Class declarations
| A JVM class or interface.
| Returns true if the class is public.
| Returns true if the class is final.
| Returns true if the class was annotated with the @super@ attribute.
| Returns true if the class is an interface.
| Returns true if the class is abstract.
| Returns the name of the class.
| Returns the name of the superclass of this class or 'Nothing'
if this class has no superclass.
| Returns the list of interfaces this class implements.
| Returns the list of fields of the class.
Maps method keys to method.
| Returns the name of the source file where the class was
defined.
| Returns the list of user-defined attributes of the class.
| Returns methods in class.
| Binary parser for classes.
| Returns method with given key in class or 'Nothing' if no method with that
key is found.
| Load and parse the class at the given path. | |
Module : Language . JVM.Parser
Copyright : Galois , Inc. 2012 - 2014
License : :
Stability : stable
Portability : portable
for the JVM bytecode format .
Module : Language.JVM.Parser
Copyright : Galois, Inc. 2012-2014
License : BSD3
Maintainer :
Stability : stable
Portability : portable
Parser for the JVM bytecode format.
-}
# LANGUAGE LambdaCase #
module Language.JVM.Parser (
Class
, className
, superClass
, classIsPublic
, classIsFinal
, classIsInterface
, classIsAbstract
, classHasSuperAttribute
, classInterfaces
, classFields
, classMethods
, classAttributes
, loadClass
, lookupMethod
, showClass
, getClass
, Field
, Visibility(..)
, Attribute(..)
, fieldName
, fieldType
, fieldVisibility
, fieldIsStatic
, fieldIsFinal
, fieldIsVolatile
, fieldIsTransient
, fieldConstantValue
, fieldIsSynthetic
, fieldIsDeprecated
, fieldIsEnum
, fieldSignature
, fieldAttributes
, Method
, methodName
, methodParameterTypes
, methodParameterIndexes
, localIndexOfParameter
, methodReturnType
, methodMaxLocals
, methodIsNative
, methodIsAbstract
, methodBody
, MethodBody(..)
, methodExceptionTable
, methodKey
, methodIsStatic
, MethodKey(..)
, makeMethodKey
, LocalVariableIndex
, LocalVariableTableEntry(..)
, PC
, lookupInstruction
, nextPc
, ExceptionTableEntry
, catchType
, startPc
, endPc
, handlerPc
, byteArrayTy
, charArrayTy
, getElemTy
, intArrayTy
, stringTy
, unparseMethodDescriptor
, mainKey
, hasDebugInfo
, classSourceFile
, sourceLineNumberInfo
, sourceLineNumberOrPrev
, lookupLineStartPC
, lookupLineMethodStartPC
, localVariableEntries
, lookupLocalVariableByIdx
, lookupLocalVariableByName
, ppInst
, slashesToDots
, cfgToDot
, Type(..)
, isIValue
, isPrimitiveType
, stackWidth
, isFloatType
, isRefType
, FieldId(..)
, Instruction(..)
, ClassName
, mkClassName
, unClassName
, ConstantPoolValue(..)
) where
import Control.Exception (assert)
import Control.Monad
import Data.Array (Array, (!), listArray)
import Data.Binary
import Data.Binary.Get
import Data.Bits (Bits(..))
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import Data.Char
import Data.Int
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import Prelude hiding(read)
import System.IO
import Language.JVM.CFG
import Language.JVM.Common
failure :: String -> Get a
failure msg = fail msg
subParser :: Get a -> L.ByteString -> Get a
subParser g l =
case runGetOrFail g l of
Left (_, pos, msg) ->
failure ("Sub-parser failed at position " ++ show pos ++ ": " ++ msg)
Right (_, _, x) ->
pure x
replicateN :: (Integral b, Monad m) => m a -> b -> m [a]
replicateN fn i = sequence (replicate (fromIntegral i) fn)
showOnNewLines :: Int -> [String] -> String
showOnNewLines n [] = replicate n ' ' ++ "None"
showOnNewLines n [a] = replicate n ' ' ++ a
showOnNewLines n (a : rest) = replicate n ' ' ++ a ++ "\n" ++ showOnNewLines n rest
parseTypeDescriptor :: String -> Maybe (Type, String)
parseTypeDescriptor str =
case str of
('B' : rest) -> Just (ByteType, rest)
('C' : rest) -> Just (CharType, rest)
('D' : rest) -> Just (DoubleType, rest)
('F' : rest) -> Just (FloatType, rest)
('I' : rest) -> Just (IntType, rest)
('J' : rest) -> Just (LongType, rest)
('S' : rest) -> Just (ShortType, rest)
('Z' : rest) -> Just (BooleanType, rest)
('L' : rest) -> split rest []
('[' : rest) ->
do (tp, result) <- parseTypeDescriptor rest
Just (ArrayType tp, result)
_ -> Nothing
where
split (';' : rest') result = Just (ClassType (mkClassName (reverse result)), rest')
split (ch : rest') result = split rest' (ch : result)
split _ _ = Nothing
data Visibility = Default | Private | Protected | Public
deriving Eq
instance Show Visibility where
show Default = "default"
show Private = "private"
show Protected = "protected"
show Public = "public"
parseMethodDescriptor :: String -> Maybe (Maybe Type, [Type])
parseMethodDescriptor str =
case str of
('(' : rest) -> impl rest []
_ -> Nothing
where
impl ")V" types = Just (Nothing, reverse types)
impl (')' : rest') types =
case parseTypeDescriptor rest' of
Just (tp, "") -> Just (Just tp, reverse types)
_ -> Nothing
impl text types =
do (tp, rest') <- parseTypeDescriptor text
impl rest' (tp : types)
unparseMethodDescriptor :: MethodKey -> String
unparseMethodDescriptor (MethodKey _ paramTys retTy) =
"(" ++ concatMap tyToDesc paramTys ++ ")" ++ maybe "V" tyToDesc retTy
where
tyToDesc (ArrayType ty) = "[" ++ tyToDesc ty
tyToDesc BooleanType = "Z"
tyToDesc ByteType = "B"
tyToDesc CharType = "C"
tyToDesc (ClassType cn) = "L" ++ unClassName cn ++ ";"
tyToDesc DoubleType = "D"
tyToDesc FloatType = "F"
tyToDesc IntType = "I"
tyToDesc LongType = "J"
tyToDesc ShortType = "S"
-> MethodKey
makeMethodKey name descriptor = MethodKey name parameters returnType
where (returnType, parameters) =
fromMaybe (error "Invalid method descriptor") $ parseMethodDescriptor descriptor
mainKey :: MethodKey
mainKey = makeMethodKey "main" "([Ljava/lang/String;)V"
ConstantPool
data ConstantPoolInfo
= ConstantClass Word16
| FieldRef Word16 Word16
| MethodRef Word16 Word16
| InterfaceMethodRef Word16 Word16
| ConstantString Word16
| ConstantInteger Int32
| ConstantFloat Float
| ConstantLong Int64
| ConstantDouble Double
| NameAndType Word16 Word16
| Utf8 String
| MethodHandle Word8 Word16
| MethodType Word16
| InvokeDynamic Word16 Word16
| Phantom
deriving (Show)
| Parse a string from a list of bytes , according to section 4.4.7
of the JVM spec : " String content is encoded in modified UTF-8 .
using only 1 byte per code point , but all code points in the
" There are two differences between this format and the " standard "
UTF-8 format . First , the null character ( char)0 is encoded using
the 2 - byte format rather than the 1 - byte format , so that modified
UTF-8 strings never have embedded nulls . Second , only the 1 - byte ,
2 - byte , and 3 - byte formats of standard UTF-8 are used . The Java
Virtual Machine does not recognize the four - byte format of standard
UTF-8 ; it uses its own two - times - three - byte format instead . "
parseJavaString :: [Word8] -> Maybe String
parseJavaString [] = Just []
parseJavaString (x : rest)
| (x .&. 0x80) == 0 = (:) (chr (fromIntegral x)) <$> parseJavaString rest
parseJavaString (x : y : rest)
| (x .&. 0xE0) == 0xC0 && ((y .&. 0xC0) == 0x80)
= (:) (chr i) <$> parseJavaString rest
where i = (fromIntegral x .&. 0x1F) `shift` 6 + (fromIntegral y .&. 0x3F)
parseJavaString (x : y : z : rest)
| (x .&. 0xF0) == 0xE0 && ((y .&. 0xC0) == 0x80) && ((z .&. 0xC0) == 0x80)
= (:) (chr i) <$> parseJavaString rest
where i = ((fromIntegral x .&. 0x0F) `shift` 12
+ (fromIntegral y .&. 0x3F) `shift` 6
+ (fromIntegral z .&. 0x3F))
parseJavaString _ = Nothing
getConstantPoolInfo :: Get [ConstantPoolInfo]
getConstantPoolInfo = do
tag <- getWord8
case tag of
CONSTANT_Utf8
1 -> do bytes <- replicateN getWord8 =<< getWord16be
case parseJavaString bytes of
Nothing -> failure "unable to parse byte array for Java string"
Just s -> return [Utf8 s]
3 -> do val <- get
return [ConstantInteger val]
4 -> do v <- getFloatbe
return [ConstantFloat v]
5 -> do val <- get
return [Phantom, ConstantLong val]
6 -> do val <- getDoublebe
return [Phantom, ConstantDouble val]
7 -> do index <- getWord16be
return [ConstantClass index]
8 -> do index <- getWord16be
return [ConstantString index]
9 -> do classIndex <- getWord16be
nameTypeIndex <- getWord16be
return [FieldRef classIndex nameTypeIndex]
10 -> do classIndex <- getWord16be
nameTypeIndex <- getWord16be
return [MethodRef classIndex nameTypeIndex]
11 -> do classIndex <- getWord16be
nameTypeIndex <- getWord16be
return [InterfaceMethodRef classIndex nameTypeIndex]
12 -> do classIndex <- getWord16be
nameTypeIndex <- getWord16be
return [NameAndType classIndex nameTypeIndex]
15 -> do referenceKind <- getWord8
referenceIndex <- getWord16be
return [MethodHandle referenceKind referenceIndex]
16 -> do descriptorIndex <- getWord16be
return [MethodType descriptorIndex]
18 -> do bootstrapMethodIndex <- getWord16be
nameTypeIndex <- getWord16be
return [InvokeDynamic bootstrapMethodIndex nameTypeIndex]
_ -> do failure ("Unexpected constant " ++ show tag)
type ConstantPoolIndex = Word16
type ConstantPool = Array ConstantPoolIndex ConstantPoolInfo
Get monad that extract ConstantPool from input .
getConstantPool :: Get ConstantPool
getConstantPool = do
poolCount <- getWord16be
list <- parseList (poolCount - 1) []
return $ listArray (1, poolCount - 1) list
where parseList 0 result = return $ reverse result
parseList n result = do
info <- getConstantPoolInfo
parseList (n - fromIntegral (length info)) (info ++ result)
fail if the constant pool index is not a UTF-8 string .
poolUtf8 :: ConstantPool -> ConstantPoolIndex -> Get String
poolUtf8 cp i =
case cp ! i of
Utf8 s -> pure s
v -> failure $ "Index " ++ show i ++ " has value " ++ show v ++ " when string expected."
poolValue :: ConstantPool -> ConstantPoolIndex -> Get ConstantPoolValue
poolValue cp i =
case cp ! i of
ConstantClass j -> ClassRef . mkClassName <$> poolUtf8 cp j
ConstantDouble v -> pure $ Double v
ConstantFloat v -> pure $ Float v
ConstantInteger v -> pure $ Integer v
ConstantLong v -> pure $ Long v
ConstantString j -> String <$> poolUtf8 cp j
v -> failure ("Index " ++ show i ++ " has unexpected value " ++ show v
++ " when a constant was expected.")
parseType :: String -> Get Type
parseType s =
case parseTypeDescriptor s of
Just (tp, []) -> pure tp
_ -> failure ("Invalid type descriptor: " ++ show s)
| For instructions that are described in the JVM spec like this :
poolClassType :: ConstantPool -> ConstantPoolIndex -> Get Type
poolClassType cp i =
case cp ! i of
ConstantClass j ->
do typeName <- poolUtf8 cp j
if head typeName == '['
then parseType typeName
else pure $ ClassType (mkClassName typeName)
_ ->
failure ("Index " ++ show i ++ " is not a class reference.")
poolClassName :: ConstantPool -> ConstantPoolIndex -> Get ClassName
poolClassName cp i =
case cp ! i of
ConstantClass j ->
do typeName <- poolUtf8 cp j
when (head typeName == '[') $
failure ("Index " ++ show i ++ " is an array type and not a class.")
pure $ mkClassName typeName
_ ->
failure ("Index " ++ show i ++ " is not a class reference.")
poolNameAndType :: ConstantPool -> ConstantPoolIndex -> Get (String, String)
poolNameAndType cp i =
case cp ! i of
NameAndType nameIndex typeIndex ->
(,) <$> poolUtf8 cp nameIndex <*> poolUtf8 cp typeIndex
_ -> failure ("Index " ++ show i ++ " is not a name and type reference.")
poolFieldRef :: ConstantPool -> ConstantPoolIndex -> Get FieldId
poolFieldRef cp i =
case cp ! i of
FieldRef classIndex ntIndex ->
do (name, descriptor) <- poolNameAndType cp ntIndex
fldType <- parseType descriptor
cName <- poolClassName cp classIndex
pure $ FieldId cName name fldType
_ -> failure ("Index " ++ show i ++ " is not a field reference.")
poolInterfaceMethodRef :: ConstantPool -> ConstantPoolIndex -> Get (Type, MethodKey)
poolInterfaceMethodRef cp i =
case cp ! i of
InterfaceMethodRef classIndex ntIndex ->
poolTypeAndMethodKey cp classIndex ntIndex
_ -> failure ("Index " ++ show i ++ " is not an interface method reference.")
poolMethodRef :: ConstantPool -> ConstantPoolIndex -> Get (Type, MethodKey)
poolMethodRef cp i =
case cp ! i of
MethodRef classIndex ntIndex ->
poolTypeAndMethodKey cp classIndex ntIndex
_ -> failure ("Index " ++ show i ++ " is not a method reference.")
poolMethodOrInterfaceRef :: ConstantPool -> ConstantPoolIndex -> Get (Type, MethodKey)
poolMethodOrInterfaceRef cp i =
case cp ! i of
MethodRef classIndex ntIndex ->
poolTypeAndMethodKey cp classIndex ntIndex
InterfaceMethodRef classIndex ntIndex ->
poolTypeAndMethodKey cp classIndex ntIndex
_ -> failure ("Index " ++ show i ++ " is not a method or interface method reference.")
poolTypeAndMethodKey :: ConstantPool -> ConstantPoolIndex -> ConstantPoolIndex -> Get (Type, MethodKey)
poolTypeAndMethodKey cp classIndex ntIndex =
do (name, fieldDescriptor) <- poolNameAndType cp ntIndex
classType <- poolClassType cp classIndex
pure (classType, makeMethodKey name fieldDescriptor)
_uncurry3 :: (a -> b -> c -> d) -> (a,b,c) -> d
_uncurry3 fn (a,b,c) = fn a b c
( getInstruction cp addr ) returns a parser for the instruction
getInstruction :: ConstantPool -> PC -> Get Instruction
getInstruction cp address = do
op <- getWord8
case op of
0x00 -> return Nop
0x01 -> return Aconst_null
0x02 -> return $ Ldc $ Integer (-1)
0x03 -> return $ Ldc $ Integer 0
0x04 -> return $ Ldc $ Integer 1
0x05 -> return $ Ldc $ Integer 2
0x06 -> return $ Ldc $ Integer 3
0x07 -> return $ Ldc $ Integer 4
0x08 -> return $ Ldc $ Integer 5
0x09 -> return $ Ldc $ Long 0
0x0A -> return $ Ldc $ Long 1
0x0B -> return $ Ldc $ Float 0.0
0x0C -> return $ Ldc $ Float 1.0
0x0D -> return $ Ldc $ Float 2.0
0x0E -> return $ Ldc $ Double 0.0
0x0F -> return $ Ldc $ Double 1.0
0x10 -> liftM (Ldc . Integer . fromIntegral) getInt8
0x11 -> liftM (Ldc . Integer . fromIntegral) getInt16be
0x12 -> liftM Ldc $ poolValue cp =<< liftM fromIntegral getWord8
0x13 -> liftM Ldc $ poolValue cp =<< getWord16be
0x14 -> liftM Ldc $ poolValue cp =<< getWord16be
0x15 -> liftM (Iload . fromIntegral) getWord8
0x16 -> liftM (Lload . fromIntegral) getWord8
0x17 -> liftM (Fload . fromIntegral) getWord8
0x18 -> liftM (Dload . fromIntegral) getWord8
0x19 -> liftM (Aload . fromIntegral) getWord8
0x1A -> return (Iload 0)
0x1B -> return (Iload 1)
0x1C -> return (Iload 2)
0x1D -> return (Iload 3)
0x1E -> return (Lload 0)
0x1F -> return (Lload 1)
0x20 -> return (Lload 2)
0x21 -> return (Lload 3)
0x22 -> return (Fload 0)
0x23 -> return (Fload 1)
0x24 -> return (Fload 2)
0x25 -> return (Fload 3)
0x26 -> return (Dload 0)
0x27 -> return (Dload 1)
0x28 -> return (Dload 2)
0x29 -> return (Dload 3)
0x2A -> return (Aload 0)
0x2B -> return (Aload 1)
0x2C -> return (Aload 2)
0x2D -> return (Aload 3)
0x2E -> return Iaload
0x2F -> return Laload
0x30 -> return Faload
0x31 -> return Daload
0x32 -> return Aaload
0x33 -> return Baload
0x34 -> return Caload
0x35 -> return Saload
0x36 -> liftM (Istore . fromIntegral) getWord8
0x37 -> liftM (Lstore . fromIntegral) getWord8
0x38 -> liftM (Fstore . fromIntegral) getWord8
0x39 -> liftM (Dstore . fromIntegral) getWord8
0x3A -> liftM (Astore . fromIntegral) getWord8
0x3B -> return (Istore 0)
0x3C -> return (Istore 1)
0x3D -> return (Istore 2)
0x3E -> return (Istore 3)
0x3F -> return (Lstore 0)
0x40 -> return (Lstore 1)
0x41 -> return (Lstore 2)
0x42 -> return (Lstore 3)
0x43 -> return (Fstore 0)
0x44 -> return (Fstore 1)
0x45 -> return (Fstore 2)
0x46 -> return (Fstore 3)
0x47 -> return (Dstore 0)
0x48 -> return (Dstore 1)
0x49 -> return (Dstore 2)
0x4A -> return (Dstore 3)
0x4B -> return (Astore 0)
0x4C -> return (Astore 1)
0x4D -> return (Astore 2)
0x4E -> return (Astore 3)
0x4F -> return Iastore
0x50 -> return Lastore
0x51 -> return Fastore
0x52 -> return Dastore
0x53 -> return Aastore
0x54 -> return Bastore
0x55 -> return Castore
0x56 -> return Sastore
0x57 -> return Pop
0x58 -> return Pop2
0x59 -> return Dup
0x5A -> return Dup_x1
0x5B -> return Dup_x2
0x5C -> return Dup2
0x5D -> return Dup2_x1
0x5E -> return Dup2_x2
0x5F -> return Swap
0x60 -> return Iadd
0x61 -> return Ladd
0x62 -> return Fadd
0x63 -> return Dadd
0x64 -> return Isub
0x65 -> return Lsub
0x66 -> return Fsub
0x67 -> return Dsub
0x68 -> return Imul
0x69 -> return Lmul
0x6A -> return Fmul
0x6B -> return Dmul
0x6C -> return Idiv
0x6D -> return Ldiv
0x6E -> return Fdiv
0x6F -> return Ddiv
0x70 -> return Irem
0x71 -> return Lrem
0x72 -> return Frem
0x73 -> return Drem
0x74 -> return Ineg
0x75 -> return Lneg
0x76 -> return Fneg
0x77 -> return Dneg
0x78 -> return Ishl
0x79 -> return Lshl
0x7A -> return Ishr
0x7B -> return Lshr
0x7C -> return Iushr
0x7D -> return Lushr
0x7E -> return Iand
0x7F -> return Land
0x80 -> return Ior
0x81 -> return Lor
0x82 -> return Ixor
0x83 -> return Lxor
0x84 -> do
index <- getWord8
constant <- getInt8
return (Iinc (fromIntegral index) (fromIntegral constant))
0x85 -> return I2l
0x86 -> return I2f
0x87 -> return I2d
0x88 -> return L2i
0x89 -> return L2f
0x8A -> return L2d
0x8B -> return F2i
0x8C -> return F2l
0x8D -> return F2d
0x8E -> return D2i
0x8F -> return D2l
0x90 -> return D2f
0x91 -> return I2b
0x92 -> return I2c
0x93 -> return I2s
0x94 -> return Lcmp
0x95 -> return Fcmpl
0x96 -> return Fcmpg
0x97 -> return Dcmpl
0x98 -> return Dcmpg
0x99 -> return . Ifeq . (address +) . fromIntegral =<< getInt16be
0x9A -> return . Ifne . (address +) . fromIntegral =<< getInt16be
0x9B -> return . Iflt . (address +) . fromIntegral =<< getInt16be
0x9C -> return . Ifge . (address +) . fromIntegral =<< getInt16be
0x9D -> return . Ifgt . (address +) . fromIntegral =<< getInt16be
0x9E -> return . Ifle . (address +) . fromIntegral =<< getInt16be
0x9F -> return . If_icmpeq . (address +) . fromIntegral =<< getInt16be
0xA0 -> return . If_icmpne . (address +) . fromIntegral =<< getInt16be
0xA1 -> return . If_icmplt . (address +) . fromIntegral =<< getInt16be
0xA2 -> return . If_icmpge . (address +) . fromIntegral =<< getInt16be
0xA3 -> return . If_icmpgt . (address +) . fromIntegral =<< getInt16be
0xA4 -> return . If_icmple . (address +) . fromIntegral =<< getInt16be
0xA5 -> return . If_acmpeq . (address +) . fromIntegral =<< getInt16be
0xA6 -> return . If_acmpne . (address +) . fromIntegral =<< getInt16be
0xA7 -> return . Goto . (address +) . fromIntegral =<< getInt16be
0xA8 -> return . Jsr . (address +) . fromIntegral =<< getInt16be
0xA9 -> liftM (Ret . fromIntegral) getWord8
0xAA -> do
read <- bytesRead
skip $ fromIntegral $ (4 - read `mod` 4) `mod` 4
defaultBranch <- return . (address +) . fromIntegral =<< getInt32be
low <- getInt32be
high <- getInt32be
offsets <- replicateN
(return . (address +) . fromIntegral =<< getInt32be)
(high - low + 1)
return $ Tableswitch defaultBranch low high offsets
0xAB -> do
read <- bytesRead
skip (fromIntegral ((4 - read `mod` 4) `mod` 4))
defaultBranch <- getInt32be
count <- getInt32be
pairs <- replicateM (fromIntegral count) $ do
v <- getInt32be
o <- getInt32be
return (v, ((address +) . fromIntegral) o)
return $ Lookupswitch (address + fromIntegral defaultBranch) pairs
0xAC -> return Ireturn
0xAD -> return Lreturn
0xAE -> return Freturn
0xAF -> return Dreturn
0xB0 -> return Areturn
0xB1 -> return Return
0xB2 -> Getstatic <$> (poolFieldRef cp =<< getWord16be)
0xB3 -> Putstatic <$> (poolFieldRef cp =<< getWord16be)
0xB4 -> Getfield <$> (poolFieldRef cp =<< getWord16be)
0xB5 -> Putfield <$> (poolFieldRef cp =<< getWord16be)
0xB6 -> do index <- getWord16be
(classType, key) <- poolMethodRef cp index
return $ Invokevirtual classType key
0xB7 -> do index <- getWord16be
(classType, key) <- poolMethodOrInterfaceRef cp index
return $ Invokespecial classType key
0xB8 -> do index <- getWord16be
(classType, key) <- poolMethodOrInterfaceRef cp index
cName <-
case classType of
ClassType cName -> pure cName
_ -> failure ("invokestatic: expected class type, found " ++ show classType)
pure $ Invokestatic cName key
0xB9 -> do index <- getWord16be
_ <- getWord8
_ <- getWord8
(classType, key) <- poolInterfaceMethodRef cp index
cName <-
case classType of
ClassType cName -> pure cName
_ -> failure ("invokeinterface: expected class type, found " ++ show classType)
pure $ Invokeinterface cName key
0xBA -> do index <- getWord16be
_ <- getWord8
_ <- getWord8
return $ Invokedynamic index
0xBB -> New <$> (poolClassName cp =<< getWord16be)
0xBC -> do typeCode <- getWord8
elementType <-
case typeCode of
4 -> pure BooleanType
5 -> pure CharType
6 -> pure FloatType
7 -> pure DoubleType
8 -> pure ByteType
9 -> pure ShortType
10 -> pure IntType
11 -> pure LongType
_ -> failure "internal: invalid type code encountered"
pure $ Newarray (ArrayType elementType)
0xBD -> Newarray . ArrayType <$> (poolClassType cp =<< getWord16be)
0xBE -> return Arraylength
0xBF -> return Athrow
0xC0 -> Checkcast <$> (poolClassType cp =<< getWord16be)
0xC1 -> Instanceof <$> (poolClassType cp =<< getWord16be)
0xC2 -> return Monitorenter
0xC3 -> return Monitorexit
0xC4 -> do
embeddedOp <- getWord8
case embeddedOp of
0x15 -> liftM Iload getWord16be
0x16 -> liftM Lload getWord16be
0x17 -> liftM Fload getWord16be
0x18 -> liftM Dload getWord16be
0x19 -> liftM Aload getWord16be
0x36 -> liftM Istore getWord16be
0x37 -> liftM Lstore getWord16be
0x38 -> liftM Fstore getWord16be
0x39 -> liftM Dstore getWord16be
0x3A -> liftM Astore getWord16be
0x84 -> liftM2 Iinc getWord16be getInt16be
0xA9 -> liftM Ret getWord16be
_ -> do
position <- bytesRead
failure ("Unexpected wide op " ++ (show op) ++ " at position " ++ show (position - 2))
0xC5 -> Multianewarray <$> (poolClassType cp =<< getWord16be) <*> getWord8
0xC6 -> return . Ifnull . (address +) . fromIntegral =<< getInt16be
0xC7 -> return . Ifnonnull . (address +) . fromIntegral =<< getInt16be
0xC8 -> return . Goto . (address +) . fromIntegral =<< getInt32be
0xC9 -> return . Jsr . (address +) . fromIntegral =<< getInt32be
_ -> do
position <- bytesRead
failure ("Unexpected op " ++ (show op) ++ " at position " ++ show (position - 1))
data Attribute = Attribute {
attributeName :: String
, attributeData :: B.ByteString
} deriving (Eq,Show)
splitAttributes :: ConstantPool -> [String] -> Get ([[L.ByteString]], [Attribute])
splitAttributes cp names = do
count <- getWord16be
impl count (replicate (length names) []) []
( appendAt list - of - lists index ) adds to front of list at
appendAt (l : rest) 0 a = (l ++ [a]) : rest
appendAt (first : rest) n a = first : appendAt rest (n - 1) a
appendAt [] _ _ = error "internal: appendAt expects non-empty list"
Parse values
impl 0 values rest = return (values, reverse rest)
impl n values rest = do
nameIndex <- getWord16be
len <- getWord32be
name <- poolUtf8 cp nameIndex
case elemIndex name names of
Just i ->
do bytes <- getLazyByteString (fromIntegral len)
impl (n - 1) (appendAt values i bytes) rest
Nothing ->
do bytes <- getByteString (fromIntegral len)
impl (n - 1) values (Attribute name bytes : rest)
Field declarations
data Field = Field {
fieldName :: String
, fieldType :: Type
, fieldVisibility :: Visibility
, fieldIsStatic :: Bool
, fieldIsFinal :: Bool
, fieldIsVolatile :: Bool
, fieldIsTransient :: Bool
, fieldConstantValue :: Maybe ConstantPoolValue
, fieldIsSynthetic :: Bool
, fieldIsDeprecated :: Bool
, fieldIsEnum :: Bool
, fieldSignature :: Maybe String
, fieldAttributes :: [Attribute]
} deriving (Show)
instance Show Field where
show ( Field ( FieldKey name tp )
isFinal
+ + ( if isFinal then " final " else " " )
+ + show attrs
getField :: ConstantPool -> Get Field
getField cp = do
accessFlags <- getWord16be
name <- poolUtf8 cp =<< getWord16be
fldType <- parseType =<< poolUtf8 cp =<< getWord16be
([constantValue, synthetic, deprecated, signature], userAttrs)
<- splitAttributes cp ["ConstantValue", "Synthetic", "Deprecated", "Signature"]
constantVal <-
case constantValue of
[bytes] -> Just <$> (poolValue cp =<< subParser getWord16be bytes)
[] -> pure Nothing
_ -> failure "internal: unexpected constant value form"
sig <-
case signature of
[bytes] -> Just <$> (poolUtf8 cp =<< subParser getWord16be bytes)
[] -> pure Nothing
_ -> failure "internal: unexpected signature form"
visibility <-
case accessFlags .&. 0x7 of
0x0 -> pure Default
0x1 -> pure Public
0x2 -> pure Private
0x4 -> pure Protected
flags -> failure $ "Unexpected flags " ++ show flags
return $ Field name
fldType
visibility
((accessFlags .&. 0x0008) /= 0)
((accessFlags .&. 0x0010) /= 0)
((accessFlags .&. 0x0040) /= 0)
((accessFlags .&. 0x0080) /= 0)
constantVal
((accessFlags .&. 0x1000) /= 0 || (not (null synthetic)))
(not (null deprecated))
((accessFlags .&. 0x4000) /= 0)
Signature
sig
userAttrs
getExceptionTableEntry :: ConstantPool -> Get ExceptionTableEntry
getExceptionTableEntry cp = do
startPc' <- getWord16be
endPc' <- getWord16be
handlerPc' <- getWord16be
catchIndex <- getWord16be
catchType' <-
if catchIndex == 0
then pure Nothing
else Just <$> poolClassType cp catchIndex
return (ExceptionTableEntry startPc'
endPc'
handlerPc'
catchType')
getInstructions :: ConstantPool -> PC -> Get InstructionStream
getInstructions cp count = do
read <- bytesRead
impl 0 read []
where impl pos prevRead result = do
if pos == (fromIntegral count)
then return (listArray (0, count - 1) (reverse result))
else do
inst <- getInstruction cp pos
newRead <- bytesRead
let dist = fromIntegral (newRead - prevRead)
padding = replicate (fromIntegral (dist - 1)) Nothing
in impl (pos + dist) newRead (padding ++ (Just inst : result))
getValidPcs : : InstructionStream - > [ PC ]
getValidPcs = map fst . filter ( isJust . snd ) . assocs
where isJust Nothing = False
isJust _ = True
getValidPcs :: InstructionStream -> [PC]
getValidPcs = map fst . filter (isJust . snd) . assocs
where isJust Nothing = False
isJust _ = True
-}
LineNumberTable
data LineNumberTable = LNT {
pcLineMap :: Map PC Word16
, linePCMap :: Map Word16 PC
} deriving (Eq,Show)
getLineNumberTableEntries :: Get [(PC, Word16)]
getLineNumberTableEntries = do
tableLength <- getWord16be
replicateM (fromIntegral tableLength)
(do startPc' <- getWord16be
lineNumber <- getWord16be
return (startPc', lineNumber))
parseLineNumberTable :: [L.ByteString] -> Get LineNumberTable
parseLineNumberTable buffers =
do l <- concat <$> traverse (subParser getLineNumberTableEntries) buffers
pure LNT { pcLineMap = Map.fromList l
, linePCMap = Map.fromListWith min [ (ln,pc) | (pc,ln) <- l ]
}
data LocalVariableTableEntry
= LocalVariableTableEntry
}
deriving (Eq,Show)
type LocalVariableTable = [LocalVariableTableEntry]
getLocalVariableTableEntries :: ConstantPool -> Get [LocalVariableTableEntry]
getLocalVariableTableEntries cp = do
tableLength <- getWord16be
replicateM (fromIntegral tableLength)
(do startPc' <- getWord16be
len <- getWord16be
name <- getWord16be >>= poolUtf8 cp
ty <- getWord16be >>= poolUtf8 cp >>= parseType
index <- getWord16be
pure $ LocalVariableTableEntry startPc' len name ty index)
parseLocalVariableTable :: ConstantPool -> [L.ByteString] -> Get [LocalVariableTableEntry]
parseLocalVariableTable cp buffers =
concat <$> traverse (subParser (getLocalVariableTableEntries cp)) buffers
data MethodBody
CFG
| AbstractMethod
| NativeMethod
deriving (Eq,Show)
getCode :: ConstantPool -> Get MethodBody
getCode cp = do
maxStack <- getWord16be
maxLocals <- getWord16be
codeLength <- getWord32be
instructions <- getInstructions cp (fromIntegral codeLength)
exceptionTable <- getWord16be >>= replicateN (getExceptionTableEntry cp)
([lineNumberTables, localVariableTables], userAttrs)
<- splitAttributes cp ["LineNumberTable", "LocalVariableTable"]
lnt <- parseLineNumberTable lineNumberTables
lvt <- parseLocalVariableTable cp localVariableTables
return $ Code maxStack
maxLocals
(buildCFG exceptionTable instructions)
exceptionTable
lnt
lvt
userAttrs
data Method = Method {
methodKey :: MethodKey
, _visibility :: Visibility
, methodIsStatic :: Bool
, _methodIsFinal :: Bool
, _isSynchronized :: Bool
, _isStrictFp :: Bool
, methodBody :: MethodBody
, _exceptions :: Maybe [Type]
, _isSynthetic :: Bool
, _isDeprecated :: Bool
, _attributes :: [Attribute]
} deriving (Eq,Show)
instance Ord Method where
compare m1 m2 = compare (methodKey m1) (methodKey m2)
show ( Method ( MethodKey name )
isFinal
attrs )
+ + ( if isFinal then " final " else " " )
NativeMethod - > " native "
Code maxStack maxLocals is exceptions lineNumbers _ codeAttrs - >
" Max Stack : " + + show
+ + " Max Locals : " + + show maxLocals + + " \n "
+ + ( showOnNewLines 4
+ + if null codeAttrs
else " \n Attributes : " + + show codeAttrs
getExceptions :: ConstantPool -> Get [Type]
getExceptions cp = do
exceptionCount <- getWord16be
replicateN (getWord16be >>= poolClassType cp) exceptionCount
getMethod :: ConstantPool -> Get Method
getMethod cp = do
accessFlags <- getWord16be
name <- getWord16be >>= poolUtf8 cp
descriptor <- getWord16be >>= poolUtf8 cp
(returnType, parameterTypes) <-
maybe (failure "Invalid method descriptor") pure $ parseMethodDescriptor descriptor
([codeVal, exceptionsVal, syntheticVal, deprecatedVal], userAttrs)
<- splitAttributes cp ["Code", "Exceptions", "Synthetic", "Deprecated"]
visibility <-
case accessFlags .&. 0x7 of
0x0 -> pure Default
0x1 -> pure Public
0x2 -> pure Private
0x4 -> pure Protected
flags -> failure $ "Unexpected flags " ++ show flags
let isStatic' = (accessFlags .&. 0x008) /= 0
isFinal = (accessFlags .&. 0x010) /= 0
isSynchronized' = (accessFlags .&. 0x020) /= 0
isAbstract = (accessFlags .&. 0x400) /= 0
isStrictFp' = (accessFlags .&. 0x800) /= 0
body <-
if ((accessFlags .&. 0x100) /= 0) then pure NativeMethod else
if isAbstract then pure AbstractMethod else
case codeVal of
[bytes] -> subParser (getCode cp) bytes
_ -> failure "Could not find code attribute"
exceptions <-
case exceptionsVal of
[bytes] -> Just <$> subParser (getExceptions cp) bytes
[] -> pure Nothing
_ -> failure "internal: unexpected expectionsVal form"
return $
Method (MethodKey name parameterTypes returnType)
visibility
isStatic'
isFinal
isSynchronized'
isStrictFp'
body
exceptions
(not $ null syntheticVal)
(not $ null deprecatedVal)
userAttrs
methodIsNative :: Method -> Bool
methodIsNative m =
case methodBody m of
NativeMethod -> True
_ -> False
methodIsAbstract :: Method -> Bool
methodIsAbstract m =
case methodBody m of
AbstractMethod -> True
_ -> False
methodName :: Method -> String
methodName = methodKeyName . methodKey
methodParameterTypes :: Method -> [Type]
methodParameterTypes = methodKeyParameterTypes . methodKey
methods reserve index 0 for the @self@ parameter .
methodParameterIndexes :: Method -> [LocalVariableIndex]
methodParameterIndexes m = init $ scanl next start params
where
params = methodParameterTypes m
start = if methodIsStatic m then 0 else 1
next n DoubleType = n + 2
next n LongType = n + 2
next n _ = n + 1
localIndexOfParameter :: Method -> Int -> LocalVariableIndex
localIndexOfParameter m i = assert (0 <= i && i < length offsets) $ offsets !! i
where offsets = methodParameterIndexes m
methodReturnType :: Method -> Maybe Type
methodReturnType = methodKeyReturnType . methodKey
lookupInstruction :: Method -> PC -> Instruction
lookupInstruction method pc =
case methodBody method of
Code _ _ cfg _ _ _ _ ->
case (cfgInstByPC cfg pc) of
Just i -> i
Nothing -> error "internal: failed to index inst stream"
_ -> error ("Method " ++ show method ++ " has no body")
nextPc :: Method -> PC -> PC
nextPc method pc =
case methodBody method of
Code _ _ cfg _ _ _ _ ->
case nextPC cfg pc of
Nothing -> error "JavaParser.nextPc: no next instruction"
Just npc -> npc
_ -> error "internal: unexpected method body form"
methodMaxLocals :: Method -> LocalVariableIndex
methodMaxLocals method =
case methodBody method of
Code _ c _ _ _ _ _ -> c
_ -> error "internal: unexpected method body form"
hasDebugInfo :: Method -> Bool
hasDebugInfo method =
case methodBody method of
Code _ _ _ _ lns lvars _ -> not (Map.null (pcLineMap lns) && null lvars)
_ -> False
methodLineNumberTable :: Method -> Maybe LineNumberTable
methodLineNumberTable me = do
case methodBody me of
Code _ _ _ _ lns _ _ -> Just lns
_ -> Nothing
sourceLineNumberInfo :: Method -> [(Word16,PC)]
sourceLineNumberInfo me =
maybe [] (Map.toList . pcLineMap) $ methodLineNumberTable me
sourceLineNumberOrPrev :: Method -> PC -> Maybe Word16
sourceLineNumberOrPrev me pc =
case methodBody me of
Code _ _ _ _ lns _ _ ->
case Map.splitLookup pc (pcLineMap lns) of
(prs, Nothing, _)
| not $ Map.null prs -> Just $ snd $ Map.findMax prs
| otherwise -> Nothing
(_, ln, _) -> ln
_ -> error "internal: unexpected method body form"
lookupLineStartPC :: Method -> Word16 -> Maybe PC
lookupLineStartPC me ln = do
m <- methodLineNumberTable me
Map.lookup ln (linePCMap m)
lookupLineMethodStartPC :: Class -> Word16 -> Maybe (Method, PC)
lookupLineMethodStartPC cl ln =
case results of
(p:_) -> return p
[] -> mzero
where results = do
me <- Map.elems . classMethodMap $ cl
case lookupLineStartPC me ln of
Just pc -> return (me, pc)
Nothing -> mzero
localVariableEntries :: Method -> PC -> [LocalVariableTableEntry]
localVariableEntries method pc =
case methodBody method of
Code _ _ _ _ _ lvars _ ->
let matches e = localStart e <= pc &&
pc - localStart e <= localExtent e
in filter matches lvars
_ -> []
lookupLocalVariableByIdx :: Method -> PC -> LocalVariableIndex
-> Maybe LocalVariableTableEntry
lookupLocalVariableByIdx method pc i =
find (\e -> localIdx e == i) (localVariableEntries method pc)
lookupLocalVariableByName :: Method -> PC -> String -> Maybe LocalVariableTableEntry
lookupLocalVariableByName method pc name =
find (\e -> localName e == name) (localVariableEntries method pc)
methodExceptionTable :: Method -> [ExceptionTableEntry]
methodExceptionTable method =
case methodBody method of
Code _ _ _ table _ _ _ -> table
_ -> error "internal: unexpected method body form"
data Class = MkClass {
majorVersion :: Word16
, minorVersion :: Word16
, constantPool :: ConstantPool
, classIsPublic :: Bool
, classIsFinal :: Bool
, classHasSuperAttribute :: Bool
, classIsInterface :: Bool
, classIsAbstract :: Bool
, className :: ClassName
, superClass :: Maybe ClassName
, classInterfaces :: [ClassName]
, classFields :: [Field]
, classMethodMap :: Map MethodKey Method
, classSourceFile :: Maybe String
, classAttributes :: [Attribute]
} deriving (Show)
classMethods :: Class -> [Method]
classMethods = Map.elems . classMethodMap
showClass :: Class -> String
showClass cl
= "Major Version: " ++ show (majorVersion cl) ++ "\n"
++ "Minor Version: " ++ show (minorVersion cl) ++ "\n"
++ "Constant Pool:\n" ++ show (constantPool cl) ++ "\n"
++ (if classIsPublic cl then "public\n" else "")
++ (if classIsFinal cl then "final\n" else "")
++ (if classHasSuperAttribute cl then "super\n" else "")
++ (if classIsInterface cl then "interface\n" else "")
++ (if classIsAbstract cl then "abstract\n" else "")
++ "This Class: " ++ show (className cl) ++ "\n"
++ "Super Class: " ++ show (superClass cl) ++ "\n"
++ "Interfaces:\n" ++ showOnNewLines 2 (map show (classInterfaces cl)) ++ "\n"
++ "Fields:\n" ++ showOnNewLines 2 (map show (classFields cl)) ++ "\n"
++ "Methods:\n" ++ showOnNewLines 2 (map show $ classMethods cl) ++ "\n"
++ "Source file: " ++ show (classSourceFile cl) ++ "\n"
++ "Attributes:\n" ++ showOnNewLines 2 (map show $ classAttributes cl)
getClass :: Get Class
getClass = do
magic <- getWord32be
(if magic /= 0xCAFEBABE
then failure "Unexpected magic value"
else return ())
minorVersion' <- getWord16be
majorVersion' <- getWord16be
cp <- getConstantPool
accessFlags <- getWord16be
thisClass <- getWord16be >>= poolClassName cp
superClassIndex <- getWord16be
superClass' <- if superClassIndex == 0 then pure Nothing else
Just <$> poolClassName cp superClassIndex
interfaces <- getWord16be >>= replicateN (getWord16be >>= poolClassName cp)
fields <- getWord16be >>= replicateN (getField cp)
methods <- getWord16be >>= replicateN (getMethod cp)
([sourceFile], userAttrs) <- splitAttributes cp ["SourceFile"]
sourceFile' <-
case sourceFile of
[bytes] -> Just <$> (poolUtf8 cp =<< subParser getWord16be bytes)
[] -> pure Nothing
_ -> failure "internal: unexpected source file form"
return $ MkClass majorVersion'
minorVersion'
cp
((accessFlags .&. 0x001) /= 0)
((accessFlags .&. 0x010) /= 0)
((accessFlags .&. 0x020) /= 0)
((accessFlags .&. 0x200) /= 0)
((accessFlags .&. 0x400) /= 0)
thisClass
superClass'
interfaces
fields
(Map.fromList (map (\m -> (methodKey m, m)) methods))
sourceFile'
userAttrs
lookupMethod :: Class -> MethodKey -> Maybe Method
lookupMethod javaClass key = Map.lookup key (classMethodMap javaClass)
loadClass :: FilePath -> IO Class
loadClass path = do
handle <- openBinaryFile path ReadMode
contents <- L.hGetContents handle
case runGetOrFail getClass contents of
Left (_, pos, msg) -> fail $ "loadClass: parse failure at offset " ++ show pos ++ ": " ++ msg
Right (_, _, result) -> result `seq` (hClose handle >> pure result)
getElemTy :: Type -> Type
getElemTy (ArrayType t) = aux t
where aux (ArrayType t') = aux t'
aux t' = t'
getElemTy _ = error "getArrElemTy given non-array type"
|
9e99c0b9562123e845b54865fb037cb13298f14fae16d0601e48bfb49a7ba73d | aeternity/aeternity | sophia_bytecode_aevm_SUITE.erl | -module(sophia_bytecode_aevm_SUITE).
%% common_test exports
-export(
[ all/0
, init_per_suite/1
, end_per_suite/1
]).
%% test case exports
-export(
[
execute_identity_fun_from_sophia_file/1
]).
-include_lib("aecontract/include/aecontract.hrl").
-include_lib("aebytecode/include/aeb_opcodes.hrl").
-include_lib("common_test/include/ct.hrl").
-include_lib("aecontract/include/hard_forks.hrl").
all() ->
[
execute_identity_fun_from_sophia_file ].
init_per_suite(Config) ->
case aect_test_utils:latest_protocol_version() < ?IRIS_PROTOCOL_VSN of
true -> Config;
false -> {skip, aevm_deprecated}
end.
end_per_suite(_Config) ->
ok.
execute_identity_fun_from_sophia_file(_Cfg) ->
{ok, ContractBin} = aect_test_utils:read_contract(identity),
{ok, Compiled} = aect_test_utils:compile_contract(identity),
#{ byte_code := Code,
type_info := TypeInfo} = aect_sophia:deserialize(Compiled),
{ok, ArgType} = aeb_aevm_abi:arg_typerep_from_function(<<"main_">>, TypeInfo),
CallDataType = {tuple, [word, ArgType]},
OutType = word,
%% Create the call data
{ok, CallData} = aect_test_utils:encode_call_data(ContractBin, <<"main_">>, [<<"42">>]),
ABI = aect_test_utils:latest_sophia_abi_version(),
VM = aect_test_utils:latest_sophia_vm_version(),
{ok, Store} = aevm_eeevm_store:from_sophia_state(
#{vm => VM, abi => ABI},
aeb_heap:to_binary({{tuple, []}, {}})),
{ok, Res} =
aevm_eeevm:eval(
aevm_eeevm_state:init(
#{ exec => #{ code => Code,
store => Store,
address => 91210,
caller => 0,
data => CallData,
call_data_type => CallDataType,
out_type => OutType,
gas => 1000000,
gasPrice => 1,
origin => 0,
creator => 0,
value => 0 },
env => #{currentCoinbase => 0,
currentDifficulty => 0,
currentGasLimit => 10000,
currentNumber => 0,
currentTimestamp => 0,
chainState => aevm_dummy_chain:new_state(),
chainAPI => aevm_dummy_chain,
protocol_version => aect_test_utils:latest_protocol_version(),
vm_version => VM,
abi_version => ABI},
pre => #{}},
#{trace => true})
),
#{ out := RetVal } = Res,
<<42:256>> = RetVal,
ok.
| null | https://raw.githubusercontent.com/aeternity/aeternity/f61163c89dc8bf01a8e2297f1189c02c3d3563f9/test/sophia_bytecode_aevm_SUITE.erl | erlang | common_test exports
test case exports
Create the call data | -module(sophia_bytecode_aevm_SUITE).
-export(
[ all/0
, init_per_suite/1
, end_per_suite/1
]).
-export(
[
execute_identity_fun_from_sophia_file/1
]).
-include_lib("aecontract/include/aecontract.hrl").
-include_lib("aebytecode/include/aeb_opcodes.hrl").
-include_lib("common_test/include/ct.hrl").
-include_lib("aecontract/include/hard_forks.hrl").
all() ->
[
execute_identity_fun_from_sophia_file ].
init_per_suite(Config) ->
case aect_test_utils:latest_protocol_version() < ?IRIS_PROTOCOL_VSN of
true -> Config;
false -> {skip, aevm_deprecated}
end.
end_per_suite(_Config) ->
ok.
execute_identity_fun_from_sophia_file(_Cfg) ->
{ok, ContractBin} = aect_test_utils:read_contract(identity),
{ok, Compiled} = aect_test_utils:compile_contract(identity),
#{ byte_code := Code,
type_info := TypeInfo} = aect_sophia:deserialize(Compiled),
{ok, ArgType} = aeb_aevm_abi:arg_typerep_from_function(<<"main_">>, TypeInfo),
CallDataType = {tuple, [word, ArgType]},
OutType = word,
{ok, CallData} = aect_test_utils:encode_call_data(ContractBin, <<"main_">>, [<<"42">>]),
ABI = aect_test_utils:latest_sophia_abi_version(),
VM = aect_test_utils:latest_sophia_vm_version(),
{ok, Store} = aevm_eeevm_store:from_sophia_state(
#{vm => VM, abi => ABI},
aeb_heap:to_binary({{tuple, []}, {}})),
{ok, Res} =
aevm_eeevm:eval(
aevm_eeevm_state:init(
#{ exec => #{ code => Code,
store => Store,
address => 91210,
caller => 0,
data => CallData,
call_data_type => CallDataType,
out_type => OutType,
gas => 1000000,
gasPrice => 1,
origin => 0,
creator => 0,
value => 0 },
env => #{currentCoinbase => 0,
currentDifficulty => 0,
currentGasLimit => 10000,
currentNumber => 0,
currentTimestamp => 0,
chainState => aevm_dummy_chain:new_state(),
chainAPI => aevm_dummy_chain,
protocol_version => aect_test_utils:latest_protocol_version(),
vm_version => VM,
abi_version => ABI},
pre => #{}},
#{trace => true})
),
#{ out := RetVal } = Res,
<<42:256>> = RetVal,
ok.
|
e84db4173355c343580da4d52dacba5d1313f4c81631ccd36d92512d8cfe5245 | buntine/Simply-Scheme-Exercises | 4-10.scm | ; Write a procedure to compute the tip you should leave at a restaurant. It should
take the total bill as its argument and return the amount of the tip . It should tip by 15 % ,
; but it should know to round up so that the total amount of money you leave (tip plus
; original bill) is a whole number of dollars. (Use the ceiling procedure to round up.)
;
> ( tip 19.98 )
3.02
;
> ( tip 29.23 )
4.77
;
> ( tip 7.54 )
1.46
(define (discount price reduction)
(if (and (> reduction 0) (> 100 reduction))
(- price
(* (/ price 100)
reduction))))
(define (tip price)
(ceiling (discount price 85)))
| null | https://raw.githubusercontent.com/buntine/Simply-Scheme-Exercises/c6cbf0bd60d6385b506b8df94c348ac5edc7f646/04-defining-your-own-procedures/4-10.scm | scheme | Write a procedure to compute the tip you should leave at a restaurant. It should
but it should know to round up so that the total amount of money you leave (tip plus
original bill) is a whole number of dollars. (Use the ceiling procedure to round up.)
| take the total bill as its argument and return the amount of the tip . It should tip by 15 % ,
> ( tip 19.98 )
3.02
> ( tip 29.23 )
4.77
> ( tip 7.54 )
1.46
(define (discount price reduction)
(if (and (> reduction 0) (> 100 reduction))
(- price
(* (/ price 100)
reduction))))
(define (tip price)
(ceiling (discount price 85)))
|
529c9a9777c50a1ececcabdbbc0f2ad15e5994663c191f2153acf78e3eb812b3 | EDToaster/CSC324-A2-TestingSuite | testIfNonAtomic.rkt | (if (cps:equal? (cps:+ 10 10) (cps:+ 20 20)) (cps:+ (cps:* 10 2) (cps:* 10 3)) (cps:* (cps:+ 1 2) (cps:+ 3 4))) | null | https://raw.githubusercontent.com/EDToaster/CSC324-A2-TestingSuite/f07cbd01587a46c61aac29c52a6804864a4eb77b/tests/testIfNonAtomic.rkt | racket | (if (cps:equal? (cps:+ 10 10) (cps:+ 20 20)) (cps:+ (cps:* 10 2) (cps:* 10 3)) (cps:* (cps:+ 1 2) (cps:+ 3 4))) |
|
9fa5e3bd041490759d19caaa2f036bc781f0e1c642072a5bdfa0843492f6abc0 | footprintanalytics/footprint-web | normalize.cljc | (ns metabase.mbql.normalize
"Logic for taking any sort of weird MBQL query and normalizing it into a standardized, canonical form. You can think
of this like taking any 'valid' MBQL query and rewriting it as-if it was written in perfect up-to-date MBQL in the
latest version. There are four main things done here, done as four separate steps:
#### NORMALIZING TOKENS
Converting all identifiers to lower-case, lisp-case keywords. e.g. `{\"SOURCE_TABLE\" 10}` becomes `{:source-table
10}`.
#### CANONICALIZING THE QUERY
Rewriting deprecated MBQL 95/98 syntax and other things that are still supported for backwards-compatibility in
canonical modern MBQL syntax. For example `{:breakout [:count 10]}` becomes `{:breakout [[:count [:field 10 nil]]]}`.
#### WHOLE-QUERY TRANSFORMATIONS
Transformations and cleanup of the query structure as a whole to fix inconsistencies. Whereas the canonicalization
phase operates on a lower-level, transforming invidual clauses, this phase focuses on transformations that affect
multiple clauses, such as removing duplicate references to Fields if they are specified in both the `:breakout` and
`:fields` clauses.
several pieces of QP middleware perform similar
individual transformations, such as `reconcile-breakout-and-order-by-bucketing`.
#### REMOVING EMPTY CLAUSES
Removing empty clauses like `{:aggregation nil}` or `{:breakout []}`.
Token normalization occurs first, followed by canonicalization, followed by removing empty clauses."
(:require [clojure.set :as set]
[clojure.walk :as walk]
[medley.core :as m]
[metabase.mbql.util :as mbql.u]
[metabase.mbql.util.match :as mbql.match]
[metabase.shared.util.i18n :as i18n]
[metabase.shared.util.log :as log]))
(defn- mbql-clause?
"True if `x` is an MBQL clause (a sequence with a token as its first arg). (This is different from the implementation
in `mbql.u` because it also supports un-normalized clauses. You shouldn't need to use this outside of this
namespace.)"
[x]
(and (sequential? x)
(not (map-entry? x))
((some-fn keyword? string?) (first x))))
(defn- maybe-normalize-token
"Normalize token `x`, but only if it's a keyword or string."
[x]
(if ((some-fn keyword? string?) x)
(mbql.u/normalize-token x)
x))
(defn is-clause?
"If `x` an MBQL clause, and an instance of clauses defined by keyword(s) `k-or-ks`?
(is-clause? :count [:count 10]) ; -> true
(is-clause? #{:+ :- :* :/} [:+ 10 20]) ; -> true
(This is different from the implementation in `mbql.u` because it also supports un-normalized clauses. You shouldn't
need to use this outside of this namespace.)"
[k-or-ks x]
(and
(mbql-clause? x)
(let [clause-name (maybe-normalize-token (first x))]
(if (coll? k-or-ks)
((set k-or-ks) clause-name)
(= k-or-ks clause-name)))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | NORMALIZE TOKENS |
;;; +----------------------------------------------------------------------------------------------------------------+
(declare normalize-tokens)
(defmulti ^:private normalize-mbql-clause-tokens
(comp maybe-normalize-token first))
(defmethod normalize-mbql-clause-tokens :expression
;; For expression references (`[:expression \"my_expression\"]`) keep the arg as is but make sure it is a string.
[[_ expression-name]]
[:expression (if (keyword? expression-name)
(mbql.u/qualified-name expression-name)
expression-name)])
(defmethod normalize-mbql-clause-tokens :binning-strategy
For ` : binning - strategy ` clauses ( which wrap other Field clauses ) normalize the strategy - name and recursively
normalize the Field it bins .
[[_ field strategy-name strategy-param]]
(if strategy-param
(conj (normalize-mbql-clause-tokens [:binning-strategy field strategy-name]) strategy-param)
[:binning-strategy (normalize-tokens field :ignore-path) (maybe-normalize-token strategy-name)]))
(defmethod normalize-mbql-clause-tokens :field
[[_ id-or-name opts]]
(let [opts (normalize-tokens opts :ignore-path)]
[:field
id-or-name
(cond-> opts
(:base-type opts) (update :base-type keyword)
(:temporal-unit opts) (update :temporal-unit keyword)
(:binning opts) (update :binning (fn [binning]
(cond-> binning
(:strategy binning) (update :strategy keyword)))))]))
(defmethod normalize-mbql-clause-tokens :field-literal
Similarly , for Field literals , keep the arg as - is , but make sure it is a string . "
[[_ field-name field-type]]
[:field-literal
(if (keyword? field-name)
(mbql.u/qualified-name field-name)
field-name)
(keyword field-type)])
(defmethod normalize-mbql-clause-tokens :datetime-field
;; Datetime fields look like `[:datetime-field <field> <unit>]` or `[:datetime-field <field> :as <unit>]`
;; normalize the unit, and `:as` (if present) tokens, and the Field."
[[_ field as-or-unit maybe-unit]]
(if maybe-unit
[:datetime-field (normalize-tokens field :ignore-path) :as (maybe-normalize-token maybe-unit)]
[:datetime-field (normalize-tokens field :ignore-path) (maybe-normalize-token as-or-unit)]))
(defmethod normalize-mbql-clause-tokens :time-interval
;; `time-interval`'s `unit` should get normalized, and `amount` if it's not an integer."
[[_ field amount unit options]]
(if options
(conj (normalize-mbql-clause-tokens [:time-interval field amount unit])
(normalize-tokens options :ignore-path))
[:time-interval
(normalize-tokens field :ignore-path)
(if (integer? amount)
amount
(maybe-normalize-token amount))
(maybe-normalize-token unit)]))
(defmethod normalize-mbql-clause-tokens :relative-datetime
Normalize a ` relative - datetime ` clause . ` relative - datetime ` comes in two flavors :
;;
;; [:relative-datetime :current]
;; [:relative-datetime -10 :day] ; amount & unit"
[[_ amount unit]]
(if unit
[:relative-datetime amount (maybe-normalize-token unit)]
[:relative-datetime :current]))
(defmethod normalize-mbql-clause-tokens :interval
[[_ amount unit]]
[:interval amount (maybe-normalize-token unit)])
(defmethod normalize-mbql-clause-tokens :datetime-add
[[_ field amount unit]]
[:datetime-add (normalize-tokens field :ignore-path) amount (maybe-normalize-token unit)])
(defmethod normalize-mbql-clause-tokens :datetime-subtract
[[_ field amount unit]]
[:datetime-subtract (normalize-tokens field :ignore-path) amount (maybe-normalize-token unit)])
(defmethod normalize-mbql-clause-tokens :get-week
[[_ field mode]]
(if mode
[:get-week (normalize-tokens field :ignore-path) (maybe-normalize-token mode)]
[:get-week (normalize-tokens field :ignore-path)]))
(defmethod normalize-mbql-clause-tokens :temporal-extract
[[_ field unit mode]]
(if mode
[:temporal-extract (normalize-tokens field :ignore-path) (maybe-normalize-token unit) (maybe-normalize-token mode)]
[:temporal-extract (normalize-tokens field :ignore-path) (maybe-normalize-token unit)]))
(defmethod normalize-mbql-clause-tokens :datetime-diff
[[_ x y unit]]
[:datetime-diff
(normalize-tokens x :ignore-path)
(normalize-tokens y :ignore-path)
(maybe-normalize-token unit)])
(defmethod normalize-mbql-clause-tokens :value
;; The args of a `value` clause shouldn't be normalized.
;; See for details
[[_ value info]]
[:value value info])
(defmethod normalize-mbql-clause-tokens :default
;; MBQL clauses by default are recursively normalized.
;; This includes the clause name (e.g. `[\"COUNT\" ...]` becomes `[:count ...]`) and args.
[[clause-name & args]]
(into [(maybe-normalize-token clause-name)] (map #(normalize-tokens % :ignore-path)) args))
(defn- aggregation-subclause?
[x]
(or (when ((some-fn keyword? string?) x)
(#{:avg :count :cum-count :distinct :stddev :sum :min :max :+ :- :/ :*
:sum-where :count-where :share :var :median :percentile}
(maybe-normalize-token x)))
(when (mbql-clause? x)
(aggregation-subclause? (first x)))))
(defn- normalize-ag-clause-tokens
"For old-style aggregations like `{:aggregation :count}` make sure we normalize the ag type (`:count`). Other wacky
clauses like `{:aggregation [:count :count]}` need to be handled as well :("
[ag-clause]
(cond
;; something like {:aggregations :count}
((some-fn keyword? string?) ag-clause)
(maybe-normalize-token ag-clause)
;; named aggregation ([:named <ag> <name>])
(is-clause? :named ag-clause)
(let [[_ wrapped-ag & more] ag-clause]
(into [:named (normalize-ag-clause-tokens wrapped-ag)] more))
something wack like { : aggregations [: count [: sum 10 ] ] } or { : aggregations [: count : count ] }
(when (mbql-clause? ag-clause)
(aggregation-subclause? (second ag-clause)))
(mapv normalize-ag-clause-tokens ag-clause)
:else
(normalize-tokens ag-clause :ignore-path)))
(defn- normalize-expressions-tokens
"For expressions, we don't want to normalize the name of the expression; keep that as is, and make it a string;
normalize the definitions as normal."
[expressions-clause]
(into {} (for [[expression-name definition] expressions-clause]
[(mbql.u/qualified-name expression-name)
(normalize-tokens definition :ignore-path)])))
(defn- normalize-order-by-tokens
"Normalize tokens in the order-by clause, which can have different syntax when using MBQL 95 or 98
rules (`[<field> :asc]` vs `[:asc <field>]`, for example)."
[clauses]
(vec (for [subclause clauses]
(if (mbql-clause? subclause)
;; MBQL 98+ [direction field] style: normalize as normal
(normalize-mbql-clause-tokens subclause)
;; otherwise it's MBQL 95 [field direction] style: flip the args and *then* normalize the clause. And then
;; flip it back to put it back the way we found it.
(reverse (normalize-mbql-clause-tokens (reverse subclause)))))))
(defn- template-tag-definition-key->transform-fn
"Get the function that should be used to transform values for normalized key `k` in a template tag definition."
[k]
(get {:default identity
:type maybe-normalize-token
:widget-type maybe-normalize-token}
k
;; if there's not a special transform function for the key in the map above, just wrap the key-value
;; pair in a dummy map and let [[normalize-tokens]] take care of it. Then unwrap
(fn [v]
(-> (normalize-tokens {k v} :ignore-path)
(get k)))))
(defn- normalize-template-tag-definition
"For a template tag definition, normalize all the keys appropriately."
[tag-definition]
(let [tag-def (into
{}
(map (fn [[k v]]
(let [k (maybe-normalize-token k)
transform-fn (template-tag-definition-key->transform-fn k)]
[k (transform-fn v)])))
tag-definition)]
` : widget - type ` is a required key for Field Filter ( dimension ) template tags -- see
;; [[metabase.mbql.schema/TemplateTag:FieldFilter]] -- but prior to v42 it wasn't usually included by the
frontend . See # 20643 . If it 's not present , just add in ` : category ` which will make things work they way they
;; did in the past.
(cond-> tag-def
(and (= (:type tag-def) :dimension)
(not (:widget-type tag-def)))
(assoc :widget-type :category))))
(defn- normalize-template-tags
"Normalize native-query template tags. Like `expressions` we want to preserve the original name rather than normalize
it."
[template-tags]
(into
{}
(map (fn [[tag-name tag-definition]]
(let [tag-name (mbql.u/qualified-name tag-name)]
[tag-name
(-> (normalize-template-tag-definition tag-definition)
(assoc :name tag-name))])))
template-tags))
(defn normalize-query-parameter
"Normalize a parameter in the query `:parameters` list."
[{:keys [type target id], :as param}]
(cond-> param
id (update :id mbql.u/qualified-name)
;; some things that get ran thru here, like dashcard param targets, do not have :type
type (update :type maybe-normalize-token)
target (update :target #(normalize-tokens % :ignore-path))))
(defn- normalize-source-query [source-query]
(let [{native? :native, :as source-query} (m/map-keys maybe-normalize-token source-query)]
(if native?
(-> source-query
(set/rename-keys {:native :query})
(normalize-tokens [:native])
(set/rename-keys {:query :native}))
(normalize-tokens source-query [:query]))))
(defn- normalize-join [join]
;; path in call to `normalize-tokens` is [:query] so it will normalize `:source-query` as appropriate
(let [{:keys [strategy fields alias], :as join} (normalize-tokens join :query)]
(cond-> join
strategy
(update :strategy maybe-normalize-token)
((some-fn keyword? string?) fields)
(update :fields maybe-normalize-token)
alias
(update :alias mbql.u/qualified-name))))
(declare canonicalize-mbql-clauses)
(defn normalize-source-metadata
"Normalize source/results metadata for a single column."
[metadata]
{:pre [(map? metadata)]}
(-> (reduce #(m/update-existing %1 %2 keyword) metadata [:base_type :effective_type :semantic_type :visibility_type :source :unit])
(m/update-existing :field_ref (comp canonicalize-mbql-clauses normalize-tokens))
(m/update-existing :fingerprint walk/keywordize-keys)))
(defn- normalize-native-query
"For native queries, normalize the top-level keys, and template tags, but nothing else."
[native-query]
(let [native-query (m/map-keys maybe-normalize-token native-query)]
(cond-> native-query
(seq (:template-tags native-query)) (update :template-tags normalize-template-tags))))
;; TODO - why not make this a multimethod of some sort?
(def ^:private path->special-token-normalization-fn
"Map of special functions that should be used to perform token normalization for a given path. For example, the
`:expressions` key in an MBQL query should preserve the case of the expression names; this custom behavior is
defined below."
{:type maybe-normalize-token
;; don't normalize native queries
:native normalize-native-query
:query {:aggregation normalize-ag-clause-tokens
:expressions normalize-expressions-tokens
:order-by normalize-order-by-tokens
:source-query normalize-source-query
:source-metadata {::sequence normalize-source-metadata}
:joins {::sequence normalize-join}}
;; we smuggle metadata for datasets and want to preserve their "database" form vs a normalized form so it matches
;; the style in annotate.clj
:info {:metadata/dataset-metadata identity}
:parameters {::sequence normalize-query-parameter}
:context #(some-> % maybe-normalize-token)
:source-metadata {::sequence normalize-source-metadata}
:viz-settings maybe-normalize-token})
(defn normalize-tokens
"Recursively normalize tokens in `x`.
Every time this function recurses (thru a map value) it adds a new (normalized) key to key path, e.g. `path` will be
`[:query :order-by]` when we're in the MBQL order-by clause. If we need to handle these top-level clauses in special
ways add a function to `path->special-token-normalization-fn` above.
In some cases, dealing with the path isn't desirable, but we don't want to accidentally trigger normalization
functions (such as accidentally normalizing the `:type` key in something other than the top-level of the query), so
by convention please pass `:ignore-path` to avoid accidentally triggering path functions."
[x & [path]]
(let [path (if (keyword? path)
[path]
(vec path))
special-fn (when (seq path)
(get-in path->special-token-normalization-fn path))]
(try
(cond
(fn? special-fn)
(special-fn x)
;; Skip record types because this query is an `expanded` query, which is not going to play nice here. Hopefully we
;; can remove expanded queries entirely soon.
(record? x)
x
;; maps should just get the keys normalized and then recursively call normalize-tokens on the values.
;; Each recursive call appends to the keypath above so we can handle top-level clauses in a special way if needed
(map? x)
(into {} (for [[k v] x
:let [k (maybe-normalize-token k)]]
[k (normalize-tokens v (conj (vec path) k))]))
;; MBQL clauses handled above because of special cases
(mbql-clause? x)
(normalize-mbql-clause-tokens x)
;; for non-mbql sequential collections (probably something like the subclauses of :order-by or something like
;; that) recurse on all the args.
;;
;; To signify that we're recursing into a sequential collection, this appends `::sequence` to path
(sequential? x)
(mapv #(normalize-tokens % (conj (vec path) ::sequence)) x)
:else
x)
(catch #?(:clj Throwable :cljs js/Error) e
(throw (ex-info (i18n/tru "Error normalizing form: {0}" (ex-message e))
{:form x, :path path, :special-fn special-fn}
e))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | CANONICALIZE |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- wrap-implicit-field-id
"Wrap raw integer Field IDs (i.e., those in an implicit 'field' position) in a `:field` clause if they're not
already. Done for MBQL 95 backwards-compatibility. e.g.:
- > { : filter [: = [ : field 10 nil ] 20 ] } "
[field]
(if (integer? field)
[:field field nil]
field))
(defmulti ^:private canonicalize-mbql-clause
{:arglists '([clause])}
(fn [clause]
(when (mbql-clause? clause)
(first clause))))
(defmethod canonicalize-mbql-clause :default
[clause]
clause)
(defn- canonicalize-implicit-field-id
"If `clause` is a raw integer ID wrap it in a `:field` clause. Either way, canonicalize the resulting clause."
[clause]
(canonicalize-mbql-clause (wrap-implicit-field-id clause)))
(defmethod canonicalize-mbql-clause :field
[[_ id-or-name opts]]
(if (is-clause? :field id-or-name)
(let [[_ nested-id-or-name nested-opts] id-or-name]
(canonicalize-mbql-clause [:field nested-id-or-name (not-empty (merge nested-opts opts))]))
;; remove empty stuff from the options map. The `remove-empty-clauses` step will further remove empty stuff
;; afterwards
[:field id-or-name (not-empty opts)]))
legacy Field clauses
(defmethod canonicalize-mbql-clause :field-id
[[_ id]]
;; if someone is dumb and does something like [:field-id [:field-literal ...]] be nice and fix it for them.
(if (mbql-clause? id)
(canonicalize-mbql-clause id)
[:field id nil]))
(defmethod canonicalize-mbql-clause :field-literal
[[_ field-name base-type]]
[:field field-name {:base-type base-type}])
(defmethod canonicalize-mbql-clause :fk->
[[_ field-1 field-2]]
(let [[_ source _] (canonicalize-implicit-field-id field-1)
[_ dest dest-opts] (canonicalize-implicit-field-id field-2)]
[:field dest (assoc dest-opts :source-field source)]))
(defmethod canonicalize-mbql-clause :joined-field
[[_ join-alias field]]
(-> (canonicalize-implicit-field-id field)
(mbql.u/assoc-field-options :join-alias join-alias)))
(defmethod canonicalize-mbql-clause :datetime-field
[clause]
(case (count clause)
3
(let [[_ field unit] clause]
(-> (canonicalize-implicit-field-id field)
(mbql.u/with-temporal-unit unit)))
4
(let [[_ field _ unit] clause]
(canonicalize-mbql-clause [:datetime-field field unit]))))
(defmethod canonicalize-mbql-clause :binning-strategy
[[_ field strategy param binning-options]]
(let [[_ id-or-name opts] (canonicalize-implicit-field-id field)]
[:field
id-or-name
(assoc opts :binning (merge {:strategy strategy}
(when param
{strategy param})
binning-options))]))
;;; filter clauses
;; For `and`/`or`/`not` compound filters, recurse on the arg(s), then simplify the whole thing.
(defn- canonicalize-compound-filter-clause [[filter-name & args]]
(mbql.u/simplify-compound-filter
(into [filter-name]
we need to canonicalize any other clauses that might show up in args here because
;; simplify-compund-filter validates its output :(
(map canonicalize-mbql-clause args))))
(doseq [clause-name [:and :or :not]]
(defmethod canonicalize-mbql-clause clause-name
[clause]
(canonicalize-compound-filter-clause clause)))
(defmethod canonicalize-mbql-clause :inside
[[_ field-1 field-2 & coordinates]]
(into [:inside
(canonicalize-implicit-field-id field-1)
(canonicalize-implicit-field-id field-2)]
coordinates))
(defmethod canonicalize-mbql-clause :time-interval
[[_ field & args]]
if you specify a ` : temporal - unit ` for the Field inside a ` : time - interval ` , remove it . The unit in
;; `:time-interval` takes precedence.
(let [field (cond-> (canonicalize-implicit-field-id field)
(mbql.u/is-clause? :field field) (mbql.u/update-field-options dissoc :temporal-unit))]
(into [:time-interval field] args)))
all the other filter types have an implict field ID for the first arg
( e.g. [: = 10 20 ] gets canonicalized to [: = [ : field - id 10 ] 20 ]
(defn- canonicalize-simple-filter-clause
[[filter-name first-arg & other-args]]
Support legacy expressions like [ :> 1 25 ] where 1 is a field i d.
(into [filter-name (canonicalize-implicit-field-id first-arg)]
(map canonicalize-mbql-clause other-args)))
(doseq [clause-name [:starts-with :ends-with :contains :does-not-contain
:= :!= :< :<= :> :>=
:is-empty :not-empty :is-null :not-null
:between]]
(defmethod canonicalize-mbql-clause clause-name
[clause]
(canonicalize-simple-filter-clause clause)))
aggregations / expression
Remove ` : rows ` type aggregation ( long - since deprecated ; means no aggregation ) if present
(defmethod canonicalize-mbql-clause :rows
[_]
nil)
TODO -- if options is empty , should we just unwrap the clause ?
(defmethod canonicalize-mbql-clause :aggregation-options
[[_ wrapped-aggregation-clause options]]
[:aggregation-options (canonicalize-mbql-clause wrapped-aggregation-clause) options])
;; for legacy `:named` aggregations convert them to a new-style `:aggregation-options` clause.
;;
99.99 % of clauses should have no options , however if they do and ` : use - as - display - name ? ` is false ( default is
;; true) then generate options to change `:name` rather than `:display-name`
(defmethod canonicalize-mbql-clause :named
[[_ wrapped-ag expr-name & more]]
(canonicalize-mbql-clause
[:aggregation-options
(canonicalize-mbql-clause wrapped-ag)
(let [[{:keys [use-as-display-name?]}] more]
(if (false? use-as-display-name?)
{:name expr-name}
{:display-name expr-name}))]))
(defn- canonicalize-count-clause [[clause-name field]]
(if field
[clause-name (canonicalize-implicit-field-id field)]
[clause-name]))
(doseq [clause-name [:count :cum-count]]
(defmethod canonicalize-mbql-clause clause-name
[clause]
(canonicalize-count-clause clause)))
(defn- canonicalize-simple-aggregation-with-field
[[clause-name field]]
[clause-name (canonicalize-implicit-field-id field)])
(doseq [clause-name [:avg :cum-sum :distinct :stddev :sum :min :max :median :var]]
(defmethod canonicalize-mbql-clause clause-name
[clause]
(canonicalize-simple-aggregation-with-field clause)))
(defmethod canonicalize-mbql-clause :percentile
[[_ field percentile]]
[:percentile (canonicalize-implicit-field-id field) percentile])
(defn- canonicalize-filtered-aggregation-clause
[[clause-name filter-subclause]]
[clause-name (canonicalize-mbql-clause filter-subclause)])
(doseq [clause-name [:share :count-where]]
(defmethod canonicalize-mbql-clause clause-name
[clause]
(canonicalize-filtered-aggregation-clause clause)))
(defmethod canonicalize-mbql-clause :sum-where
[[_ field filter-subclause]]
[:sum-where (canonicalize-mbql-clause field) (canonicalize-mbql-clause filter-subclause)])
(defmethod canonicalize-mbql-clause :case
[[_ clauses options]]
(if options
(conj (canonicalize-mbql-clause [:case clauses])
(normalize-tokens options :ignore-path))
[:case (vec (for [[pred expr] clauses]
[(canonicalize-mbql-clause pred) (canonicalize-mbql-clause expr)]))]))
;;; top-level key canonicalization
(defn- canonicalize-mbql-clauses
"Walk an `mbql-query` an canonicalize non-top-level clauses like `:fk->`."
[mbql-query]
(walk/prewalk
(fn [x]
(cond
(map? x)
(m/map-vals canonicalize-mbql-clauses x)
(not (mbql-clause? x))
x
:else
(try
(canonicalize-mbql-clause x)
(catch #?(:clj Throwable :cljs js/Error) e
(log/error (i18n/tru "Invalid clause:") x)
(throw (ex-info (i18n/tru "Invalid MBQL clause: {0}" (ex-message e))
{:clause x}
e))))))
mbql-query))
(defn- wrap-single-aggregations
"Convert old MBQL 95 single-aggregations like `{:aggregation :count}` or `{:aggregation [:count]}` to MBQL 98+
multiple-aggregation syntax (e.g. `{:aggregation [[:count]]}`)."
[aggregations]
(mbql.match/replace aggregations
seq? (recur (vec &match))
something like { : aggregations : count } -- MBQL 95 single aggregation
keyword?
[[&match]]
special - case : MBQL 98 multiple aggregations using unwrapped : count or : rows
e.g. { : aggregations [: count [: sum 10 ] ] } or { : aggregations [: count : count ] }
[(_ :guard (every-pred keyword? (complement #{:named :+ :- :* :/})))
(_ :guard aggregation-subclause?)
& _]
(vec (reduce concat (map wrap-single-aggregations aggregations)))
something like { : aggregations [: sum 10 ] } -- MBQL 95 single aggregation
[(_ :guard keyword?) & _]
[&match]
_
&match))
(defn- canonicalize-aggregations
"Canonicalize subclauses (see above) and make sure `:aggregation` is a sequence of clauses instead of a single
clause."
[aggregations]
(->> (wrap-single-aggregations aggregations)
(keep canonicalize-mbql-clauses)
vec))
(defn- canonicalize-breakouts [breakouts]
(if (mbql-clause? breakouts)
(recur [breakouts])
(not-empty (mapv wrap-implicit-field-id breakouts))))
(defn- canonicalize-order-by
"Make sure order by clauses like `[:asc 10]` get `:field-id` added where appropriate, e.g. `[:asc [:field-id 10]]`"
[clauses]
(mbql.match/replace clauses
seq? (recur (vec &match))
;; MBQL 95 reversed [<field> <direction>] clause
[field :asc] (recur [:asc field])
[field :desc] (recur [:desc field])
[field :ascending] (recur [:asc field])
[field :descending] (recur [:desc field])
MBQL 95 names but MBQL 98 + reversed syntax
[:ascending field] (recur [:asc field])
[:descending field] (recur [:desc field])
[:asc field] [:asc (canonicalize-implicit-field-id field)]
[:desc field] [:desc (canonicalize-implicit-field-id field)]
this case should be the first one hit when we come in with a vector of clauses e.g. [ [: asc 1 ] [: desc 2 ] ]
[& clauses] (vec (distinct (map canonicalize-order-by clauses)))))
(declare canonicalize-inner-mbql-query)
(defn- canonicalize-template-tag [{:keys [dimension], :as tag}]
(cond-> tag
dimension (update :dimension canonicalize-mbql-clause)))
(defn- canonicalize-template-tags [tags]
(into {} (for [[tag-name tag] tags]
[tag-name (canonicalize-template-tag tag)])))
(defn- canonicalize-native-query [{:keys [template-tags], :as native-query}]
(cond-> native-query
template-tags (update :template-tags canonicalize-template-tags)))
(defn- canonicalize-source-query [{native? :native, :as source-query}]
(cond-> source-query
(not native?) canonicalize-inner-mbql-query
native? canonicalize-native-query))
(defn- non-empty? [x]
(if (coll? x)
(seq x)
(some? x)))
(defn- canonicalize-top-level-mbql-clauses
"Perform specific steps to canonicalize the various top-level clauses in an MBQL query."
[mbql-query]
(cond-> mbql-query
(non-empty? (:aggregation mbql-query)) (update :aggregation canonicalize-aggregations)
(non-empty? (:breakout mbql-query)) (update :breakout canonicalize-breakouts)
(non-empty? (:fields mbql-query)) (update :fields (partial mapv wrap-implicit-field-id))
(non-empty? (:order-by mbql-query)) (update :order-by canonicalize-order-by)
(non-empty? (:source-query mbql-query)) (update :source-query canonicalize-source-query)))
(def ^:private ^{:arglists '([query])} canonicalize-inner-mbql-query
(comp canonicalize-mbql-clauses canonicalize-top-level-mbql-clauses))
(defn- move-source-metadata-to-mbql-query
"In Metabase 0.33.0 `:source-metadata` about resolved queries is added to the 'inner' MBQL query rather than to the
top-level; if we encounter the old style, move it to the appropriate location."
[{:keys [source-metadata], :as query}]
(-> query
(dissoc :source-metadata)
(assoc-in [:query :source-metadata] source-metadata)))
(defn- canonicalize
"Canonicalize a query [MBQL query], rewriting the query as if you perfectly followed the recommended style guides for
writing MBQL. Does things like removes unneeded and empty clauses, converts older MBQL '95 syntax to MBQL '98, etc."
[{:keys [query parameters source-metadata native], :as outer-query}]
(try
(cond-> outer-query
source-metadata move-source-metadata-to-mbql-query
query (update :query canonicalize-inner-mbql-query)
parameters (update :parameters (partial mapv canonicalize-mbql-clauses))
native (update :native canonicalize-native-query)
true canonicalize-mbql-clauses)
(catch #?(:clj Throwable :cljs js/Error) e
(throw (ex-info (i18n/tru "Error canonicalizing query: {0}" (ex-message e))
{:query query}
e)))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | WHOLE-QUERY TRANSFORMATIONS |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- remove-breakout-fields-from-fields
it is implied that any breakout Field
will be returned, specifying it in both would imply it is to be returned twice, which tends to cause confusion for
the QP and drivers. (This is done to work around historic bugs with the way queries were generated on the frontend;
I'm not sure this behavior makes sense, but removing it would break existing queries.)
We will remove either exact matches:
{:breakout [[:field-id 10]], :fields [[:field-id 10]]} ; -> {:breakout [[:field-id 10]]}
or unbucketed matches:
{:breakout [[:datetime-field [:field-id 10] :month]], :fields [[:field-id 10]]}
;; -> {:breakout [[:field-id 10]]}"
[{{:keys [breakout fields]} :query, :as query}]
(if-not (and (seq breakout) (seq fields))
query
get a set of all Field clauses ( of any type ) in the breakout . For temporal - bucketed fields , we 'll include both
;; the bucketed `[:datetime-field <field> ...]` clause and the `<field>` clause it wraps
(let [breakout-fields (set (reduce concat (mbql.match/match breakout
[:field id-or-name opts]
[&match
[:field id-or-name (dissoc opts :temporal-unit)]])))]
now remove all the Fields in ` : fields ` that match the ones in the set
(update-in query [:query :fields] (comp vec (partial remove breakout-fields))))))
(defn- perform-whole-query-transformations
"Perform transformations that operate on the query as a whole, making sure the structure as a whole is logical and
consistent."
[query]
(try
(remove-breakout-fields-from-fields query)
(catch #?(:clj Throwable :cljs js/Error) e
(throw (ex-info (i18n/tru "Error performing whole query transformations")
{:query query}
e)))))
;;; +----------------------------------------------------------------------------------------------------------------+
| REMOVING EMPTY CLAUSES |
;;; +----------------------------------------------------------------------------------------------------------------+
(declare remove-empty-clauses)
(defn- remove-empty-clauses-in-map [m path]
(let [m (into (empty m) (for [[k v] m
:let [v (remove-empty-clauses v (conj path k))]
:when (some? v)]
[k v]))]
(when (seq m)
m)))
(defn- remove-empty-clauses-in-sequence [xs path]
(let [xs (mapv #(remove-empty-clauses % (conj path ::sequence))
xs)]
(when (some some? xs)
xs)))
(defn- remove-empty-clauses-in-join [join]
(remove-empty-clauses join [:query]))
(defn- remove-empty-clauses-in-source-query [{native? :native, :as source-query}]
(if native?
(-> source-query
(set/rename-keys {:native :query})
(remove-empty-clauses [:native])
(set/rename-keys {:query :native}))
(remove-empty-clauses source-query [:query])))
(def ^:private path->special-remove-empty-clauses-fn
{:native identity
:query {:source-query remove-empty-clauses-in-source-query
:joins {::sequence remove-empty-clauses-in-join}}
:viz-settings identity})
(defn- remove-empty-clauses
"Remove any empty or `nil` clauses in a query."
([query]
(remove-empty-clauses query []))
([x path]
(try
(let [special-fn (when (seq path)
(get-in path->special-remove-empty-clauses-fn path))]
(cond
(fn? special-fn) (special-fn x)
(record? x) x
(map? x) (remove-empty-clauses-in-map x path)
(sequential? x) (remove-empty-clauses-in-sequence x path)
:else x))
(catch #?(:clj Throwable :cljs js/Error) e
(throw (ex-info "Error removing empty clauses from form."
{:form x, :path path}
e))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | PUTTING IT ALL TOGETHER |
;;; +----------------------------------------------------------------------------------------------------------------+
(def ^{:arglists '([outer-query])} normalize
"Normalize the tokens in a Metabase query (i.e., make them all `lisp-case` keywords), rewrite deprecated clauses as
up-to-date MBQL 2000, and remove empty clauses."
(let [normalize* (comp remove-empty-clauses
perform-whole-query-transformations
canonicalize
normalize-tokens)]
(fn [query]
(try
(normalize* query)
(catch #?(:clj Throwable :cljs js/Error) e
(throw (ex-info (i18n/tru "Error normalizing query: {0}" (ex-message e))
{:query query}
e)))))))
(defn normalize-fragment
"Normalize just a specific fragment of a query, such as just the inner MBQL part or just a filter clause. `path` is
where this fragment would normally live in a full query.
(normalize-fragment [:query :filter] [\"=\" 100 200])
- > [: = [ : field - id 100 ] 200 ] "
{:style/indent 1}
[path x]
(if-not (seq path)
(normalize x)
(get (normalize-fragment (butlast path) {(last path) x}) (last path))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/shared/src/metabase/mbql/normalize.cljc | clojure | -> true
-> true
+----------------------------------------------------------------------------------------------------------------+
| NORMALIZE TOKENS |
+----------------------------------------------------------------------------------------------------------------+
For expression references (`[:expression \"my_expression\"]`) keep the arg as is but make sure it is a string.
Datetime fields look like `[:datetime-field <field> <unit>]` or `[:datetime-field <field> :as <unit>]`
normalize the unit, and `:as` (if present) tokens, and the Field."
`time-interval`'s `unit` should get normalized, and `amount` if it's not an integer."
[:relative-datetime :current]
[:relative-datetime -10 :day] ; amount & unit"
The args of a `value` clause shouldn't be normalized.
See for details
MBQL clauses by default are recursively normalized.
This includes the clause name (e.g. `[\"COUNT\" ...]` becomes `[:count ...]`) and args.
something like {:aggregations :count}
named aggregation ([:named <ag> <name>])
keep that as is, and make it a string;
MBQL 98+ [direction field] style: normalize as normal
otherwise it's MBQL 95 [field direction] style: flip the args and *then* normalize the clause. And then
flip it back to put it back the way we found it.
if there's not a special transform function for the key in the map above, just wrap the key-value
pair in a dummy map and let [[normalize-tokens]] take care of it. Then unwrap
[[metabase.mbql.schema/TemplateTag:FieldFilter]] -- but prior to v42 it wasn't usually included by the
did in the past.
some things that get ran thru here, like dashcard param targets, do not have :type
path in call to `normalize-tokens` is [:query] so it will normalize `:source-query` as appropriate
TODO - why not make this a multimethod of some sort?
this custom behavior is
don't normalize native queries
we smuggle metadata for datasets and want to preserve their "database" form vs a normalized form so it matches
the style in annotate.clj
Skip record types because this query is an `expanded` query, which is not going to play nice here. Hopefully we
can remove expanded queries entirely soon.
maps should just get the keys normalized and then recursively call normalize-tokens on the values.
Each recursive call appends to the keypath above so we can handle top-level clauses in a special way if needed
MBQL clauses handled above because of special cases
for non-mbql sequential collections (probably something like the subclauses of :order-by or something like
that) recurse on all the args.
To signify that we're recursing into a sequential collection, this appends `::sequence` to path
+----------------------------------------------------------------------------------------------------------------+
| CANONICALIZE |
+----------------------------------------------------------------------------------------------------------------+
remove empty stuff from the options map. The `remove-empty-clauses` step will further remove empty stuff
afterwards
if someone is dumb and does something like [:field-id [:field-literal ...]] be nice and fix it for them.
filter clauses
For `and`/`or`/`not` compound filters, recurse on the arg(s), then simplify the whole thing.
simplify-compund-filter validates its output :(
`:time-interval` takes precedence.
means no aggregation ) if present
for legacy `:named` aggregations convert them to a new-style `:aggregation-options` clause.
true) then generate options to change `:name` rather than `:display-name`
top-level key canonicalization
MBQL 95 reversed [<field> <direction>] clause
if we encounter the old style, move it to the appropriate location."
+----------------------------------------------------------------------------------------------------------------+
| WHOLE-QUERY TRANSFORMATIONS |
+----------------------------------------------------------------------------------------------------------------+
-> {:breakout [[:field-id 10]]}
-> {:breakout [[:field-id 10]]}"
the bucketed `[:datetime-field <field> ...]` clause and the `<field>` clause it wraps
+----------------------------------------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------------------------------------+
| PUTTING IT ALL TOGETHER |
+----------------------------------------------------------------------------------------------------------------+ | (ns metabase.mbql.normalize
"Logic for taking any sort of weird MBQL query and normalizing it into a standardized, canonical form. You can think
of this like taking any 'valid' MBQL query and rewriting it as-if it was written in perfect up-to-date MBQL in the
latest version. There are four main things done here, done as four separate steps:
#### NORMALIZING TOKENS
Converting all identifiers to lower-case, lisp-case keywords. e.g. `{\"SOURCE_TABLE\" 10}` becomes `{:source-table
10}`.
#### CANONICALIZING THE QUERY
Rewriting deprecated MBQL 95/98 syntax and other things that are still supported for backwards-compatibility in
canonical modern MBQL syntax. For example `{:breakout [:count 10]}` becomes `{:breakout [[:count [:field 10 nil]]]}`.
#### WHOLE-QUERY TRANSFORMATIONS
Transformations and cleanup of the query structure as a whole to fix inconsistencies. Whereas the canonicalization
phase operates on a lower-level, transforming invidual clauses, this phase focuses on transformations that affect
multiple clauses, such as removing duplicate references to Fields if they are specified in both the `:breakout` and
`:fields` clauses.
several pieces of QP middleware perform similar
individual transformations, such as `reconcile-breakout-and-order-by-bucketing`.
#### REMOVING EMPTY CLAUSES
Removing empty clauses like `{:aggregation nil}` or `{:breakout []}`.
Token normalization occurs first, followed by canonicalization, followed by removing empty clauses."
(:require [clojure.set :as set]
[clojure.walk :as walk]
[medley.core :as m]
[metabase.mbql.util :as mbql.u]
[metabase.mbql.util.match :as mbql.match]
[metabase.shared.util.i18n :as i18n]
[metabase.shared.util.log :as log]))
(defn- mbql-clause?
"True if `x` is an MBQL clause (a sequence with a token as its first arg). (This is different from the implementation
in `mbql.u` because it also supports un-normalized clauses. You shouldn't need to use this outside of this
namespace.)"
[x]
(and (sequential? x)
(not (map-entry? x))
((some-fn keyword? string?) (first x))))
(defn- maybe-normalize-token
"Normalize token `x`, but only if it's a keyword or string."
[x]
(if ((some-fn keyword? string?) x)
(mbql.u/normalize-token x)
x))
(defn is-clause?
"If `x` an MBQL clause, and an instance of clauses defined by keyword(s) `k-or-ks`?
(This is different from the implementation in `mbql.u` because it also supports un-normalized clauses. You shouldn't
need to use this outside of this namespace.)"
[k-or-ks x]
(and
(mbql-clause? x)
(let [clause-name (maybe-normalize-token (first x))]
(if (coll? k-or-ks)
((set k-or-ks) clause-name)
(= k-or-ks clause-name)))))
(declare normalize-tokens)
(defmulti ^:private normalize-mbql-clause-tokens
(comp maybe-normalize-token first))
(defmethod normalize-mbql-clause-tokens :expression
[[_ expression-name]]
[:expression (if (keyword? expression-name)
(mbql.u/qualified-name expression-name)
expression-name)])
(defmethod normalize-mbql-clause-tokens :binning-strategy
For ` : binning - strategy ` clauses ( which wrap other Field clauses ) normalize the strategy - name and recursively
normalize the Field it bins .
[[_ field strategy-name strategy-param]]
(if strategy-param
(conj (normalize-mbql-clause-tokens [:binning-strategy field strategy-name]) strategy-param)
[:binning-strategy (normalize-tokens field :ignore-path) (maybe-normalize-token strategy-name)]))
(defmethod normalize-mbql-clause-tokens :field
[[_ id-or-name opts]]
(let [opts (normalize-tokens opts :ignore-path)]
[:field
id-or-name
(cond-> opts
(:base-type opts) (update :base-type keyword)
(:temporal-unit opts) (update :temporal-unit keyword)
(:binning opts) (update :binning (fn [binning]
(cond-> binning
(:strategy binning) (update :strategy keyword)))))]))
(defmethod normalize-mbql-clause-tokens :field-literal
Similarly , for Field literals , keep the arg as - is , but make sure it is a string . "
[[_ field-name field-type]]
[:field-literal
(if (keyword? field-name)
(mbql.u/qualified-name field-name)
field-name)
(keyword field-type)])
(defmethod normalize-mbql-clause-tokens :datetime-field
[[_ field as-or-unit maybe-unit]]
(if maybe-unit
[:datetime-field (normalize-tokens field :ignore-path) :as (maybe-normalize-token maybe-unit)]
[:datetime-field (normalize-tokens field :ignore-path) (maybe-normalize-token as-or-unit)]))
(defmethod normalize-mbql-clause-tokens :time-interval
[[_ field amount unit options]]
(if options
(conj (normalize-mbql-clause-tokens [:time-interval field amount unit])
(normalize-tokens options :ignore-path))
[:time-interval
(normalize-tokens field :ignore-path)
(if (integer? amount)
amount
(maybe-normalize-token amount))
(maybe-normalize-token unit)]))
(defmethod normalize-mbql-clause-tokens :relative-datetime
Normalize a ` relative - datetime ` clause . ` relative - datetime ` comes in two flavors :
[[_ amount unit]]
(if unit
[:relative-datetime amount (maybe-normalize-token unit)]
[:relative-datetime :current]))
(defmethod normalize-mbql-clause-tokens :interval
[[_ amount unit]]
[:interval amount (maybe-normalize-token unit)])
(defmethod normalize-mbql-clause-tokens :datetime-add
[[_ field amount unit]]
[:datetime-add (normalize-tokens field :ignore-path) amount (maybe-normalize-token unit)])
(defmethod normalize-mbql-clause-tokens :datetime-subtract
[[_ field amount unit]]
[:datetime-subtract (normalize-tokens field :ignore-path) amount (maybe-normalize-token unit)])
(defmethod normalize-mbql-clause-tokens :get-week
[[_ field mode]]
(if mode
[:get-week (normalize-tokens field :ignore-path) (maybe-normalize-token mode)]
[:get-week (normalize-tokens field :ignore-path)]))
(defmethod normalize-mbql-clause-tokens :temporal-extract
[[_ field unit mode]]
(if mode
[:temporal-extract (normalize-tokens field :ignore-path) (maybe-normalize-token unit) (maybe-normalize-token mode)]
[:temporal-extract (normalize-tokens field :ignore-path) (maybe-normalize-token unit)]))
(defmethod normalize-mbql-clause-tokens :datetime-diff
[[_ x y unit]]
[:datetime-diff
(normalize-tokens x :ignore-path)
(normalize-tokens y :ignore-path)
(maybe-normalize-token unit)])
(defmethod normalize-mbql-clause-tokens :value
[[_ value info]]
[:value value info])
(defmethod normalize-mbql-clause-tokens :default
[[clause-name & args]]
(into [(maybe-normalize-token clause-name)] (map #(normalize-tokens % :ignore-path)) args))
(defn- aggregation-subclause?
[x]
(or (when ((some-fn keyword? string?) x)
(#{:avg :count :cum-count :distinct :stddev :sum :min :max :+ :- :/ :*
:sum-where :count-where :share :var :median :percentile}
(maybe-normalize-token x)))
(when (mbql-clause? x)
(aggregation-subclause? (first x)))))
(defn- normalize-ag-clause-tokens
"For old-style aggregations like `{:aggregation :count}` make sure we normalize the ag type (`:count`). Other wacky
clauses like `{:aggregation [:count :count]}` need to be handled as well :("
[ag-clause]
(cond
((some-fn keyword? string?) ag-clause)
(maybe-normalize-token ag-clause)
(is-clause? :named ag-clause)
(let [[_ wrapped-ag & more] ag-clause]
(into [:named (normalize-ag-clause-tokens wrapped-ag)] more))
something wack like { : aggregations [: count [: sum 10 ] ] } or { : aggregations [: count : count ] }
(when (mbql-clause? ag-clause)
(aggregation-subclause? (second ag-clause)))
(mapv normalize-ag-clause-tokens ag-clause)
:else
(normalize-tokens ag-clause :ignore-path)))
(defn- normalize-expressions-tokens
normalize the definitions as normal."
[expressions-clause]
(into {} (for [[expression-name definition] expressions-clause]
[(mbql.u/qualified-name expression-name)
(normalize-tokens definition :ignore-path)])))
(defn- normalize-order-by-tokens
"Normalize tokens in the order-by clause, which can have different syntax when using MBQL 95 or 98
rules (`[<field> :asc]` vs `[:asc <field>]`, for example)."
[clauses]
(vec (for [subclause clauses]
(if (mbql-clause? subclause)
(normalize-mbql-clause-tokens subclause)
(reverse (normalize-mbql-clause-tokens (reverse subclause)))))))
(defn- template-tag-definition-key->transform-fn
"Get the function that should be used to transform values for normalized key `k` in a template tag definition."
[k]
(get {:default identity
:type maybe-normalize-token
:widget-type maybe-normalize-token}
k
(fn [v]
(-> (normalize-tokens {k v} :ignore-path)
(get k)))))
(defn- normalize-template-tag-definition
"For a template tag definition, normalize all the keys appropriately."
[tag-definition]
(let [tag-def (into
{}
(map (fn [[k v]]
(let [k (maybe-normalize-token k)
transform-fn (template-tag-definition-key->transform-fn k)]
[k (transform-fn v)])))
tag-definition)]
` : widget - type ` is a required key for Field Filter ( dimension ) template tags -- see
frontend . See # 20643 . If it 's not present , just add in ` : category ` which will make things work they way they
(cond-> tag-def
(and (= (:type tag-def) :dimension)
(not (:widget-type tag-def)))
(assoc :widget-type :category))))
(defn- normalize-template-tags
"Normalize native-query template tags. Like `expressions` we want to preserve the original name rather than normalize
it."
[template-tags]
(into
{}
(map (fn [[tag-name tag-definition]]
(let [tag-name (mbql.u/qualified-name tag-name)]
[tag-name
(-> (normalize-template-tag-definition tag-definition)
(assoc :name tag-name))])))
template-tags))
(defn normalize-query-parameter
"Normalize a parameter in the query `:parameters` list."
[{:keys [type target id], :as param}]
(cond-> param
id (update :id mbql.u/qualified-name)
type (update :type maybe-normalize-token)
target (update :target #(normalize-tokens % :ignore-path))))
(defn- normalize-source-query [source-query]
(let [{native? :native, :as source-query} (m/map-keys maybe-normalize-token source-query)]
(if native?
(-> source-query
(set/rename-keys {:native :query})
(normalize-tokens [:native])
(set/rename-keys {:query :native}))
(normalize-tokens source-query [:query]))))
(defn- normalize-join [join]
(let [{:keys [strategy fields alias], :as join} (normalize-tokens join :query)]
(cond-> join
strategy
(update :strategy maybe-normalize-token)
((some-fn keyword? string?) fields)
(update :fields maybe-normalize-token)
alias
(update :alias mbql.u/qualified-name))))
(declare canonicalize-mbql-clauses)
(defn normalize-source-metadata
"Normalize source/results metadata for a single column."
[metadata]
{:pre [(map? metadata)]}
(-> (reduce #(m/update-existing %1 %2 keyword) metadata [:base_type :effective_type :semantic_type :visibility_type :source :unit])
(m/update-existing :field_ref (comp canonicalize-mbql-clauses normalize-tokens))
(m/update-existing :fingerprint walk/keywordize-keys)))
(defn- normalize-native-query
"For native queries, normalize the top-level keys, and template tags, but nothing else."
[native-query]
(let [native-query (m/map-keys maybe-normalize-token native-query)]
(cond-> native-query
(seq (:template-tags native-query)) (update :template-tags normalize-template-tags))))
(def ^:private path->special-token-normalization-fn
"Map of special functions that should be used to perform token normalization for a given path. For example, the
defined below."
{:type maybe-normalize-token
:native normalize-native-query
:query {:aggregation normalize-ag-clause-tokens
:expressions normalize-expressions-tokens
:order-by normalize-order-by-tokens
:source-query normalize-source-query
:source-metadata {::sequence normalize-source-metadata}
:joins {::sequence normalize-join}}
:info {:metadata/dataset-metadata identity}
:parameters {::sequence normalize-query-parameter}
:context #(some-> % maybe-normalize-token)
:source-metadata {::sequence normalize-source-metadata}
:viz-settings maybe-normalize-token})
(defn normalize-tokens
"Recursively normalize tokens in `x`.
Every time this function recurses (thru a map value) it adds a new (normalized) key to key path, e.g. `path` will be
`[:query :order-by]` when we're in the MBQL order-by clause. If we need to handle these top-level clauses in special
ways add a function to `path->special-token-normalization-fn` above.
In some cases, dealing with the path isn't desirable, but we don't want to accidentally trigger normalization
functions (such as accidentally normalizing the `:type` key in something other than the top-level of the query), so
by convention please pass `:ignore-path` to avoid accidentally triggering path functions."
[x & [path]]
(let [path (if (keyword? path)
[path]
(vec path))
special-fn (when (seq path)
(get-in path->special-token-normalization-fn path))]
(try
(cond
(fn? special-fn)
(special-fn x)
(record? x)
x
(map? x)
(into {} (for [[k v] x
:let [k (maybe-normalize-token k)]]
[k (normalize-tokens v (conj (vec path) k))]))
(mbql-clause? x)
(normalize-mbql-clause-tokens x)
(sequential? x)
(mapv #(normalize-tokens % (conj (vec path) ::sequence)) x)
:else
x)
(catch #?(:clj Throwable :cljs js/Error) e
(throw (ex-info (i18n/tru "Error normalizing form: {0}" (ex-message e))
{:form x, :path path, :special-fn special-fn}
e))))))
(defn- wrap-implicit-field-id
"Wrap raw integer Field IDs (i.e., those in an implicit 'field' position) in a `:field` clause if they're not
already. Done for MBQL 95 backwards-compatibility. e.g.:
- > { : filter [: = [ : field 10 nil ] 20 ] } "
[field]
(if (integer? field)
[:field field nil]
field))
(defmulti ^:private canonicalize-mbql-clause
{:arglists '([clause])}
(fn [clause]
(when (mbql-clause? clause)
(first clause))))
(defmethod canonicalize-mbql-clause :default
[clause]
clause)
(defn- canonicalize-implicit-field-id
"If `clause` is a raw integer ID wrap it in a `:field` clause. Either way, canonicalize the resulting clause."
[clause]
(canonicalize-mbql-clause (wrap-implicit-field-id clause)))
(defmethod canonicalize-mbql-clause :field
[[_ id-or-name opts]]
(if (is-clause? :field id-or-name)
(let [[_ nested-id-or-name nested-opts] id-or-name]
(canonicalize-mbql-clause [:field nested-id-or-name (not-empty (merge nested-opts opts))]))
[:field id-or-name (not-empty opts)]))
legacy Field clauses
(defmethod canonicalize-mbql-clause :field-id
[[_ id]]
(if (mbql-clause? id)
(canonicalize-mbql-clause id)
[:field id nil]))
(defmethod canonicalize-mbql-clause :field-literal
[[_ field-name base-type]]
[:field field-name {:base-type base-type}])
(defmethod canonicalize-mbql-clause :fk->
[[_ field-1 field-2]]
(let [[_ source _] (canonicalize-implicit-field-id field-1)
[_ dest dest-opts] (canonicalize-implicit-field-id field-2)]
[:field dest (assoc dest-opts :source-field source)]))
(defmethod canonicalize-mbql-clause :joined-field
[[_ join-alias field]]
(-> (canonicalize-implicit-field-id field)
(mbql.u/assoc-field-options :join-alias join-alias)))
(defmethod canonicalize-mbql-clause :datetime-field
[clause]
(case (count clause)
3
(let [[_ field unit] clause]
(-> (canonicalize-implicit-field-id field)
(mbql.u/with-temporal-unit unit)))
4
(let [[_ field _ unit] clause]
(canonicalize-mbql-clause [:datetime-field field unit]))))
(defmethod canonicalize-mbql-clause :binning-strategy
[[_ field strategy param binning-options]]
(let [[_ id-or-name opts] (canonicalize-implicit-field-id field)]
[:field
id-or-name
(assoc opts :binning (merge {:strategy strategy}
(when param
{strategy param})
binning-options))]))
(defn- canonicalize-compound-filter-clause [[filter-name & args]]
(mbql.u/simplify-compound-filter
(into [filter-name]
we need to canonicalize any other clauses that might show up in args here because
(map canonicalize-mbql-clause args))))
(doseq [clause-name [:and :or :not]]
(defmethod canonicalize-mbql-clause clause-name
[clause]
(canonicalize-compound-filter-clause clause)))
(defmethod canonicalize-mbql-clause :inside
[[_ field-1 field-2 & coordinates]]
(into [:inside
(canonicalize-implicit-field-id field-1)
(canonicalize-implicit-field-id field-2)]
coordinates))
(defmethod canonicalize-mbql-clause :time-interval
[[_ field & args]]
if you specify a ` : temporal - unit ` for the Field inside a ` : time - interval ` , remove it . The unit in
(let [field (cond-> (canonicalize-implicit-field-id field)
(mbql.u/is-clause? :field field) (mbql.u/update-field-options dissoc :temporal-unit))]
(into [:time-interval field] args)))
all the other filter types have an implict field ID for the first arg
( e.g. [: = 10 20 ] gets canonicalized to [: = [ : field - id 10 ] 20 ]
(defn- canonicalize-simple-filter-clause
[[filter-name first-arg & other-args]]
Support legacy expressions like [ :> 1 25 ] where 1 is a field i d.
(into [filter-name (canonicalize-implicit-field-id first-arg)]
(map canonicalize-mbql-clause other-args)))
(doseq [clause-name [:starts-with :ends-with :contains :does-not-contain
:= :!= :< :<= :> :>=
:is-empty :not-empty :is-null :not-null
:between]]
(defmethod canonicalize-mbql-clause clause-name
[clause]
(canonicalize-simple-filter-clause clause)))
aggregations / expression
(defmethod canonicalize-mbql-clause :rows
[_]
nil)
TODO -- if options is empty , should we just unwrap the clause ?
(defmethod canonicalize-mbql-clause :aggregation-options
[[_ wrapped-aggregation-clause options]]
[:aggregation-options (canonicalize-mbql-clause wrapped-aggregation-clause) options])
99.99 % of clauses should have no options , however if they do and ` : use - as - display - name ? ` is false ( default is
(defmethod canonicalize-mbql-clause :named
[[_ wrapped-ag expr-name & more]]
(canonicalize-mbql-clause
[:aggregation-options
(canonicalize-mbql-clause wrapped-ag)
(let [[{:keys [use-as-display-name?]}] more]
(if (false? use-as-display-name?)
{:name expr-name}
{:display-name expr-name}))]))
(defn- canonicalize-count-clause [[clause-name field]]
(if field
[clause-name (canonicalize-implicit-field-id field)]
[clause-name]))
(doseq [clause-name [:count :cum-count]]
(defmethod canonicalize-mbql-clause clause-name
[clause]
(canonicalize-count-clause clause)))
(defn- canonicalize-simple-aggregation-with-field
[[clause-name field]]
[clause-name (canonicalize-implicit-field-id field)])
(doseq [clause-name [:avg :cum-sum :distinct :stddev :sum :min :max :median :var]]
(defmethod canonicalize-mbql-clause clause-name
[clause]
(canonicalize-simple-aggregation-with-field clause)))
(defmethod canonicalize-mbql-clause :percentile
[[_ field percentile]]
[:percentile (canonicalize-implicit-field-id field) percentile])
(defn- canonicalize-filtered-aggregation-clause
[[clause-name filter-subclause]]
[clause-name (canonicalize-mbql-clause filter-subclause)])
(doseq [clause-name [:share :count-where]]
(defmethod canonicalize-mbql-clause clause-name
[clause]
(canonicalize-filtered-aggregation-clause clause)))
(defmethod canonicalize-mbql-clause :sum-where
[[_ field filter-subclause]]
[:sum-where (canonicalize-mbql-clause field) (canonicalize-mbql-clause filter-subclause)])
(defmethod canonicalize-mbql-clause :case
[[_ clauses options]]
(if options
(conj (canonicalize-mbql-clause [:case clauses])
(normalize-tokens options :ignore-path))
[:case (vec (for [[pred expr] clauses]
[(canonicalize-mbql-clause pred) (canonicalize-mbql-clause expr)]))]))
(defn- canonicalize-mbql-clauses
"Walk an `mbql-query` an canonicalize non-top-level clauses like `:fk->`."
[mbql-query]
(walk/prewalk
(fn [x]
(cond
(map? x)
(m/map-vals canonicalize-mbql-clauses x)
(not (mbql-clause? x))
x
:else
(try
(canonicalize-mbql-clause x)
(catch #?(:clj Throwable :cljs js/Error) e
(log/error (i18n/tru "Invalid clause:") x)
(throw (ex-info (i18n/tru "Invalid MBQL clause: {0}" (ex-message e))
{:clause x}
e))))))
mbql-query))
(defn- wrap-single-aggregations
"Convert old MBQL 95 single-aggregations like `{:aggregation :count}` or `{:aggregation [:count]}` to MBQL 98+
multiple-aggregation syntax (e.g. `{:aggregation [[:count]]}`)."
[aggregations]
(mbql.match/replace aggregations
seq? (recur (vec &match))
something like { : aggregations : count } -- MBQL 95 single aggregation
keyword?
[[&match]]
special - case : MBQL 98 multiple aggregations using unwrapped : count or : rows
e.g. { : aggregations [: count [: sum 10 ] ] } or { : aggregations [: count : count ] }
[(_ :guard (every-pred keyword? (complement #{:named :+ :- :* :/})))
(_ :guard aggregation-subclause?)
& _]
(vec (reduce concat (map wrap-single-aggregations aggregations)))
something like { : aggregations [: sum 10 ] } -- MBQL 95 single aggregation
[(_ :guard keyword?) & _]
[&match]
_
&match))
(defn- canonicalize-aggregations
"Canonicalize subclauses (see above) and make sure `:aggregation` is a sequence of clauses instead of a single
clause."
[aggregations]
(->> (wrap-single-aggregations aggregations)
(keep canonicalize-mbql-clauses)
vec))
(defn- canonicalize-breakouts [breakouts]
(if (mbql-clause? breakouts)
(recur [breakouts])
(not-empty (mapv wrap-implicit-field-id breakouts))))
(defn- canonicalize-order-by
"Make sure order by clauses like `[:asc 10]` get `:field-id` added where appropriate, e.g. `[:asc [:field-id 10]]`"
[clauses]
(mbql.match/replace clauses
seq? (recur (vec &match))
[field :asc] (recur [:asc field])
[field :desc] (recur [:desc field])
[field :ascending] (recur [:asc field])
[field :descending] (recur [:desc field])
MBQL 95 names but MBQL 98 + reversed syntax
[:ascending field] (recur [:asc field])
[:descending field] (recur [:desc field])
[:asc field] [:asc (canonicalize-implicit-field-id field)]
[:desc field] [:desc (canonicalize-implicit-field-id field)]
this case should be the first one hit when we come in with a vector of clauses e.g. [ [: asc 1 ] [: desc 2 ] ]
[& clauses] (vec (distinct (map canonicalize-order-by clauses)))))
(declare canonicalize-inner-mbql-query)
(defn- canonicalize-template-tag [{:keys [dimension], :as tag}]
(cond-> tag
dimension (update :dimension canonicalize-mbql-clause)))
(defn- canonicalize-template-tags [tags]
(into {} (for [[tag-name tag] tags]
[tag-name (canonicalize-template-tag tag)])))
(defn- canonicalize-native-query [{:keys [template-tags], :as native-query}]
(cond-> native-query
template-tags (update :template-tags canonicalize-template-tags)))
(defn- canonicalize-source-query [{native? :native, :as source-query}]
(cond-> source-query
(not native?) canonicalize-inner-mbql-query
native? canonicalize-native-query))
(defn- non-empty? [x]
(if (coll? x)
(seq x)
(some? x)))
(defn- canonicalize-top-level-mbql-clauses
"Perform specific steps to canonicalize the various top-level clauses in an MBQL query."
[mbql-query]
(cond-> mbql-query
(non-empty? (:aggregation mbql-query)) (update :aggregation canonicalize-aggregations)
(non-empty? (:breakout mbql-query)) (update :breakout canonicalize-breakouts)
(non-empty? (:fields mbql-query)) (update :fields (partial mapv wrap-implicit-field-id))
(non-empty? (:order-by mbql-query)) (update :order-by canonicalize-order-by)
(non-empty? (:source-query mbql-query)) (update :source-query canonicalize-source-query)))
(def ^:private ^{:arglists '([query])} canonicalize-inner-mbql-query
(comp canonicalize-mbql-clauses canonicalize-top-level-mbql-clauses))
(defn- move-source-metadata-to-mbql-query
"In Metabase 0.33.0 `:source-metadata` about resolved queries is added to the 'inner' MBQL query rather than to the
[{:keys [source-metadata], :as query}]
(-> query
(dissoc :source-metadata)
(assoc-in [:query :source-metadata] source-metadata)))
(defn- canonicalize
"Canonicalize a query [MBQL query], rewriting the query as if you perfectly followed the recommended style guides for
writing MBQL. Does things like removes unneeded and empty clauses, converts older MBQL '95 syntax to MBQL '98, etc."
[{:keys [query parameters source-metadata native], :as outer-query}]
(try
(cond-> outer-query
source-metadata move-source-metadata-to-mbql-query
query (update :query canonicalize-inner-mbql-query)
parameters (update :parameters (partial mapv canonicalize-mbql-clauses))
native (update :native canonicalize-native-query)
true canonicalize-mbql-clauses)
(catch #?(:clj Throwable :cljs js/Error) e
(throw (ex-info (i18n/tru "Error canonicalizing query: {0}" (ex-message e))
{:query query}
e)))))
(defn- remove-breakout-fields-from-fields
it is implied that any breakout Field
will be returned, specifying it in both would imply it is to be returned twice, which tends to cause confusion for
I'm not sure this behavior makes sense, but removing it would break existing queries.)
We will remove either exact matches:
or unbucketed matches:
{:breakout [[:datetime-field [:field-id 10] :month]], :fields [[:field-id 10]]}
[{{:keys [breakout fields]} :query, :as query}]
(if-not (and (seq breakout) (seq fields))
query
get a set of all Field clauses ( of any type ) in the breakout . For temporal - bucketed fields , we 'll include both
(let [breakout-fields (set (reduce concat (mbql.match/match breakout
[:field id-or-name opts]
[&match
[:field id-or-name (dissoc opts :temporal-unit)]])))]
now remove all the Fields in ` : fields ` that match the ones in the set
(update-in query [:query :fields] (comp vec (partial remove breakout-fields))))))
(defn- perform-whole-query-transformations
"Perform transformations that operate on the query as a whole, making sure the structure as a whole is logical and
consistent."
[query]
(try
(remove-breakout-fields-from-fields query)
(catch #?(:clj Throwable :cljs js/Error) e
(throw (ex-info (i18n/tru "Error performing whole query transformations")
{:query query}
e)))))
| REMOVING EMPTY CLAUSES |
(declare remove-empty-clauses)
(defn- remove-empty-clauses-in-map [m path]
(let [m (into (empty m) (for [[k v] m
:let [v (remove-empty-clauses v (conj path k))]
:when (some? v)]
[k v]))]
(when (seq m)
m)))
(defn- remove-empty-clauses-in-sequence [xs path]
(let [xs (mapv #(remove-empty-clauses % (conj path ::sequence))
xs)]
(when (some some? xs)
xs)))
(defn- remove-empty-clauses-in-join [join]
(remove-empty-clauses join [:query]))
(defn- remove-empty-clauses-in-source-query [{native? :native, :as source-query}]
(if native?
(-> source-query
(set/rename-keys {:native :query})
(remove-empty-clauses [:native])
(set/rename-keys {:query :native}))
(remove-empty-clauses source-query [:query])))
(def ^:private path->special-remove-empty-clauses-fn
{:native identity
:query {:source-query remove-empty-clauses-in-source-query
:joins {::sequence remove-empty-clauses-in-join}}
:viz-settings identity})
(defn- remove-empty-clauses
"Remove any empty or `nil` clauses in a query."
([query]
(remove-empty-clauses query []))
([x path]
(try
(let [special-fn (when (seq path)
(get-in path->special-remove-empty-clauses-fn path))]
(cond
(fn? special-fn) (special-fn x)
(record? x) x
(map? x) (remove-empty-clauses-in-map x path)
(sequential? x) (remove-empty-clauses-in-sequence x path)
:else x))
(catch #?(:clj Throwable :cljs js/Error) e
(throw (ex-info "Error removing empty clauses from form."
{:form x, :path path}
e))))))
(def ^{:arglists '([outer-query])} normalize
"Normalize the tokens in a Metabase query (i.e., make them all `lisp-case` keywords), rewrite deprecated clauses as
up-to-date MBQL 2000, and remove empty clauses."
(let [normalize* (comp remove-empty-clauses
perform-whole-query-transformations
canonicalize
normalize-tokens)]
(fn [query]
(try
(normalize* query)
(catch #?(:clj Throwable :cljs js/Error) e
(throw (ex-info (i18n/tru "Error normalizing query: {0}" (ex-message e))
{:query query}
e)))))))
(defn normalize-fragment
"Normalize just a specific fragment of a query, such as just the inner MBQL part or just a filter clause. `path` is
where this fragment would normally live in a full query.
(normalize-fragment [:query :filter] [\"=\" 100 200])
- > [: = [ : field - id 100 ] 200 ] "
{:style/indent 1}
[path x]
(if-not (seq path)
(normalize x)
(get (normalize-fragment (butlast path) {(last path) x}) (last path))))
|
d37fe3af3cb7087aa2b08ed58822af995bcb9b2829fa5aa135a2e0049bbb1efa | vituscze/norri | Context.hs | -- | Contexts used during type inference - kind contexts, typing contexts,
-- error location contexts and type signature contexts.
module Compiler.TypeChecking.Context
(
-- * Kinds
Kind
, KindCtx
-- * Types
, TyCtx
-- * Type signatures
, SigCtx
-- * Error location context
, ErrCtx
-- * Type inference context
, TICtx(..)
)
where
import Data.Map (Map)
import Compiler.AST
import Compiler.TypeChecking.Error
-- | The type for kinds.
--
-- Since the only possible kinds are of the form @* -> * -> ... -> *@,
-- we can just store their arity.
type Kind = Int
-- | Kind context.
--
-- Used for kind checking of data definitions and user-declared types.
-- Internal types have correct kind by construction.
type KindCtx = Map TyName Kind
-- | Typing context.
type TyCtx = Map Name Scheme
-- | Declared type signatures.
type SigCtx = Map Name Scheme
-- | Error location.
type ErrCtx = Location
-- | All contexts needed for type inference.
--
-- This contains kind context, type context and type signature context.
data TICtx
= TICtx
{ kindCtx :: KindCtx
, typeCtx :: TyCtx
, sigCtx :: SigCtx
}
deriving (Eq, Show)
| null | https://raw.githubusercontent.com/vituscze/norri/133aef0b42b2c5bdd789ce2fa2655aecfcb96424/src/Compiler/TypeChecking/Context.hs | haskell | | Contexts used during type inference - kind contexts, typing contexts,
error location contexts and type signature contexts.
* Kinds
* Types
* Type signatures
* Error location context
* Type inference context
| The type for kinds.
Since the only possible kinds are of the form @* -> * -> ... -> *@,
we can just store their arity.
| Kind context.
Used for kind checking of data definitions and user-declared types.
Internal types have correct kind by construction.
| Typing context.
| Declared type signatures.
| Error location.
| All contexts needed for type inference.
This contains kind context, type context and type signature context. | module Compiler.TypeChecking.Context
(
Kind
, KindCtx
, TyCtx
, SigCtx
, ErrCtx
, TICtx(..)
)
where
import Data.Map (Map)
import Compiler.AST
import Compiler.TypeChecking.Error
type Kind = Int
type KindCtx = Map TyName Kind
type TyCtx = Map Name Scheme
type SigCtx = Map Name Scheme
type ErrCtx = Location
data TICtx
= TICtx
{ kindCtx :: KindCtx
, typeCtx :: TyCtx
, sigCtx :: SigCtx
}
deriving (Eq, Show)
|
a5fd36784a97f97c91c93a4f11b9c8fc2693328130219d8ce5462a9c0ec60051 | aumouvantsillage/Virgule-CPU-Racket | device.rkt | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
#lang racket
(require
syntax/parse/define
"signal.rkt")
(provide (all-defined-out))
(struct device (start-address size))
(define (device-size-in-words dev)
(ceiling (/ (device-size dev) 4)))
(define (device-end-address dev)
(+ (device-start-address dev) (device-size dev) -1))
(define (device-accepts? dev address)
(<= (device-start-address dev) address (device-end-address dev)))
(define (device-address* dev address)
(modulo (- address (device-start-address dev))
(device-size dev)))
(define (device-word-address* dev address)
(quotient (device-address* dev address) 4))
(define (device-valid dev valid address)
(for/signal (valid address)
(and valid (device-accepts? dev address))))
(define (device-address dev address)
(for/signal (address)
(device-address* dev address)))
(define (device-word-address dev address)
(for/signal (address)
(device-word-address* dev address)))
(define-simple-macro (device-ready-rdata valid address (dev dev-ready dev-rdata) ...)
(values
(for/signal (valid address dev-ready ...)
(and valid
(cond [(device-accepts? dev address) (and valid dev-ready)]
...
[else valid])))
(for/signal (valid address dev-rdata ...)
(cond [(device-accepts? dev address) dev-rdata]
...
[else 0]))))
| null | https://raw.githubusercontent.com/aumouvantsillage/Virgule-CPU-Racket/47348d9e3a211560fc9d7a59c49d6d250d2369c5/src/device.rkt | racket | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
#lang racket
(require
syntax/parse/define
"signal.rkt")
(provide (all-defined-out))
(struct device (start-address size))
(define (device-size-in-words dev)
(ceiling (/ (device-size dev) 4)))
(define (device-end-address dev)
(+ (device-start-address dev) (device-size dev) -1))
(define (device-accepts? dev address)
(<= (device-start-address dev) address (device-end-address dev)))
(define (device-address* dev address)
(modulo (- address (device-start-address dev))
(device-size dev)))
(define (device-word-address* dev address)
(quotient (device-address* dev address) 4))
(define (device-valid dev valid address)
(for/signal (valid address)
(and valid (device-accepts? dev address))))
(define (device-address dev address)
(for/signal (address)
(device-address* dev address)))
(define (device-word-address dev address)
(for/signal (address)
(device-word-address* dev address)))
(define-simple-macro (device-ready-rdata valid address (dev dev-ready dev-rdata) ...)
(values
(for/signal (valid address dev-ready ...)
(and valid
(cond [(device-accepts? dev address) (and valid dev-ready)]
...
[else valid])))
(for/signal (valid address dev-rdata ...)
(cond [(device-accepts? dev address) dev-rdata]
...
[else 0]))))
|
|
41023c7a71dd4b8d3e002a4006b893b9a87a8a2e80785bdd676b3b6fd472cedd | OCamlPro/typerex-lint | lint_init_dynload.ml | (**************************************************************************)
(* *)
(* OCamlPro Typerex *)
(* *)
Copyright OCamlPro 2011 - 2016 . All rights reserved .
(* This file is distributed under the terms of the GPL v3.0 *)
( GNU General Public Licence version 3.0 ) .
(* *)
(* Contact: <> (/) *)
(* *)
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. *)
(**************************************************************************)
let init () =
Core modules
List.iter (Findlib.record_package Findlib.Record_core)
[ "findlib";
"dynlink";
"findlib.dynload";
"compiler-libs.common";
"unix";
"str";
"ocplib-unix";
"ocp-lint-output";
"ocp-lint-config";
"ocp-lint-db";
"ocp-lint-init";
"ocp-lint-utils"];
#if OCAML_VERSION >= "4.04.0"
(match Sys.backend_type with
| Sys.Native ->
Findlib.record_package_predicates
["pkg_findlib";"pkg_dynlink";"pkg_findlib.dynload";"autolink";"native"]
| Sys.Bytecode ->
Dynlink.allow_unsafe_modules true;
Findlib.record_package_predicates
["pkg_findlib";"pkg_dynlink";"pkg_findlib.dynload";"autolink";"byte"]
| Sys.Other str -> ())
#else
Findlib.record_package_predicates
["pkg_findlib";"pkg_dynlink";"pkg_findlib.dynload";"autolink";"native"]
#endif
| null | https://raw.githubusercontent.com/OCamlPro/typerex-lint/6d9e994c8278fb65e1f7de91d74876531691120c/tools/ocp-lint/main/lint_init_dynload.ml | ocaml | ************************************************************************
OCamlPro Typerex
This file is distributed under the terms of the GPL v3.0
Contact: <> (/)
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
************************************************************************ | Copyright OCamlPro 2011 - 2016 . All rights reserved .
( GNU General Public Licence version 3.0 ) .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
let init () =
Core modules
List.iter (Findlib.record_package Findlib.Record_core)
[ "findlib";
"dynlink";
"findlib.dynload";
"compiler-libs.common";
"unix";
"str";
"ocplib-unix";
"ocp-lint-output";
"ocp-lint-config";
"ocp-lint-db";
"ocp-lint-init";
"ocp-lint-utils"];
#if OCAML_VERSION >= "4.04.0"
(match Sys.backend_type with
| Sys.Native ->
Findlib.record_package_predicates
["pkg_findlib";"pkg_dynlink";"pkg_findlib.dynload";"autolink";"native"]
| Sys.Bytecode ->
Dynlink.allow_unsafe_modules true;
Findlib.record_package_predicates
["pkg_findlib";"pkg_dynlink";"pkg_findlib.dynload";"autolink";"byte"]
| Sys.Other str -> ())
#else
Findlib.record_package_predicates
["pkg_findlib";"pkg_dynlink";"pkg_findlib.dynload";"autolink";"native"]
#endif
|
1e8c88094d2856b3c841e015d65d483d4daaa9ed90bbcc1cf37d6a18e2abdf83 | sellout/haskerwaul | Laws.hs | module Haskerwaul.Lattice.Laws where
import Haskerwaul.Category.Monoidal.Cartesian
import Haskerwaul.Semilattice.Laws
import Haskerwaul.Lattice
data LatticeLaws c a =
LatticeLaws
{ meetSemilattice :: SemilatticeLaws c (Meet a)
, joinSemilattice :: SemilatticeLaws c (Join a)
}
latticeLaws ::
(CartesianMonoidalCategory c, Lattice c (Prod c) a) => LatticeLaws c a
latticeLaws =
LatticeLaws
{ meetSemilattice = semilatticeLaws
, joinSemilattice = semilatticeLaws
}
| null | https://raw.githubusercontent.com/sellout/haskerwaul/cdd4a61c6abe0f757e32058f4832cf616025b45f/src/Haskerwaul/Lattice/Laws.hs | haskell | module Haskerwaul.Lattice.Laws where
import Haskerwaul.Category.Monoidal.Cartesian
import Haskerwaul.Semilattice.Laws
import Haskerwaul.Lattice
data LatticeLaws c a =
LatticeLaws
{ meetSemilattice :: SemilatticeLaws c (Meet a)
, joinSemilattice :: SemilatticeLaws c (Join a)
}
latticeLaws ::
(CartesianMonoidalCategory c, Lattice c (Prod c) a) => LatticeLaws c a
latticeLaws =
LatticeLaws
{ meetSemilattice = semilatticeLaws
, joinSemilattice = semilatticeLaws
}
|
|
6d7e73ff8929381603481226135cec6521aea817957f39a3a915ec141dbfa3f7 | xapi-project/message-switch | data_source.ml |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
type t = {
name: string
; description: string
; enabled: bool
; standard: bool
; min: float
; max: float
; units: string
}
[@@deriving rpcty]
let to_key_value_map ds =
[
("name_label", ds.name)
; ("name_description", ds.description)
; ("enabled", string_of_bool ds.enabled)
; ("standard", string_of_bool ds.standard)
; ("min", string_of_float ds.min)
; ("max", string_of_float ds.max)
; ("units", ds.units)
]
| null | https://raw.githubusercontent.com/xapi-project/message-switch/1d0d1aa45c01eba144ac2826d0d88bb663e33101/xapi-idl/rrd/data_source.ml | ocaml |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
type t = {
name: string
; description: string
; enabled: bool
; standard: bool
; min: float
; max: float
; units: string
}
[@@deriving rpcty]
let to_key_value_map ds =
[
("name_label", ds.name)
; ("name_description", ds.description)
; ("enabled", string_of_bool ds.enabled)
; ("standard", string_of_bool ds.standard)
; ("min", string_of_float ds.min)
; ("max", string_of_float ds.max)
; ("units", ds.units)
]
|
|
2a199f9e98e30b656fb1b1369e72f93984ca51bc369f96ac7f613b005a098b4f | ChrisTitusTech/gimphelp | 210_Shapes_circle-create.scm | 210_Shapes_circle-creator.scm
last modified / tested by [ gimphelp.org ]
05/11/2019 on GIMP 2.10.10
;==================================================
;
; Installation:
; This script should be placed in the user or system-wide script folder.
;
; Windows 7/10
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
; or
C:\Users\YOUR - NAME\AppData\Roaming\GIMP\2.10\scripts
;
;
; Linux
; /home/yourname/.config/GIMP/2.10/scripts
; or
; Linux system-wide
; /usr/share/gimp/2.0/scripts
;
;==================================================
;
; LICENSE
;
; 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 </>.
;
;==============================================================
; Original information
;
( c)2010 by
; uploaded to gimphelp.org
;
; initial idea based upon:
; Plugin : draw-circle.scm
Author : Arch .
;==============================================================
(define (210-circle-creator image layer Radius FeatherRadius isSolid circlethick sfcolor)
(let* (
(sx 0)
(sy 0)
(diameter 0)
(dx 0)
(dy 0)
(image-width (car (gimp-drawable-width layer)))
(image-height (car (gimp-drawable-height layer)))
(center-x (/ image-width 2))
(center-y (/ image-height 2))
(layer1 '())
)
; make sure thickness of circle outline is not larger than the radius
; just knock it down rather than bother the user...
(while (> circlethick Radius)
(set! circlethick (- circlethick 1))
)
; make sure radius fits inside image (width then height)
(while (>= Radius (- center-x 2))
(set! Radius (- Radius 1))
)
(while (>= Radius (- center-y 2))
(set! Radius (- Radius 1))
)
; since size is now asured to fit in the image,
; we can now center it in the image, since circle will be on it' own layer,
; dragging it where wanted is easier than setting x and y coordinates.
(set! sx (- center-x Radius))
(set! sy (- center-y Radius))
(set! diameter (* Radius 2))
(set! dx diameter)
(set! dy diameter)
(set! layer1 (car (gimp-layer-copy layer 1)))
(gimp-image-undo-group-start image)
(gimp-image-insert-layer image layer1 0 -1)
(gimp-image-set-active-layer image layer1)
(gimp-edit-clear layer1)
(gimp-image-select-ellipse image CHANNEL-OP-REPLACE sx sy dx dy)
(gimp-context-set-foreground sfcolor)
(gimp-edit-fill layer1 0)
; punch appropriate-size hole in circle, if not solid
(if (not (= isSolid 1))
(begin
(gimp-selection-shrink image circlethick)
(gimp-edit-cut layer1)))
(gimp-selection-none image)
(plug-in-autocrop-layer 1 image layer1)
; tidy up
(gimp-image-undo-group-end image)
(gimp-displays-flush)
) ;;let
) ;;def
(script-fu-register
"210-circle-creator"
"Circle Draw"
"Draw a circle"
"Paul Sherman"
"Paul Sherman"
"15 October 2010"
"*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Layer" 0
SF-ADJUSTMENT "Radius" '(16 0 9999 1 10 0 1)
SF-ADJUSTMENT "Feather Edge" '(1 0 9999 1 10 0 1)
SF-TOGGLE "\nSolid Circle?\n" FALSE
SF-ADJUSTMENT "Circle Thickness (used if not solid)" '(1 0 200 1 10 0 1)
SF-COLOR "SF-COLOR" '(0 0 0)
)
(script-fu-menu-register "210-circle-creator" "<Image>/Script-Fu/Shapes")
| null | https://raw.githubusercontent.com/ChrisTitusTech/gimphelp/fdbc7e3671ce6bd74cefd83ecf7216e5ee0f1542/gimp_scripts-2.10/210_Shapes_circle-create.scm | scheme | ==================================================
Installation:
This script should be placed in the user or system-wide script folder.
Windows 7/10
or
Linux
/home/yourname/.config/GIMP/2.10/scripts
or
Linux system-wide
/usr/share/gimp/2.0/scripts
==================================================
LICENSE
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 </>.
==============================================================
Original information
uploaded to gimphelp.org
initial idea based upon:
Plugin : draw-circle.scm
==============================================================
make sure thickness of circle outline is not larger than the radius
just knock it down rather than bother the user...
make sure radius fits inside image (width then height)
since size is now asured to fit in the image,
we can now center it in the image, since circle will be on it' own layer,
dragging it where wanted is easier than setting x and y coordinates.
punch appropriate-size hole in circle, if not solid
tidy up
let
def | 210_Shapes_circle-creator.scm
last modified / tested by [ gimphelp.org ]
05/11/2019 on GIMP 2.10.10
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
C:\Users\YOUR - NAME\AppData\Roaming\GIMP\2.10\scripts
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
( c)2010 by
Author : Arch .
(define (210-circle-creator image layer Radius FeatherRadius isSolid circlethick sfcolor)
(let* (
(sx 0)
(sy 0)
(diameter 0)
(dx 0)
(dy 0)
(image-width (car (gimp-drawable-width layer)))
(image-height (car (gimp-drawable-height layer)))
(center-x (/ image-width 2))
(center-y (/ image-height 2))
(layer1 '())
)
(while (> circlethick Radius)
(set! circlethick (- circlethick 1))
)
(while (>= Radius (- center-x 2))
(set! Radius (- Radius 1))
)
(while (>= Radius (- center-y 2))
(set! Radius (- Radius 1))
)
(set! sx (- center-x Radius))
(set! sy (- center-y Radius))
(set! diameter (* Radius 2))
(set! dx diameter)
(set! dy diameter)
(set! layer1 (car (gimp-layer-copy layer 1)))
(gimp-image-undo-group-start image)
(gimp-image-insert-layer image layer1 0 -1)
(gimp-image-set-active-layer image layer1)
(gimp-edit-clear layer1)
(gimp-image-select-ellipse image CHANNEL-OP-REPLACE sx sy dx dy)
(gimp-context-set-foreground sfcolor)
(gimp-edit-fill layer1 0)
(if (not (= isSolid 1))
(begin
(gimp-selection-shrink image circlethick)
(gimp-edit-cut layer1)))
(gimp-selection-none image)
(plug-in-autocrop-layer 1 image layer1)
(gimp-image-undo-group-end image)
(gimp-displays-flush)
(script-fu-register
"210-circle-creator"
"Circle Draw"
"Draw a circle"
"Paul Sherman"
"Paul Sherman"
"15 October 2010"
"*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Layer" 0
SF-ADJUSTMENT "Radius" '(16 0 9999 1 10 0 1)
SF-ADJUSTMENT "Feather Edge" '(1 0 9999 1 10 0 1)
SF-TOGGLE "\nSolid Circle?\n" FALSE
SF-ADJUSTMENT "Circle Thickness (used if not solid)" '(1 0 200 1 10 0 1)
SF-COLOR "SF-COLOR" '(0 0 0)
)
(script-fu-menu-register "210-circle-creator" "<Image>/Script-Fu/Shapes")
|
55bd94c7968e960c61e9a2db9d66968975e74fe27e3e81a73f8422a9a41f05f7 | waxeye-org/waxeye | gen.rkt | ;; Waxeye Parser Generator
;; www.waxeye.org
Copyright ( C ) 2008 - 2010 Orlando Hill
Licensed under the MIT license . See ' LICENSE ' for details .
#lang racket/base
(require waxeye/ast)
(provide (all-defined-out))
(define *eof-check* #t)
(define *expression-level* '())
(define *file-header* #f)
(define *module-name* #f)
(define *name-prefix* #f)
(define *start-index* 0)
(define *start-name* "")
(define (eof-check! val)
(set! *eof-check* val))
(define (file-header! val)
(set! *file-header* val))
(define (module-name! val)
(set! *module-name* val))
(define (name-prefix! val)
(set! *name-prefix* val))
(define (start-index! val)
(set! *start-index* val))
(define (start-name! val)
(set! *start-name* val))
(define (start-nt! name grammar)
; This method exists in racket/list since Racket v6.7,
but we 're compatible with the Racket version in the latest Ubuntu LTS ( v6.4 as of this comment ) .
(define (index-of ls v)
(let loop ([ls ls]
[i 0])
(cond [(null? ls) #f]
[(equal? (car ls) v) i]
[else (loop (cdr ls) (add1 i))])))
(set! *start-name* name)
(if (equal? name "")
(start-name! (get-non-term (car (get-defs grammar))))
(let ([si (index-of (map get-non-term (get-defs grammar)) name)])
(if si
(start-index! si)
(error 'waxeye (format "Can't find definition of starting non-terminal: ~a" *start-name*))))))
(define (push-exp-level level)
(set! *expression-level* (cons level *expression-level*)))
(define (pop-exp-level)
(let ((top (car *expression-level*)))
(set! *expression-level* (cdr *expression-level*))
top))
(define (peek-exp-level)
(car *expression-level*))
(define (get-non-terms grammar)
(map get-non-term (ast-c grammar)))
(define (get-non-term def)
(list->string (ast-c (car (ast-c def)))))
(define (get-defs grammar)
(ast-c grammar))
(define (get-arrow def)
(ast-t (cadr (ast-c def))))
(define (get-alternation def)
(caddr (ast-c def)))
| null | https://raw.githubusercontent.com/waxeye-org/waxeye/723da0475fc0c8e3dd43da46665ef7c62734857b/src/waxeye/gen.rkt | racket | Waxeye Parser Generator
www.waxeye.org
This method exists in racket/list since Racket v6.7, | Copyright ( C ) 2008 - 2010 Orlando Hill
Licensed under the MIT license . See ' LICENSE ' for details .
#lang racket/base
(require waxeye/ast)
(provide (all-defined-out))
(define *eof-check* #t)
(define *expression-level* '())
(define *file-header* #f)
(define *module-name* #f)
(define *name-prefix* #f)
(define *start-index* 0)
(define *start-name* "")
(define (eof-check! val)
(set! *eof-check* val))
(define (file-header! val)
(set! *file-header* val))
(define (module-name! val)
(set! *module-name* val))
(define (name-prefix! val)
(set! *name-prefix* val))
(define (start-index! val)
(set! *start-index* val))
(define (start-name! val)
(set! *start-name* val))
(define (start-nt! name grammar)
but we 're compatible with the Racket version in the latest Ubuntu LTS ( v6.4 as of this comment ) .
(define (index-of ls v)
(let loop ([ls ls]
[i 0])
(cond [(null? ls) #f]
[(equal? (car ls) v) i]
[else (loop (cdr ls) (add1 i))])))
(set! *start-name* name)
(if (equal? name "")
(start-name! (get-non-term (car (get-defs grammar))))
(let ([si (index-of (map get-non-term (get-defs grammar)) name)])
(if si
(start-index! si)
(error 'waxeye (format "Can't find definition of starting non-terminal: ~a" *start-name*))))))
(define (push-exp-level level)
(set! *expression-level* (cons level *expression-level*)))
(define (pop-exp-level)
(let ((top (car *expression-level*)))
(set! *expression-level* (cdr *expression-level*))
top))
(define (peek-exp-level)
(car *expression-level*))
(define (get-non-terms grammar)
(map get-non-term (ast-c grammar)))
(define (get-non-term def)
(list->string (ast-c (car (ast-c def)))))
(define (get-defs grammar)
(ast-c grammar))
(define (get-arrow def)
(ast-t (cadr (ast-c def))))
(define (get-alternation def)
(caddr (ast-c def)))
|
0de34704a3940ec34ba1a769c5ba94977d87d01b91f851e13176bbcb9700ed61 | nvim-treesitter/nvim-treesitter | highlights.scm | (symbol) @variable
(label name: (symbol) @label)
[
(instruction_mnemonic)
(directive_mnemonic)
] @function.builtin
(include (directive_mnemonic) @include)
(include_bin (directive_mnemonic) @include)
(include_dir (directive_mnemonic) @include)
(size) @attribute
(macro_definition name: (symbol) @function.macro)
(macro_call name: (symbol) @function.macro)
[
(path)
(string_literal)
] @string
[
(decimal_literal)
(hexadecimal_literal)
(octal_literal)
(binary_literal)
] @number
[
(reptn)
(carg)
(narg)
(macro_arg)
] @variable.builtin
[
(control_mnemonic)
(address_register)
(data_register)
(float_register)
(named_register)
] @keyword
(repeat (control_mnemonic) @repeat)
(conditional (control_mnemonic) @conditional)
(comment) @comment
[
(operator)
"="
"#"
] @operator
[
"."
","
"/"
"-"
] @punctuation.delimiter
[
"("
")"
")+"
] @punctuation.bracket
(section) @namespace
| null | https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/9fdd6765fc05632c2f3af1ad825dc4e9cc0b041f/queries/m68k/highlights.scm | scheme | (symbol) @variable
(label name: (symbol) @label)
[
(instruction_mnemonic)
(directive_mnemonic)
] @function.builtin
(include (directive_mnemonic) @include)
(include_bin (directive_mnemonic) @include)
(include_dir (directive_mnemonic) @include)
(size) @attribute
(macro_definition name: (symbol) @function.macro)
(macro_call name: (symbol) @function.macro)
[
(path)
(string_literal)
] @string
[
(decimal_literal)
(hexadecimal_literal)
(octal_literal)
(binary_literal)
] @number
[
(reptn)
(carg)
(narg)
(macro_arg)
] @variable.builtin
[
(control_mnemonic)
(address_register)
(data_register)
(float_register)
(named_register)
] @keyword
(repeat (control_mnemonic) @repeat)
(conditional (control_mnemonic) @conditional)
(comment) @comment
[
(operator)
"="
"#"
] @operator
[
"."
","
"/"
"-"
] @punctuation.delimiter
[
"("
")"
")+"
] @punctuation.bracket
(section) @namespace
|
|
348e9dbead8cfd269c10c7569a9397488c0495286d40597301bb84df8d2ec7af | okuoku/nausicaa | proof-makers.sps | -*- coding : utf-8 - unix -*-
;;;
Part of : / Scheme
;;;Contents: proof for makers
Date : Sat May 22 , 2010
;;;
;;;Abstract
;;;
;;;
;;;
Copyright ( c ) 2010 < >
;;;
;;;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 </>.
;;;
#!r6rs
(import (rnrs)
(nausicaa language makers))
(define check-count 0)
(define check-success-count 0)
(define check-failure-count 0)
(define-syntax check
(syntax-rules (=>)
((_ ?expr => ?expected-result)
(check ?expr (=> equal?) ?expected-result))
((_ ?expr (=> ?equal) ?expected-result)
(let ((result ?expr)
(expected ?expected-result))
(set! check-count (+ 1 check-count))
(if (?equal result expected)
(set! check-success-count (+ 1 check-success-count))
(begin
(set! check-failure-count (+ 1 check-failure-count))
(display "test error, expected\n\n")
(write expected)
(newline)
(display "\ngot:\n\n")
(write result)
(newline)
(display "\ntest body:\n\n")
(write '(check ?expr (=> ?equal) ?expected-result))
(newline)))))
))
(define (check-report)
(display (string-append "*** executed " (number->string check-count)
" tests, successful: " (number->string check-success-count)
", failed: "(number->string check-failure-count) "\n")))
(define-maker doit
list ((alpha 1)
(beta 2)
(gamma 3)))
(check
(doit)
=> '(1 2 3))
(check
(doit (alpha 10))
=> '(10 2 3))
(check
(doit (beta 20))
=> '(1 20 3))
(check
(doit (gamma 30))
=> '(1 2 30))
(check
(doit (alpha 10)
(beta 20))
=> '(10 20 3))
(check
(doit (alpha 10)
(gamma 30))
=> '(10 2 30))
(check
(doit (gamma 30)
(beta 20))
=> '(1 20 30))
(check
(doit (alpha 10)
(beta 20)
(gamma 30))
=> '(10 20 30))
(check
(let ((b 7))
(doit (beta (+ 6 (* 2 b)))
(alpha (+ 2 8))))
=> '(10 20 3))
(check-report)
;;; end of file
| null | https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/scheme/proofs/proof-makers.sps | scheme |
Contents: proof for makers
Abstract
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
along with this program. If not, see </>.
end of file | -*- coding : utf-8 - unix -*-
Part of : / Scheme
Date : Sat May 22 , 2010
Copyright ( c ) 2010 < >
the Free Software Foundation , either version 3 of the License , or ( at
General Public License for more details .
You should have received a copy of the GNU General Public License
#!r6rs
(import (rnrs)
(nausicaa language makers))
(define check-count 0)
(define check-success-count 0)
(define check-failure-count 0)
(define-syntax check
(syntax-rules (=>)
((_ ?expr => ?expected-result)
(check ?expr (=> equal?) ?expected-result))
((_ ?expr (=> ?equal) ?expected-result)
(let ((result ?expr)
(expected ?expected-result))
(set! check-count (+ 1 check-count))
(if (?equal result expected)
(set! check-success-count (+ 1 check-success-count))
(begin
(set! check-failure-count (+ 1 check-failure-count))
(display "test error, expected\n\n")
(write expected)
(newline)
(display "\ngot:\n\n")
(write result)
(newline)
(display "\ntest body:\n\n")
(write '(check ?expr (=> ?equal) ?expected-result))
(newline)))))
))
(define (check-report)
(display (string-append "*** executed " (number->string check-count)
" tests, successful: " (number->string check-success-count)
", failed: "(number->string check-failure-count) "\n")))
(define-maker doit
list ((alpha 1)
(beta 2)
(gamma 3)))
(check
(doit)
=> '(1 2 3))
(check
(doit (alpha 10))
=> '(10 2 3))
(check
(doit (beta 20))
=> '(1 20 3))
(check
(doit (gamma 30))
=> '(1 2 30))
(check
(doit (alpha 10)
(beta 20))
=> '(10 20 3))
(check
(doit (alpha 10)
(gamma 30))
=> '(10 2 30))
(check
(doit (gamma 30)
(beta 20))
=> '(1 20 30))
(check
(doit (alpha 10)
(beta 20)
(gamma 30))
=> '(10 20 30))
(check
(let ((b 7))
(doit (beta (+ 6 (* 2 b)))
(alpha (+ 2 8))))
=> '(10 20 3))
(check-report)
|
b683a0e73dd16af9d580a982831750c76c1ee046a99dcc774d6fe75915e79a68 | camllight/camllight | syntaxe.mli | type constante =
Entière of int
| Booléenne of bool;;
type expr_type =
Integer (* le type des entiers *)
| Boolean (* le type des booléens *)
| Array of int * int * expr_type;; (* le type des tableaux *)
(* (les deux "int" sont les bornes) *)
type expression =
Constante of constante
| Variable of string
| Application of string * expression list
| Op_unaire of string * expression
| Op_binaire of string * expression * expression
| Accès_tableau of expression * expression;;
type instruction =
Affectation_var of string * expression
| Affectation_tableau of expression * expression * expression
| Appel of string * expression list (* appel de procédure *)
| If of expression * instruction * instruction
| While of expression * instruction
| Write of expression
| Read of string
| Bloc of instruction list;; (* bloc begin ... end *)
type décl_proc =
{ proc_paramètres: (string * expr_type) list;
proc_variables: (string * expr_type) list;
proc_corps: instruction }
and décl_fonc =
{ fonc_paramètres: (string * expr_type) list;
fonc_type_résultat: expr_type;
fonc_variables: (string * expr_type) list;
fonc_corps: instruction };;
type programme =
{ prog_variables: (string * expr_type) list;
prog_procédures: (string * décl_proc) list;
prog_fonctions: (string * décl_fonc) list;
prog_corps: instruction };;
value lire_programme : char stream -> programme;;
| null | https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/examples/pascal/syntaxe.mli | ocaml | le type des entiers
le type des booléens
le type des tableaux
(les deux "int" sont les bornes)
appel de procédure
bloc begin ... end | type constante =
Entière of int
| Booléenne of bool;;
type expr_type =
type expression =
Constante of constante
| Variable of string
| Application of string * expression list
| Op_unaire of string * expression
| Op_binaire of string * expression * expression
| Accès_tableau of expression * expression;;
type instruction =
Affectation_var of string * expression
| Affectation_tableau of expression * expression * expression
| If of expression * instruction * instruction
| While of expression * instruction
| Write of expression
| Read of string
type décl_proc =
{ proc_paramètres: (string * expr_type) list;
proc_variables: (string * expr_type) list;
proc_corps: instruction }
and décl_fonc =
{ fonc_paramètres: (string * expr_type) list;
fonc_type_résultat: expr_type;
fonc_variables: (string * expr_type) list;
fonc_corps: instruction };;
type programme =
{ prog_variables: (string * expr_type) list;
prog_procédures: (string * décl_proc) list;
prog_fonctions: (string * décl_fonc) list;
prog_corps: instruction };;
value lire_programme : char stream -> programme;;
|
982ed77d89538fea1dc8879abc2951fbf2e81f9f86d5950c47caf4c0c35a1a8f | clj-kondo/clj-kondo | errors.cljs | Copyright ( c ) , , Rich Hickey & contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns ^{:no-doc true} clj-kondo.impl.toolsreader.v1v2v2.cljs.tools.reader.impl.errors
(:require [clj-kondo.impl.toolsreader.v1v2v2.cljs.tools.reader.reader-types :as types]
[clojure.string :as s]
[clj-kondo.impl.toolsreader.v1v2v2.cljs.tools.reader.impl.inspect :as i]))
(defn- ex-details
[rdr ex-type]
(let [details {:type :reader-exception
:ex-kind ex-type}]
(if (types/indexing-reader? rdr)
(assoc
details
:file (types/get-file-name rdr)
:line (types/get-line-number rdr)
:col (types/get-column-number rdr))
details)))
(defn- throw-ex
"Throw an ex-info error."
[rdr ex-type & msg]
(let [details (ex-details rdr ex-type)
file (:file details)
line (:line details)
col (:col details)
msg1 (if file (str file " "))
msg2 (if line (str "[line " line ", col " col "]"))
msg3 (if (or msg1 msg2) " ")
full-msg (apply str msg1 msg2 msg3 msg)]
(throw (ex-info full-msg details))))
(defn reader-error
"Throws an ExceptionInfo with the given message.
If rdr is an IndexingReader, additional information about column and line number is provided"
[rdr & msgs]
(throw-ex rdr :reader-error (apply str msgs)))
(defn illegal-arg-error
"Throws an ExceptionInfo with the given message.
If rdr is an IndexingReader, additional information about column and line number is provided"
[rdr & msgs]
(throw-ex rdr :illegal-argument (apply str msgs)))
(defn eof-error
"Throws an ExceptionInfo with the given message.
If rdr is an IndexingReader, additional information about column and line number is provided"
[rdr & msgs]
(throw-ex rdr :eof (apply str msgs)))
(defn throw-eof-delimited
([rdr kind column line] (throw-eof-delimited rdr kind line column nil))
([rdr kind line column n]
(eof-error
rdr
"Unexpected EOF while reading "
(if n
(str "item " n " of "))
(name kind)
(if line
(str ", starting at line " line " and column " column))
".")))
(defn throw-odd-map [rdr line col elements]
(reader-error
rdr
"The map literal starting with "
(i/inspect (first elements))
(if line (str " on line " line " column " col))
" contains "
(count elements)
" form(s). Map literals must contain an even number of forms."))
(defn throw-invalid-number [rdr token]
(reader-error
rdr
"Invalid number: "
token
"."))
(defn throw-invalid-unicode-literal [rdr token]
(throw
(illegal-arg-error
rdr
"Invalid unicode literal: \\"
token
".")))
(defn throw-invalid-unicode-escape [rdr ch]
(reader-error
rdr
"Invalid unicode escape: \\u"
ch
"."))
(defn throw-invalid [rdr kind token]
(reader-error rdr "Invalid " (name kind) ": " token "."))
(defn throw-eof-at-start [rdr kind]
(eof-error rdr "Unexpected EOF while reading start of " (name kind) "."))
(defn throw-bad-char [rdr kind ch]
(reader-error rdr "Invalid character: " ch " found while reading " (name kind) "."))
(defn throw-eof-at-dispatch [rdr]
(eof-error rdr "Unexpected EOF while reading dispatch character."))
(defn throw-bad-dispatch [rdr ch]
(reader-error rdr "No dispatch macro for " ch "."))
(defn throw-unmatch-delimiter [rdr ch]
(reader-error rdr "Unmatched delimiter " ch "."))
(defn throw-eof-reading [rdr kind & start]
(let [init (case kind :regex "#\"" :string \")]
(eof-error rdr "Unexpected EOF reading " (name kind) " starting " (apply str init start) ".")))
(defn throw-no-dispatch [rdr ch]
(throw-bad-dispatch rdr ch))
(defn throw-invalid-unicode-char[rdr token]
(reader-error
rdr
"Invalid unicode character \\"
token
"."))
(defn throw-invalid-unicode-digit-in-token[rdr ch token]
(illegal-arg-error
rdr
"Invalid digit "
ch
" in unicode character \\"
token
"."))
(defn throw-invalid-unicode-digit[rdr ch]
(illegal-arg-error
rdr
"Invalid digit "
ch
" in unicode character."))
(defn throw-invalid-unicode-len[rdr actual expected]
(illegal-arg-error
rdr
"Invalid unicode literal. Unicode literals should be "
expected
"characters long. "
"value suppled is "
actual
"characters long."))
(defn throw-invalid-character-literal[rdr token]
(reader-error rdr "Invalid character literal \\u" token "."))
(defn throw-invalid-octal-len[rdr token]
(reader-error
rdr
"Invalid octal escape sequence in a character literal:"
token
". Octal escape sequences must be 3 or fewer digits."))
(defn throw-bad-octal-number [rdr]
(reader-error rdr "Octal escape sequence must be in range [0, 377]."))
(defn throw-unsupported-character[rdr token]
(reader-error
rdr
"Unsupported character: "
token
"."))
(defn throw-eof-in-character [rdr]
(eof-error
rdr
"Unexpected EOF while reading character."))
(defn throw-bad-escape-char [rdr ch]
(reader-error rdr "Unsupported escape character: \\" ch "."))
(defn throw-single-colon [rdr]
(reader-error rdr "A single colon is not a valid keyword."))
(defn throw-bad-metadata [rdr x]
(reader-error
rdr
"Metadata cannot be "
(i/inspect x)
". Metadata must be a Symbol, Keyword, String or Map."))
(defn throw-bad-metadata-target [rdr target]
(reader-error
rdr
"Metadata can not be applied to "
(i/inspect target)
". "
"Metadata can only be applied to IMetas."))
(defn throw-feature-not-keyword [rdr feature]
(reader-error
rdr
"Feature cannot be "
(i/inspect feature)
" Features must be keywords."))
(defn throw-ns-map-no-map [rdr ns-name]
(reader-error rdr "Namespaced map with namespace " ns-name " does not specify a map."))
(defn throw-bad-ns [rdr ns-name]
(reader-error rdr "Invalid value used as namespace in namespaced map: " ns-name "."))
(defn throw-bad-reader-tag [rdr tag]
(reader-error
rdr
"Invalid reader tag: "
(i/inspect tag)
". Reader tags must be symbols."))
(defn throw-unknown-reader-tag [rdr tag]
(reader-error
rdr
"No reader function for tag "
(i/inspect tag)
"."))
(defn- duplicate-keys-error [msg coll]
(letfn [(duplicates [seq]
(for [[id freq] (frequencies seq)
:when (> freq 1)]
id))]
(let [dups (duplicates coll)]
(apply str msg
(when (> (count dups) 1) "s")
": " (interpose ", " dups)))))
(defn throw-dup-keys [rdr kind ks]
(reader-error
rdr
(duplicate-keys-error
(str (s/capitalize (name kind)) " literal contains duplicate key")
ks)))
(defn throw-eof-error [rdr line]
(if line
(eof-error rdr "EOF while reading, starting at line " line ".")
(eof-error rdr "EOF while reading.")))
| null | https://raw.githubusercontent.com/clj-kondo/clj-kondo/626978461cbf113c376634cdf034d7262deb429f/inlined/clj_kondo/impl/toolsreader/v1v2v2/cljs/tools/reader/impl/errors.cljs | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) , , Rich Hickey & contributors .
(ns ^{:no-doc true} clj-kondo.impl.toolsreader.v1v2v2.cljs.tools.reader.impl.errors
(:require [clj-kondo.impl.toolsreader.v1v2v2.cljs.tools.reader.reader-types :as types]
[clojure.string :as s]
[clj-kondo.impl.toolsreader.v1v2v2.cljs.tools.reader.impl.inspect :as i]))
(defn- ex-details
[rdr ex-type]
(let [details {:type :reader-exception
:ex-kind ex-type}]
(if (types/indexing-reader? rdr)
(assoc
details
:file (types/get-file-name rdr)
:line (types/get-line-number rdr)
:col (types/get-column-number rdr))
details)))
(defn- throw-ex
"Throw an ex-info error."
[rdr ex-type & msg]
(let [details (ex-details rdr ex-type)
file (:file details)
line (:line details)
col (:col details)
msg1 (if file (str file " "))
msg2 (if line (str "[line " line ", col " col "]"))
msg3 (if (or msg1 msg2) " ")
full-msg (apply str msg1 msg2 msg3 msg)]
(throw (ex-info full-msg details))))
(defn reader-error
"Throws an ExceptionInfo with the given message.
If rdr is an IndexingReader, additional information about column and line number is provided"
[rdr & msgs]
(throw-ex rdr :reader-error (apply str msgs)))
(defn illegal-arg-error
"Throws an ExceptionInfo with the given message.
If rdr is an IndexingReader, additional information about column and line number is provided"
[rdr & msgs]
(throw-ex rdr :illegal-argument (apply str msgs)))
(defn eof-error
"Throws an ExceptionInfo with the given message.
If rdr is an IndexingReader, additional information about column and line number is provided"
[rdr & msgs]
(throw-ex rdr :eof (apply str msgs)))
(defn throw-eof-delimited
([rdr kind column line] (throw-eof-delimited rdr kind line column nil))
([rdr kind line column n]
(eof-error
rdr
"Unexpected EOF while reading "
(if n
(str "item " n " of "))
(name kind)
(if line
(str ", starting at line " line " and column " column))
".")))
(defn throw-odd-map [rdr line col elements]
(reader-error
rdr
"The map literal starting with "
(i/inspect (first elements))
(if line (str " on line " line " column " col))
" contains "
(count elements)
" form(s). Map literals must contain an even number of forms."))
(defn throw-invalid-number [rdr token]
(reader-error
rdr
"Invalid number: "
token
"."))
(defn throw-invalid-unicode-literal [rdr token]
(throw
(illegal-arg-error
rdr
"Invalid unicode literal: \\"
token
".")))
(defn throw-invalid-unicode-escape [rdr ch]
(reader-error
rdr
"Invalid unicode escape: \\u"
ch
"."))
(defn throw-invalid [rdr kind token]
(reader-error rdr "Invalid " (name kind) ": " token "."))
(defn throw-eof-at-start [rdr kind]
(eof-error rdr "Unexpected EOF while reading start of " (name kind) "."))
(defn throw-bad-char [rdr kind ch]
(reader-error rdr "Invalid character: " ch " found while reading " (name kind) "."))
(defn throw-eof-at-dispatch [rdr]
(eof-error rdr "Unexpected EOF while reading dispatch character."))
(defn throw-bad-dispatch [rdr ch]
(reader-error rdr "No dispatch macro for " ch "."))
(defn throw-unmatch-delimiter [rdr ch]
(reader-error rdr "Unmatched delimiter " ch "."))
(defn throw-eof-reading [rdr kind & start]
(let [init (case kind :regex "#\"" :string \")]
(eof-error rdr "Unexpected EOF reading " (name kind) " starting " (apply str init start) ".")))
(defn throw-no-dispatch [rdr ch]
(throw-bad-dispatch rdr ch))
(defn throw-invalid-unicode-char[rdr token]
(reader-error
rdr
"Invalid unicode character \\"
token
"."))
(defn throw-invalid-unicode-digit-in-token[rdr ch token]
(illegal-arg-error
rdr
"Invalid digit "
ch
" in unicode character \\"
token
"."))
(defn throw-invalid-unicode-digit[rdr ch]
(illegal-arg-error
rdr
"Invalid digit "
ch
" in unicode character."))
(defn throw-invalid-unicode-len[rdr actual expected]
(illegal-arg-error
rdr
"Invalid unicode literal. Unicode literals should be "
expected
"characters long. "
"value suppled is "
actual
"characters long."))
(defn throw-invalid-character-literal[rdr token]
(reader-error rdr "Invalid character literal \\u" token "."))
(defn throw-invalid-octal-len[rdr token]
(reader-error
rdr
"Invalid octal escape sequence in a character literal:"
token
". Octal escape sequences must be 3 or fewer digits."))
(defn throw-bad-octal-number [rdr]
(reader-error rdr "Octal escape sequence must be in range [0, 377]."))
(defn throw-unsupported-character[rdr token]
(reader-error
rdr
"Unsupported character: "
token
"."))
(defn throw-eof-in-character [rdr]
(eof-error
rdr
"Unexpected EOF while reading character."))
(defn throw-bad-escape-char [rdr ch]
(reader-error rdr "Unsupported escape character: \\" ch "."))
(defn throw-single-colon [rdr]
(reader-error rdr "A single colon is not a valid keyword."))
(defn throw-bad-metadata [rdr x]
(reader-error
rdr
"Metadata cannot be "
(i/inspect x)
". Metadata must be a Symbol, Keyword, String or Map."))
(defn throw-bad-metadata-target [rdr target]
(reader-error
rdr
"Metadata can not be applied to "
(i/inspect target)
". "
"Metadata can only be applied to IMetas."))
(defn throw-feature-not-keyword [rdr feature]
(reader-error
rdr
"Feature cannot be "
(i/inspect feature)
" Features must be keywords."))
(defn throw-ns-map-no-map [rdr ns-name]
(reader-error rdr "Namespaced map with namespace " ns-name " does not specify a map."))
(defn throw-bad-ns [rdr ns-name]
(reader-error rdr "Invalid value used as namespace in namespaced map: " ns-name "."))
(defn throw-bad-reader-tag [rdr tag]
(reader-error
rdr
"Invalid reader tag: "
(i/inspect tag)
". Reader tags must be symbols."))
(defn throw-unknown-reader-tag [rdr tag]
(reader-error
rdr
"No reader function for tag "
(i/inspect tag)
"."))
(defn- duplicate-keys-error [msg coll]
(letfn [(duplicates [seq]
(for [[id freq] (frequencies seq)
:when (> freq 1)]
id))]
(let [dups (duplicates coll)]
(apply str msg
(when (> (count dups) 1) "s")
": " (interpose ", " dups)))))
(defn throw-dup-keys [rdr kind ks]
(reader-error
rdr
(duplicate-keys-error
(str (s/capitalize (name kind)) " literal contains duplicate key")
ks)))
(defn throw-eof-error [rdr line]
(if line
(eof-error rdr "EOF while reading, starting at line " line ".")
(eof-error rdr "EOF while reading.")))
|
8a58cdb3dca6e67f105fd33bcfa17d40444c0a93e18f90374f2596a4f054c1da | g000001/tagger | analysis-sysdcl.lisp | -*- Package : TDB ; Syntax : Common - Lisp ; Mode : Lisp ; Base : 10 -*-
Copyright ( c ) 1992 by Xerox Corporation . All rights reserved .
TDB Analysis components
(cl:eval-when (cl:compile cl:eval cl:load)
(pdefsys:load-system-def :tdb-sysdcl))
(cl:in-package :tdb)
(def-tdb-system :analysis
((:dir "analysis") (:sub-systems :util))
"analysis-protocol")
;;;; analysis pipeline elements
(def-tdb-system :simple-tokenizer
((:dir "analysis") (:sub-systems :analysis))
("simple-tokenizer"))
(def-tdb-system :fsm-tokenizer
((:dir "analysis") (:sub-systems :analysis :fsm-runtime))
("fsm-tokenizer"))
(def-tdb-system :fsm-tokenizer-rules
((:dir "analysis") (:sub-systems :fsm-tokenizer :fsm-calculus))
("fsm-tokenizer-rules"))
(def-tdb-system :fsa-tokenizer
((:dir "analysis") (:sub-systems :analysis :fsa :fsa-standard))
("fsa-tokenizer"))
(def-tdb-system :stop-list
((:dir "analysis") (:sub-systems :analysis :trie))
("stop-list"))
(def-tdb-system :downcase-filter
((:dir "analysis") (:sub-systems :analysis))
("downcase-filter"))
(def-tdb-system :twol-stemmer
((:dir "analysis")
(:sub-systems :analysis #-excl :fst-lookup))
#-excl "twol-stemmer"
#+excl("stem"
:language :gcc :optimizations ("-O2")
:binary-pathname #+iris4d "stem-iris4d.o" #+sun4 "stem-sun4.o")
#+excl("c-twol-stemmer" :load-before-compile t)
)
(def-tdb-system :fsm-filter
((:dir "analysis")
(:sub-systems :analysis :string-resource :fsm-calculus))
("fsm-filter"))
;;;; analysis mixins
(def-tdb-system :simple-analysis
((:dir "analysis")
(:sub-systems :simple-tokenizer :downcase-filter))
"simple-analysis")
(def-tdb-system :stop-analysis
((:dir "analysis")
(:sub-systems :simple-tokenizer :downcase-filter :stop-list))
"stop-analysis")
(def-tdb-system :twol-analysis
((:dir "analysis")
(:sub-systems
:simple-tokenizer :downcase-filter :stop-list :twol-stemmer))
"twol-analysis")
(def-tdb-system :fsa-analysis
((:dir "analysis")
(:sub-systems :fsa-tokenizer :downcase-filter
:stop-list :ssd-analysis :twol-stemmer))
"fsa-analysis")
(def-tdb-system :ssd-analysis
((:dir "analysis")
(:sub-systems :twol-analysis))
("ssd-analysis"))
(def-tdb-system :chink-chunk-analysis
((:dir "analysis")
(:sub-systems :analysis :cons-resource :stop-list :twol-stemmer
:downcase-filter :simple-tokenizer))
("chink-chunk-analysis"))
(def-tdb-system :dink-analysis
((:dir "analysis")
(:sub-systems :analysis :chink-chunk-analysis))
("dink-analysis"))
(def-tdb-system :couple-analysis
((:dir "analysis")
(:sub-systems :fsm-tokenizer-rules :fsm-filter :cons-resource
:stop-list :downcase-filter :twol-stemmer))
("couple-analysis"))
(def-tdb-system :is-a
((:dir "search")
(:sub-systems
:chink-chunk-analysis :couple-analysis :interval-ps))
("around-chunks")
("is-a"))
(def-tdb-system :token-grep
((:dir "search")
(:sub-systems :fsm-tokenizer-rules :fsm-filter :downcase-filter))
("token-grep"))
| null | https://raw.githubusercontent.com/g000001/tagger/a4e0650c55aba44250871b96e2220e1b4953c6ab/orig/src/sysdcl/analysis-sysdcl.lisp | lisp | Syntax : Common - Lisp ; Mode : Lisp ; Base : 10 -*-
analysis pipeline elements
analysis mixins |
Copyright ( c ) 1992 by Xerox Corporation . All rights reserved .
TDB Analysis components
(cl:eval-when (cl:compile cl:eval cl:load)
(pdefsys:load-system-def :tdb-sysdcl))
(cl:in-package :tdb)
(def-tdb-system :analysis
((:dir "analysis") (:sub-systems :util))
"analysis-protocol")
(def-tdb-system :simple-tokenizer
((:dir "analysis") (:sub-systems :analysis))
("simple-tokenizer"))
(def-tdb-system :fsm-tokenizer
((:dir "analysis") (:sub-systems :analysis :fsm-runtime))
("fsm-tokenizer"))
(def-tdb-system :fsm-tokenizer-rules
((:dir "analysis") (:sub-systems :fsm-tokenizer :fsm-calculus))
("fsm-tokenizer-rules"))
(def-tdb-system :fsa-tokenizer
((:dir "analysis") (:sub-systems :analysis :fsa :fsa-standard))
("fsa-tokenizer"))
(def-tdb-system :stop-list
((:dir "analysis") (:sub-systems :analysis :trie))
("stop-list"))
(def-tdb-system :downcase-filter
((:dir "analysis") (:sub-systems :analysis))
("downcase-filter"))
(def-tdb-system :twol-stemmer
((:dir "analysis")
(:sub-systems :analysis #-excl :fst-lookup))
#-excl "twol-stemmer"
#+excl("stem"
:language :gcc :optimizations ("-O2")
:binary-pathname #+iris4d "stem-iris4d.o" #+sun4 "stem-sun4.o")
#+excl("c-twol-stemmer" :load-before-compile t)
)
(def-tdb-system :fsm-filter
((:dir "analysis")
(:sub-systems :analysis :string-resource :fsm-calculus))
("fsm-filter"))
(def-tdb-system :simple-analysis
((:dir "analysis")
(:sub-systems :simple-tokenizer :downcase-filter))
"simple-analysis")
(def-tdb-system :stop-analysis
((:dir "analysis")
(:sub-systems :simple-tokenizer :downcase-filter :stop-list))
"stop-analysis")
(def-tdb-system :twol-analysis
((:dir "analysis")
(:sub-systems
:simple-tokenizer :downcase-filter :stop-list :twol-stemmer))
"twol-analysis")
(def-tdb-system :fsa-analysis
((:dir "analysis")
(:sub-systems :fsa-tokenizer :downcase-filter
:stop-list :ssd-analysis :twol-stemmer))
"fsa-analysis")
(def-tdb-system :ssd-analysis
((:dir "analysis")
(:sub-systems :twol-analysis))
("ssd-analysis"))
(def-tdb-system :chink-chunk-analysis
((:dir "analysis")
(:sub-systems :analysis :cons-resource :stop-list :twol-stemmer
:downcase-filter :simple-tokenizer))
("chink-chunk-analysis"))
(def-tdb-system :dink-analysis
((:dir "analysis")
(:sub-systems :analysis :chink-chunk-analysis))
("dink-analysis"))
(def-tdb-system :couple-analysis
((:dir "analysis")
(:sub-systems :fsm-tokenizer-rules :fsm-filter :cons-resource
:stop-list :downcase-filter :twol-stemmer))
("couple-analysis"))
(def-tdb-system :is-a
((:dir "search")
(:sub-systems
:chink-chunk-analysis :couple-analysis :interval-ps))
("around-chunks")
("is-a"))
(def-tdb-system :token-grep
((:dir "search")
(:sub-systems :fsm-tokenizer-rules :fsm-filter :downcase-filter))
("token-grep"))
|
3929f1bf16ebf48a40ea2bb47c52216ce5f67dff20aec8e3e12cdd0d0b253461 | psg-mit/twist-popl22 | static.mli | exception Error of string
val check : Ast.program -> unit
| null | https://raw.githubusercontent.com/psg-mit/twist-popl22/1195333cd4156f759c1d10a1ca7b1bcaab60c4e3/src/static.mli | ocaml | exception Error of string
val check : Ast.program -> unit
|
|
0ce55f66e63ef5cc977df0fc754f3cac3efdb5481b1f77913a9a915c47a2cfed | racket/rhombus-prototype | uses-pack.rkt | #lang racket/base
(require syntax/parse/pre
"pack.rkt")
(provide unpack-uses
pack-uses)
(define (unpack-uses v)
(syntax-parse v
[(stx ...)
#'(brackets (group stx) ...)]))
(define (pack-uses v who)
(syntax-parse v
#:datum-literals (brackets group)
[(brackets (group stx) ...)
#'(stx ...)]))
| null | https://raw.githubusercontent.com/racket/rhombus-prototype/dcf7fb9b002c0957fc0adbf9bd3475c26a8b2c01/rhombus/private/uses-pack.rkt | racket | #lang racket/base
(require syntax/parse/pre
"pack.rkt")
(provide unpack-uses
pack-uses)
(define (unpack-uses v)
(syntax-parse v
[(stx ...)
#'(brackets (group stx) ...)]))
(define (pack-uses v who)
(syntax-parse v
#:datum-literals (brackets group)
[(brackets (group stx) ...)
#'(stx ...)]))
|
|
ec909bea5cf20f14c1c839afa60f9d8f4966044d6617de879b2eead60b956603 | YoshikuniJujo/funpaala | rsa.hs | xxcrypt n ed = (`mod` n) . (^ ed)
| null | https://raw.githubusercontent.com/YoshikuniJujo/funpaala/5366130826da0e6b1180992dfff94c4a634cda99/samples/07_polymorphic/rsa.hs | haskell | xxcrypt n ed = (`mod` n) . (^ ed)
|
|
02e56063f2987da5872bc489e85bc870a232510f568fc9e454e905e7187cdc2c | mzp/coq-ide-for-ios | bigint.mli | (************************************************************************)
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 $ I d : bigint.mli 13323 2010 - 07 - 24 15:57:30Z herbelin $ i
(*i*)
open Pp
(*i*)
(* Arbitrary large integer numbers *)
type bigint
val of_string : string -> bigint
val to_string : bigint -> string
val zero : bigint
val one : bigint
val two : bigint
val div2_with_rest : bigint -> bigint * bool (* true=odd; false=even *)
val add_1 : bigint -> bigint
val sub_1 : bigint -> bigint
val mult_2 : bigint -> bigint
val add : bigint -> bigint -> bigint
val sub : bigint -> bigint -> bigint
val mult : bigint -> bigint -> bigint
val euclid : bigint -> bigint -> bigint * bigint
val less_than : bigint -> bigint -> bool
val equal : bigint -> bigint -> bool
val is_strictly_pos : bigint -> bool
val is_strictly_neg : bigint -> bool
val is_pos_or_zero : bigint -> bool
val is_neg_or_zero : bigint -> bool
val neg : bigint -> bigint
val pow : bigint -> bigint -> bigint
val pr_bigint : bigint -> std_ppcmds
| null | https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/lib/bigint.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i
i
Arbitrary large integer numbers
true=odd; false=even | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
i $ I d : bigint.mli 13323 2010 - 07 - 24 15:57:30Z herbelin $ i
open Pp
type bigint
val of_string : string -> bigint
val to_string : bigint -> string
val zero : bigint
val one : bigint
val two : bigint
val add_1 : bigint -> bigint
val sub_1 : bigint -> bigint
val mult_2 : bigint -> bigint
val add : bigint -> bigint -> bigint
val sub : bigint -> bigint -> bigint
val mult : bigint -> bigint -> bigint
val euclid : bigint -> bigint -> bigint * bigint
val less_than : bigint -> bigint -> bool
val equal : bigint -> bigint -> bool
val is_strictly_pos : bigint -> bool
val is_strictly_neg : bigint -> bool
val is_pos_or_zero : bigint -> bool
val is_neg_or_zero : bigint -> bool
val neg : bigint -> bigint
val pow : bigint -> bigint -> bigint
val pr_bigint : bigint -> std_ppcmds
|
d335cc72dd7dd8c029a0875345aa5905dc3fb9661f726a3858ec1edb6b8776db | henryw374/cljc.java-time | period.clj | (ns cljc.java-time.period (:refer-clojure :exclude [abs get range format min max next name resolve short]) (:require [cljc.java-time.extn.calendar-awareness]) (:import [java.time Period]))
(def zero java.time.Period/ZERO)
(clojure.core/defn get-months {:arglists (quote (["java.time.Period"]))} (^java.lang.Integer [^java.time.Period this12932] (.getMonths this12932)))
(clojure.core/defn of-weeks {:arglists (quote (["int"]))} (^java.time.Period [^java.lang.Integer int12933] (java.time.Period/ofWeeks int12933)))
(clojure.core/defn of-days {:arglists (quote (["int"]))} (^java.time.Period [^java.lang.Integer int12934] (java.time.Period/ofDays int12934)))
(clojure.core/defn is-negative {:arglists (quote (["java.time.Period"]))} (^java.lang.Boolean [^java.time.Period this12935] (.isNegative this12935)))
(clojure.core/defn of {:arglists (quote (["int" "int" "int"]))} (^java.time.Period [^java.lang.Integer int12936 ^java.lang.Integer int12937 ^java.lang.Integer int12938] (java.time.Period/of int12936 int12937 int12938)))
(clojure.core/defn is-zero {:arglists (quote (["java.time.Period"]))} (^java.lang.Boolean [^java.time.Period this12939] (.isZero this12939)))
(clojure.core/defn multiplied-by {:arglists (quote (["java.time.Period" "int"]))} (^java.time.Period [^java.time.Period this12940 ^java.lang.Integer int12941] (.multipliedBy this12940 int12941)))
(clojure.core/defn get-units {:arglists (quote (["java.time.Period"]))} (^java.util.List [^java.time.Period this12942] (.getUnits this12942)))
(clojure.core/defn with-days {:arglists (quote (["java.time.Period" "int"]))} (^java.time.Period [^java.time.Period this12943 ^java.lang.Integer int12944] (.withDays this12943 int12944)))
(clojure.core/defn plus {:arglists (quote (["java.time.Period" "java.time.temporal.TemporalAmount"]))} (^java.time.Period [^java.time.Period this12945 ^java.time.temporal.TemporalAmount java-time-temporal-TemporalAmount12946] (.plus this12945 java-time-temporal-TemporalAmount12946)))
(clojure.core/defn of-months {:arglists (quote (["int"]))} (^java.time.Period [^java.lang.Integer int12947] (java.time.Period/ofMonths int12947)))
(clojure.core/defn to-string {:arglists (quote (["java.time.Period"]))} (^java.lang.String [^java.time.Period this12948] (.toString this12948)))
(clojure.core/defn plus-months {:arglists (quote (["java.time.Period" "long"]))} (^java.time.Period [^java.time.Period this12949 ^long long12950] (.plusMonths this12949 long12950)))
(clojure.core/defn minus-months {:arglists (quote (["java.time.Period" "long"]))} (^java.time.Period [^java.time.Period this12951 ^long long12952] (.minusMonths this12951 long12952)))
(clojure.core/defn minus {:arglists (quote (["java.time.Period" "java.time.temporal.TemporalAmount"]))} (^java.time.Period [^java.time.Period this12953 ^java.time.temporal.TemporalAmount java-time-temporal-TemporalAmount12954] (.minus this12953 java-time-temporal-TemporalAmount12954)))
(clojure.core/defn add-to {:arglists (quote (["java.time.Period" "java.time.temporal.Temporal"]))} (^java.time.temporal.Temporal [^java.time.Period this12955 ^java.time.temporal.Temporal java-time-temporal-Temporal12956] (.addTo this12955 java-time-temporal-Temporal12956)))
(clojure.core/defn to-total-months {:arglists (quote (["java.time.Period"]))} (^long [^java.time.Period this12957] (.toTotalMonths this12957)))
(clojure.core/defn plus-days {:arglists (quote (["java.time.Period" "long"]))} (^java.time.Period [^java.time.Period this12958 ^long long12959] (.plusDays this12958 long12959)))
(clojure.core/defn of-years {:arglists (quote (["int"]))} (^java.time.Period [^java.lang.Integer int12960] (java.time.Period/ofYears int12960)))
(clojure.core/defn get-days {:arglists (quote (["java.time.Period"]))} (^java.lang.Integer [^java.time.Period this12961] (.getDays this12961)))
(clojure.core/defn negated {:arglists (quote (["java.time.Period"]))} (^java.time.Period [^java.time.Period this12962] (.negated this12962)))
(clojure.core/defn get-years {:arglists (quote (["java.time.Period"]))} (^java.lang.Integer [^java.time.Period this12963] (.getYears this12963)))
(clojure.core/defn with-years {:arglists (quote (["java.time.Period" "int"]))} (^java.time.Period [^java.time.Period this12964 ^java.lang.Integer int12965] (.withYears this12964 int12965)))
(clojure.core/defn normalized {:arglists (quote (["java.time.Period"]))} (^java.time.Period [^java.time.Period this12966] (.normalized this12966)))
(clojure.core/defn with-months {:arglists (quote (["java.time.Period" "int"]))} (^java.time.Period [^java.time.Period this12967 ^java.lang.Integer int12968] (.withMonths this12967 int12968)))
(clojure.core/defn between {:arglists (quote (["java.time.LocalDate" "java.time.LocalDate"]))} (^java.time.Period [^java.time.LocalDate java-time-LocalDate12969 ^java.time.LocalDate java-time-LocalDate12970] (java.time.Period/between java-time-LocalDate12969 java-time-LocalDate12970)))
(clojure.core/defn from {:arglists (quote (["java.time.temporal.TemporalAmount"]))} (^java.time.Period [^java.time.temporal.TemporalAmount java-time-temporal-TemporalAmount12971] (java.time.Period/from java-time-temporal-TemporalAmount12971)))
(clojure.core/defn minus-years {:arglists (quote (["java.time.Period" "long"]))} (^java.time.Period [^java.time.Period this12972 ^long long12973] (.minusYears this12972 long12973)))
(clojure.core/defn get-chronology {:arglists (quote (["java.time.Period"]))} (^java.time.chrono.IsoChronology [^java.time.Period this12974] (.getChronology this12974)))
(clojure.core/defn parse {:arglists (quote (["java.lang.CharSequence"]))} (^java.time.Period [^java.lang.CharSequence java-lang-CharSequence12975] (java.time.Period/parse java-lang-CharSequence12975)))
(clojure.core/defn hash-code {:arglists (quote (["java.time.Period"]))} (^java.lang.Integer [^java.time.Period this12976] (.hashCode this12976)))
(clojure.core/defn subtract-from {:arglists (quote (["java.time.Period" "java.time.temporal.Temporal"]))} (^java.time.temporal.Temporal [^java.time.Period this12977 ^java.time.temporal.Temporal java-time-temporal-Temporal12978] (.subtractFrom this12977 java-time-temporal-Temporal12978)))
(clojure.core/defn get {:arglists (quote (["java.time.Period" "java.time.temporal.TemporalUnit"]))} (^long [^java.time.Period this12979 ^java.time.temporal.ChronoUnit java-time-temporal-TemporalUnit12980] (.get this12979 java-time-temporal-TemporalUnit12980)))
(clojure.core/defn equals {:arglists (quote (["java.time.Period" "java.lang.Object"]))} (^java.lang.Boolean [^java.time.Period this12981 ^java.lang.Object java-lang-Object12982] (.equals this12981 java-lang-Object12982)))
(clojure.core/defn plus-years {:arglists (quote (["java.time.Period" "long"]))} (^java.time.Period [^java.time.Period this12983 ^long long12984] (.plusYears this12983 long12984)))
(clojure.core/defn minus-days {:arglists (quote (["java.time.Period" "long"]))} (^java.time.Period [^java.time.Period this12985 ^long long12986] (.minusDays this12985 long12986)))
| null | https://raw.githubusercontent.com/henryw374/cljc.java-time/2e47e8104bc2ec7f68a01bf751a7b9a2dee391b4/src/cljc/java_time/period.clj | clojure | (ns cljc.java-time.period (:refer-clojure :exclude [abs get range format min max next name resolve short]) (:require [cljc.java-time.extn.calendar-awareness]) (:import [java.time Period]))
(def zero java.time.Period/ZERO)
(clojure.core/defn get-months {:arglists (quote (["java.time.Period"]))} (^java.lang.Integer [^java.time.Period this12932] (.getMonths this12932)))
(clojure.core/defn of-weeks {:arglists (quote (["int"]))} (^java.time.Period [^java.lang.Integer int12933] (java.time.Period/ofWeeks int12933)))
(clojure.core/defn of-days {:arglists (quote (["int"]))} (^java.time.Period [^java.lang.Integer int12934] (java.time.Period/ofDays int12934)))
(clojure.core/defn is-negative {:arglists (quote (["java.time.Period"]))} (^java.lang.Boolean [^java.time.Period this12935] (.isNegative this12935)))
(clojure.core/defn of {:arglists (quote (["int" "int" "int"]))} (^java.time.Period [^java.lang.Integer int12936 ^java.lang.Integer int12937 ^java.lang.Integer int12938] (java.time.Period/of int12936 int12937 int12938)))
(clojure.core/defn is-zero {:arglists (quote (["java.time.Period"]))} (^java.lang.Boolean [^java.time.Period this12939] (.isZero this12939)))
(clojure.core/defn multiplied-by {:arglists (quote (["java.time.Period" "int"]))} (^java.time.Period [^java.time.Period this12940 ^java.lang.Integer int12941] (.multipliedBy this12940 int12941)))
(clojure.core/defn get-units {:arglists (quote (["java.time.Period"]))} (^java.util.List [^java.time.Period this12942] (.getUnits this12942)))
(clojure.core/defn with-days {:arglists (quote (["java.time.Period" "int"]))} (^java.time.Period [^java.time.Period this12943 ^java.lang.Integer int12944] (.withDays this12943 int12944)))
(clojure.core/defn plus {:arglists (quote (["java.time.Period" "java.time.temporal.TemporalAmount"]))} (^java.time.Period [^java.time.Period this12945 ^java.time.temporal.TemporalAmount java-time-temporal-TemporalAmount12946] (.plus this12945 java-time-temporal-TemporalAmount12946)))
(clojure.core/defn of-months {:arglists (quote (["int"]))} (^java.time.Period [^java.lang.Integer int12947] (java.time.Period/ofMonths int12947)))
(clojure.core/defn to-string {:arglists (quote (["java.time.Period"]))} (^java.lang.String [^java.time.Period this12948] (.toString this12948)))
(clojure.core/defn plus-months {:arglists (quote (["java.time.Period" "long"]))} (^java.time.Period [^java.time.Period this12949 ^long long12950] (.plusMonths this12949 long12950)))
(clojure.core/defn minus-months {:arglists (quote (["java.time.Period" "long"]))} (^java.time.Period [^java.time.Period this12951 ^long long12952] (.minusMonths this12951 long12952)))
(clojure.core/defn minus {:arglists (quote (["java.time.Period" "java.time.temporal.TemporalAmount"]))} (^java.time.Period [^java.time.Period this12953 ^java.time.temporal.TemporalAmount java-time-temporal-TemporalAmount12954] (.minus this12953 java-time-temporal-TemporalAmount12954)))
(clojure.core/defn add-to {:arglists (quote (["java.time.Period" "java.time.temporal.Temporal"]))} (^java.time.temporal.Temporal [^java.time.Period this12955 ^java.time.temporal.Temporal java-time-temporal-Temporal12956] (.addTo this12955 java-time-temporal-Temporal12956)))
(clojure.core/defn to-total-months {:arglists (quote (["java.time.Period"]))} (^long [^java.time.Period this12957] (.toTotalMonths this12957)))
(clojure.core/defn plus-days {:arglists (quote (["java.time.Period" "long"]))} (^java.time.Period [^java.time.Period this12958 ^long long12959] (.plusDays this12958 long12959)))
(clojure.core/defn of-years {:arglists (quote (["int"]))} (^java.time.Period [^java.lang.Integer int12960] (java.time.Period/ofYears int12960)))
(clojure.core/defn get-days {:arglists (quote (["java.time.Period"]))} (^java.lang.Integer [^java.time.Period this12961] (.getDays this12961)))
(clojure.core/defn negated {:arglists (quote (["java.time.Period"]))} (^java.time.Period [^java.time.Period this12962] (.negated this12962)))
(clojure.core/defn get-years {:arglists (quote (["java.time.Period"]))} (^java.lang.Integer [^java.time.Period this12963] (.getYears this12963)))
(clojure.core/defn with-years {:arglists (quote (["java.time.Period" "int"]))} (^java.time.Period [^java.time.Period this12964 ^java.lang.Integer int12965] (.withYears this12964 int12965)))
(clojure.core/defn normalized {:arglists (quote (["java.time.Period"]))} (^java.time.Period [^java.time.Period this12966] (.normalized this12966)))
(clojure.core/defn with-months {:arglists (quote (["java.time.Period" "int"]))} (^java.time.Period [^java.time.Period this12967 ^java.lang.Integer int12968] (.withMonths this12967 int12968)))
(clojure.core/defn between {:arglists (quote (["java.time.LocalDate" "java.time.LocalDate"]))} (^java.time.Period [^java.time.LocalDate java-time-LocalDate12969 ^java.time.LocalDate java-time-LocalDate12970] (java.time.Period/between java-time-LocalDate12969 java-time-LocalDate12970)))
(clojure.core/defn from {:arglists (quote (["java.time.temporal.TemporalAmount"]))} (^java.time.Period [^java.time.temporal.TemporalAmount java-time-temporal-TemporalAmount12971] (java.time.Period/from java-time-temporal-TemporalAmount12971)))
(clojure.core/defn minus-years {:arglists (quote (["java.time.Period" "long"]))} (^java.time.Period [^java.time.Period this12972 ^long long12973] (.minusYears this12972 long12973)))
(clojure.core/defn get-chronology {:arglists (quote (["java.time.Period"]))} (^java.time.chrono.IsoChronology [^java.time.Period this12974] (.getChronology this12974)))
(clojure.core/defn parse {:arglists (quote (["java.lang.CharSequence"]))} (^java.time.Period [^java.lang.CharSequence java-lang-CharSequence12975] (java.time.Period/parse java-lang-CharSequence12975)))
(clojure.core/defn hash-code {:arglists (quote (["java.time.Period"]))} (^java.lang.Integer [^java.time.Period this12976] (.hashCode this12976)))
(clojure.core/defn subtract-from {:arglists (quote (["java.time.Period" "java.time.temporal.Temporal"]))} (^java.time.temporal.Temporal [^java.time.Period this12977 ^java.time.temporal.Temporal java-time-temporal-Temporal12978] (.subtractFrom this12977 java-time-temporal-Temporal12978)))
(clojure.core/defn get {:arglists (quote (["java.time.Period" "java.time.temporal.TemporalUnit"]))} (^long [^java.time.Period this12979 ^java.time.temporal.ChronoUnit java-time-temporal-TemporalUnit12980] (.get this12979 java-time-temporal-TemporalUnit12980)))
(clojure.core/defn equals {:arglists (quote (["java.time.Period" "java.lang.Object"]))} (^java.lang.Boolean [^java.time.Period this12981 ^java.lang.Object java-lang-Object12982] (.equals this12981 java-lang-Object12982)))
(clojure.core/defn plus-years {:arglists (quote (["java.time.Period" "long"]))} (^java.time.Period [^java.time.Period this12983 ^long long12984] (.plusYears this12983 long12984)))
(clojure.core/defn minus-days {:arglists (quote (["java.time.Period" "long"]))} (^java.time.Period [^java.time.Period this12985 ^long long12986] (.minusDays this12985 long12986)))
|
|
b339728cbcd267c52b88221670792109fbd7f3297af2ddc324e39cf64e3269b9 | janestreet/rpc_parallel | start_app.ml | open! Core
open! Async
let backend = (module Backend : Rpc_parallel.Backend)
let backend_and_settings = Rpc_parallel.Backend_and_settings.T ((module Backend), ())
let start_app
?rpc_max_message_size
?rpc_handshake_timeout
?rpc_heartbeat_config
?when_parsing_succeeds
?complete_subcommands
command
=
Rpc_parallel.start_app
?rpc_max_message_size
?rpc_handshake_timeout
?rpc_heartbeat_config
?when_parsing_succeeds
?complete_subcommands
backend_and_settings
command
;;
module For_testing = struct
let initialize = Rpc_parallel.For_testing.initialize backend_and_settings
end
module Expert = struct
let start_master_server_exn
?rpc_max_message_size
?rpc_handshake_timeout
?rpc_heartbeat_config
?pass_name
=
Rpc_parallel.Expert.start_master_server_exn
?rpc_max_message_size
?rpc_handshake_timeout
?rpc_heartbeat_config
?pass_name
backend_and_settings
;;
let worker_command = Rpc_parallel.Expert.worker_command backend
let start_worker_server_exn = Rpc_parallel.Expert.start_worker_server_exn backend
end
| null | https://raw.githubusercontent.com/janestreet/rpc_parallel/968259d389c35aa33cc1c02e089bfc442fb4294d/unauthenticated/start_app.ml | ocaml | open! Core
open! Async
let backend = (module Backend : Rpc_parallel.Backend)
let backend_and_settings = Rpc_parallel.Backend_and_settings.T ((module Backend), ())
let start_app
?rpc_max_message_size
?rpc_handshake_timeout
?rpc_heartbeat_config
?when_parsing_succeeds
?complete_subcommands
command
=
Rpc_parallel.start_app
?rpc_max_message_size
?rpc_handshake_timeout
?rpc_heartbeat_config
?when_parsing_succeeds
?complete_subcommands
backend_and_settings
command
;;
module For_testing = struct
let initialize = Rpc_parallel.For_testing.initialize backend_and_settings
end
module Expert = struct
let start_master_server_exn
?rpc_max_message_size
?rpc_handshake_timeout
?rpc_heartbeat_config
?pass_name
=
Rpc_parallel.Expert.start_master_server_exn
?rpc_max_message_size
?rpc_handshake_timeout
?rpc_heartbeat_config
?pass_name
backend_and_settings
;;
let worker_command = Rpc_parallel.Expert.worker_command backend
let start_worker_server_exn = Rpc_parallel.Expert.start_worker_server_exn backend
end
|
|
5d0760dedbd7cf0d0dd02621d152a9ee01ea02b20cf73dde4ab064f6883479fa | soegaard/metapict | snake.rkt | #lang racket
;;
;; SNAKE
;;
An unfinished experiment . See snakes in the TikZ manual .
; The goal is to make a wiggly curve than can be used to draw wiggly arrows.
; (require "def.rkt" "parameters.rkt" "graph.rkt" "pt-vec.rkt" "curve.rkt")
(require metapict metapict/graph)
(define (wave len amplitude)
(define (f x) (* amplitude (sin (/ (* x 2pi) len))))
(define (df x) (* (/ amplitude 2pi len) (cos (/ (* x 2pi) len))))
(graph f 0 len #:samples 16 #:diff df))
(define (snake p q #:length [len 1] #:amplitude [amplitude (/ 1 pi)])
(def pq (pt- q p))
(def l (norm pq))
(def x (/ l len))
(def n (floor x))
(def w (wave len amplitude))
(def wavy-part (for/fold ([c w]) ([i (in-range 1 n)])
(curve-append c (shifted (* i len) 0 w))))
(def end (end-point wavy-part))
(cond [(< l len) (curve p -- q)]
[else
(def s (cond [(< (dist end (pt l 0)) 1e-10) wavy-part]
[else (curve-append wavy-part (curve end -- (pt l 0)))]))
(shifted p (rotated (angle2 east pq) s))]))
(set-curve-pict-size 200 200)
(with-window (window -5 5 -5 5)
(draw (color "gray" (draw (grid (pt -10 -10) (pt 10 10))))
(snake (pt -2 0) (pt 2 0) #:length 1/2)))
| null | https://raw.githubusercontent.com/soegaard/metapict/47ae265f73cbb92ff3e7bdd61e49f4af17597fdf/metapict/snake.rkt | racket |
SNAKE
The goal is to make a wiggly curve than can be used to draw wiggly arrows.
(require "def.rkt" "parameters.rkt" "graph.rkt" "pt-vec.rkt" "curve.rkt") | #lang racket
An unfinished experiment . See snakes in the TikZ manual .
(require metapict metapict/graph)
(define (wave len amplitude)
(define (f x) (* amplitude (sin (/ (* x 2pi) len))))
(define (df x) (* (/ amplitude 2pi len) (cos (/ (* x 2pi) len))))
(graph f 0 len #:samples 16 #:diff df))
(define (snake p q #:length [len 1] #:amplitude [amplitude (/ 1 pi)])
(def pq (pt- q p))
(def l (norm pq))
(def x (/ l len))
(def n (floor x))
(def w (wave len amplitude))
(def wavy-part (for/fold ([c w]) ([i (in-range 1 n)])
(curve-append c (shifted (* i len) 0 w))))
(def end (end-point wavy-part))
(cond [(< l len) (curve p -- q)]
[else
(def s (cond [(< (dist end (pt l 0)) 1e-10) wavy-part]
[else (curve-append wavy-part (curve end -- (pt l 0)))]))
(shifted p (rotated (angle2 east pq) s))]))
(set-curve-pict-size 200 200)
(with-window (window -5 5 -5 5)
(draw (color "gray" (draw (grid (pt -10 -10) (pt 10 10))))
(snake (pt -2 0) (pt 2 0) #:length 1/2)))
|
d1057c3ab4b39fe0b4316d148488bcc7bea6f8f0bbc2abb0bef086bddfb9884d | lspitzner/brittany | Test534.hs | -- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
runBrittany tabSize text = do
let
config' = staticDefaultConfig
config = config'
{ _conf_layout = (_conf_layout config')
{ _lconfig_indentAmount = coerce tabSize
}
, _conf_forward = forwardOptionsSyntaxExtsEnabled
}
parsePrintModule config text
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test534.hs | haskell | brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } | runBrittany tabSize text = do
let
config' = staticDefaultConfig
config = config'
{ _conf_layout = (_conf_layout config')
{ _lconfig_indentAmount = coerce tabSize
}
, _conf_forward = forwardOptionsSyntaxExtsEnabled
}
parsePrintModule config text
|
b9fc90339fb56420b21dff6e46689d9a640aebe8f6caf836c974228ad844aa44 | bramford/2d-exploration-game | entity.mli | type t
val to_string : t option -> string
val fg : t -> Notty.A.color
val draw : t option -> Notty.image
val is_human : t option -> bool
val make_player : string -> t option -> (t, string) result
val is_player : t option -> bool
val is_specific_player : string -> t option -> bool
val random : int -> t option
| null | https://raw.githubusercontent.com/bramford/2d-exploration-game/0660ced6ec4aa39d4548b0ecc1f20f8269bf4c6b/src/entity.mli | ocaml | type t
val to_string : t option -> string
val fg : t -> Notty.A.color
val draw : t option -> Notty.image
val is_human : t option -> bool
val make_player : string -> t option -> (t, string) result
val is_player : t option -> bool
val is_specific_player : string -> t option -> bool
val random : int -> t option
|
|
3a1dd02d0f63116605c6e9ed99a46f77011852d045ab888e26b266d05c193e1d | clojurebook/ClojureProgramming | types.clj | (ns eventing.types)
(derive 'sales/purchase 'sales/all)
(derive 'sales/purchase 'finance/accounts-receivable)
(derive 'finance/accounts-receivable 'finance/all)
(derive 'finance/all 'events/all)
(derive 'sales/all 'events/all)
(derive 'sales/RFQ 'sales/lead-generation)
(derive 'sales/lead-generation 'sales/all)
(derive 'auth/new-user 'sales/lead-generation)
(derive 'auth/new-user 'security/all)
(derive 'security/all 'events/all)
| null | https://raw.githubusercontent.com/clojurebook/ClojureProgramming/bcc7c58862982a5793e22788fc11a9ed7ffc548f/ch15-couchdb/src/eventing/types.clj | clojure | (ns eventing.types)
(derive 'sales/purchase 'sales/all)
(derive 'sales/purchase 'finance/accounts-receivable)
(derive 'finance/accounts-receivable 'finance/all)
(derive 'finance/all 'events/all)
(derive 'sales/all 'events/all)
(derive 'sales/RFQ 'sales/lead-generation)
(derive 'sales/lead-generation 'sales/all)
(derive 'auth/new-user 'sales/lead-generation)
(derive 'auth/new-user 'security/all)
(derive 'security/all 'events/all)
|
|
5c4a2e23b000ac22f2e3881771981047f0c767e65da8b86277acc39d05ef3c3e | mauricioszabo/repl-tooling | renderer.cljs | (ns repl-tooling.editor-integration.renderer
(:require [reagent.core :as r]
[promesa.core :as p]
[clojure.string :as str]
[repl-tooling.eval :as eval]
[repl-tooling.editor-integration.renderer.protocols :as proto]
[repl-tooling.editor-helpers :as helpers]
[repl-tooling.editor-integration.definition :as def]
[repl-tooling.editor-integration.renderer.interactive :as int]
[repl-tooling.editor-integration.commands :as cmds]
["source-map" :refer [SourceMapConsumer]]))
(defn- parse-inner-root [objs more-fn a-for-more]
(let [inner (cond-> (mapv #(proto/as-html (deref %) % false) objs)
more-fn (conj a-for-more))]
(->> inner
(interpose [:span {:class "whitespace"} " "])
(map #(with-meta %2 {:key %1}) (range)))))
(defn parse-inner-for-map [objs more-fn a-for-more]
(let [sep (cycle [[:span {:class "whitespace"} " "]
[:span {:class "coll whitespace"} ", "]])
inner (->> objs
(mapcat #(-> % deref :obj))
(map #(proto/as-html (deref %) % false)))]
(-> inner
(interleave sep)
butlast
vec
(cond-> more-fn (conj (second sep) a-for-more))
(->> (map #(with-meta %2 {:key %1}) (range))))))
(defn- assert-root [txt]
(if (-> txt first (= :row))
txt
[:row txt]))
(declare txt-for-result)
FIXME : why first - line - only ? is not being used
(defn textual->text [elements first-line-only?]
(let [els (cond->> elements first-line-only? (remove #(and (coll? %) (-> % first (= :row)))))]
(->> els
flatten
(partition 2 1)
(filter #(-> % first (= :text)))
(map second)
(apply str))))
(defn- copy-to-clipboard [ratom editor-state first-line-only?]
(let [copy (-> @editor-state :editor/callbacks (:on-copy #()))]
(-> ratom txt-for-result (textual->text first-line-only?) copy)))
(defn- obj-with-more-fn [more-fn ratom repl editor-state callback]
(more-fn repl (fn [res]
(swap! ratom assoc
:more-fn nil
:expanded? true
:attributes-atom (proto/as-renderable (:attributes res)
repl
editor-state))
(callback))))
(defrecord ObjWithMore [obj-atom more-fn attributes-atom expanded? repl editor-state]
proto/Renderable
(as-text [_ ratom root?]
(let [obj (assert-root (proto/as-text @obj-atom obj-atom root?))]
(if expanded?
(conj obj (proto/as-text @attributes-atom attributes-atom root?))
(conj obj [:button "..." #(obj-with-more-fn more-fn ratom repl editor-state %)]))))
(as-html [_ ratom root?]
[:div {:class ["browseable"]}
[:div {:class ["object"]}
(proto/as-html @obj-atom obj-atom root?)
(when more-fn
[:a {:href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(obj-with-more-fn more-fn ratom repl editor-state identity))}
(when root? "...")])]
(when (and root? expanded?)
[:div {:class "row children"}
[proto/as-html @attributes-atom attributes-atom true]])]))
(declare ->indexed)
(defn- reset-atom [repl ratom obj result editor-state]
(let [new-idx (->indexed result repl editor-state)]
(swap! ratom
(fn [indexed]
(assoc indexed
:obj (vec (concat obj (:obj new-idx)))
:more-fn (:more-fn new-idx))))))
(defn- link-to-copy [ratom editor-state first-line-only?]
[:a {:class "icon clipboard"
:href "#"
:on-click
(fn [^js evt]
(.preventDefault evt)
(.stopPropagation evt)
(copy-to-clipboard ratom editor-state first-line-only?))}])
(defrecord Indexed [open obj close kind expanded? more-fn repl editor-state]
proto/Renderable
(as-html [_ ratom root?]
(let [a-for-more [:a {:href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(more-fn repl false #(reset-atom repl ratom obj
% editor-state)))}
"..."]]
[:div {:class ["row" kind]}
[:div {:class ["coll" kind]}
(when root?
[:a {:class ["chevron" (if expanded? "opened" "closed")] :href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(swap! ratom update :expanded? not))}])
[:div {:class "delim opening"} open]
[:div {:class "inner"} (if (= "map" kind)
(parse-inner-for-map obj more-fn a-for-more)
(parse-inner-root obj more-fn a-for-more))]
[:div {:class "delim closing"} close]
(when root?
[link-to-copy ratom editor-state true])]
(when (and root? expanded?)
[:div {:class "children"}
[:<>
(cond-> (mapv #(proto/as-html (deref %) % true) obj)
more-fn (conj a-for-more)
:then (->> (map (fn [i e] [:div {:key i :class "row"} e]) (range))))]])]))
(as-text [_ ratom root?]
(let [children (map #(proto/as-text @% % false) obj)
toggle #(do (swap! ratom update :expanded? not) (%))
extract-map #(-> % (textual->text false)
(str/replace #"^\[" "")
(str/replace #"\]$" ""))
txt (if (= "map" kind)
[:text (->> children
(map extract-map)
(str/join ", "))]
[:text (->> children (map textual->text) (str/join " "))])
more-callback (fn [callback]
(more-fn repl false
#(do
(reset-atom repl ratom obj % editor-state)
(callback))))
complete-txt (delay (if more-fn
(update txt 1 #(str open % " ..." close))
(update txt 1 #(str open % close))))
root-part (delay [:expand (if expanded? "-" "+") toggle])
rows (cond
(not root?) @complete-txt
more-fn [:row
@root-part
(update txt 1 #(str open % " "))
[:button "..." more-callback]
[:text close]]
:else [:row @root-part @complete-txt])]
(if expanded?
(cond-> (apply conj rows (map #(assert-root (proto/as-text @% % true)) obj))
more-fn (conj [:row [:button "..." more-callback]]))
rows))))
(defrecord Leaf [obj editor-state]
proto/Renderable
(as-html [_ ratom root?]
(let [tp (cond
(string? obj) "string"
(number? obj) "number"
(boolean? obj) "bool"
(nil? obj) "nil"
:else "other")]
[:div {:class tp} (pr-str obj) (when root? [link-to-copy ratom editor-state true])]))
(as-text [_ _ _]
[:text (pr-str obj)]))
(defn- ->indexed [obj repl editor-state]
(let [more-fn (eval/get-more-fn obj)
children (mapv #(proto/as-renderable % repl editor-state) (eval/without-ellision obj))]
(cond
(vector? obj) (->Indexed "[" children "]" "vector" false more-fn repl editor-state)
(set? obj) (->Indexed "#{" (vec children) "}" "set" false more-fn repl editor-state)
(map? obj) (->Indexed "{" (vec children) "}" "map" false more-fn repl editor-state)
(seq? obj) (->Indexed "(" children ")" "list" false more-fn repl editor-state))))
(defrecord IncompleteStr [string repl editor-state]
proto/Renderable
(as-html [_ ratom root?]
[:div {:class "string big"}
[:span (-> string eval/without-ellision pr-str (str/replace #"\"$" ""))]
(when-let [get-more (eval/get-more-fn string)]
[:a {:href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(get-more repl #(swap! ratom assoc :string %)))}
"..."])
"\""
(when root? [link-to-copy ratom editor-state true])])
(as-text [_ ratom root?]
(if root?
[:row
[:text (-> string eval/without-ellision pr-str (str/replace #"\"$" ""))]
[:button "..." #(let [f (eval/get-more-fn string)]
(f repl (fn [obj]
(if (string? obj)
(reset! ratom (->Leaf obj editor-state))
(swap! ratom assoc :string obj))
(%))))]
[:text "\""]]
[:text (pr-str string)])))
(defrecord Tagged [tag subelement editor-state open?]
proto/Renderable
(as-text [_ ratom root?]
(let [toggle #(do (swap! ratom update :open? not) (%))]
(if open?
[:row [:expand "-" toggle]
[:text tag] (proto/as-text @subelement subelement false)
(assert-root (proto/as-text @subelement subelement true))]
[:row [:expand "+" toggle] [:text tag] (proto/as-text @subelement subelement false)])))
(as-html [_ ratom root?]
(let [will-be-open? (and root? open?)
copy-elem [link-to-copy ratom editor-state true]]
[:div {:class "tagged"}
(when root?
[:a {:class ["chevron" (if open? "opened" "closed")] :href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(swap! ratom update :open? not))}])
[:div {:class [(when will-be-open? "row")]}
[:div {:class "tag"} tag (when will-be-open? copy-elem)]
[:div {:class [(when will-be-open? "tag children")]}
[proto/as-html @subelement subelement will-be-open?]]
(when (and (not open?) root?) copy-elem)]])))
(defrecord IncompleteObj [incomplete repl editor-state]
proto/Renderable
(as-text [_ ratom _]
(let [more (eval/get-more-fn incomplete)]
[:button "..." (fn [callback]
(more repl #(do
(reset! ratom @(proto/as-renderable % repl editor-state))
(callback))))]))
(as-html [_ ratom _]
(let [more (eval/get-more-fn incomplete)]
[:div {:class "incomplete-obj"}
[:a {:href "#" :on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(more repl #(reset! ratom @(proto/as-renderable % repl editor-state))))}
"..."]])))
(defn- link-for-more-trace [repl ratom more-trace more-str callback?]
(cond
more-trace
(fn [e]
(when-not callback? (.preventDefault e) (.stopPropagation e))
(more-trace repl #(do
(reset! ratom %)
(when callback? (e)))))
more-str
(fn [e]
(when-not callback? (.preventDefault e) (.stopPropagation e))
(more-str repl #(do
(swap! ratom assoc 2 %)
(when callback? (e)))))))
(defn- trace-span [file row]
[:span {:class "file"} " (" file ":" row ")"])
(defn- trace-link [var file row editor-state cache-exists?]
(let [{:keys [open-editor notify]} (:editor/callbacks @editor-state)
{:keys [eql]} (:editor/features @editor-state)
aux-repl (:clj/aux @editor-state)]
[:a.file {:href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(if cache-exists?
(open-editor {:file-name file :line (dec row)})
(p/let [exists? (cmds/run-callback! editor-state
:file-exists file)]
(if exists?
(open-editor {:file-name file :line (dec row)})
(def/goto-definition editor-state
{:ex/function-name var
:ex/filename file
:ex/row row})))))}
" (" file ":" row ")"]))
(defn- prepare-source-map [editor-state js-filename]
(p/let [run-callback (:run-callback @editor-state)
file-name (str js-filename ".map")
contents (run-callback :read-file file-name)]
(when contents
(new SourceMapConsumer contents))))
(defn- resolve-source [^js sourcemap row col]
(when-let [source (some-> sourcemap
(.originalPositionFor #js {:line (int row)
:column (int col)}))]
(when (.-source ^js source)
[(.-source ^js source) (.-line ^js source) (.-column ^js source)])))
(defn- demunge-js-name [js-name]
(-> js-name
(str/replace #"\$" ".")
(str/replace #"(.*)\.(.*)$" "$1/$2")
demunge))
(defn- trace-string [p-source idx ratom editor-state]
(let [{:keys [open-editor notify]} (:editor/callbacks @editor-state)
aux-repl (:clj/aux @editor-state)
trace (get-in @ratom [:obj :trace idx])
info (str/replace trace #"\(.*" "")
filename-match (some-> (re-find #"\(.*\)" trace)
(str/replace #"[\(\)]" ""))
local-row (r/atom (str/split filename-match #":"))
loaded? (r/atom false)
fun
(fn []
(let [[file row col] @local-row]
(when-not @loaded?
(p/let [[file row col] @local-row
file-contents (p-source file)
data (resolve-source file-contents row col)]
(reset! loaded? true)
(when data (reset! local-row data))))
(if filename-match
[:span.class (demunge-js-name info) "("
[:a.file {:href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(p/let [exists? (cmds/run-callback! editor-state
:file-exists file)]
(if exists?
(open-editor {:file-name file
:line (dec row)
:column (dec col)})
; FIXME - This may be possible now...
; (.. (definition/resolve-possible-path
; aux-repl {:file file :line row})
; (then #(open-editor (assoc %
: line ( dec row )
: column ( ) ) ) )
(notify {:type :error
:title "Can't find file to go"}))))}
file ":" row ":" col]
")"]
[:span.stack-line trace])))]
[:div {:key idx :class ["row" "clj-stack"]} [fun]]))
(defn- to-trace-row [p-source repl ratom editor-state idx trace]
(let [[class method file row] trace
link-for-more (link-for-more-trace repl
(r/cursor ratom [:obj :trace idx])
(eval/get-more-fn trace)
(eval/get-more-fn file)
false)
clj-file? (re-find #"\.clj.?$" (str file))
var (cond-> (str class) clj-file? demunge)]
(cond
(string? trace)
(trace-string p-source idx ratom editor-state)
link-for-more
[:div {:key idx :class ["row" "incomplete"]}
[:div "in " [:a {:href "#" :on-click link-for-more} "..."]]]
(not= -1 row)
[:div {:key idx :class ["row" (if clj-file? "clj-stack" "stack")]}
[:div
"in "
(when var [:span {:class "class"} var])
(when-not (or clj-file? (nil? method))
[:span {:class "method"} "." method])
(if clj-file?
(trace-link var file row editor-state nil)
(let [exists? (r/atom nil)
res (fn []
(if @exists?
(trace-link var file row editor-state true)
(trace-span file row)))]
(.then (cmds/run-callback! editor-state :file-exists (str file))
#(reset! exists? %))
[res]))]])))
; :else (trace-span file row))]])))
(defn- to-trace-row-txt [repl ratom idx trace]
(let [[class method file row] trace
link-for-more (link-for-more-trace repl
(r/cursor ratom [:obj :trace idx])
(eval/get-more-fn trace)
(eval/get-more-fn file)
true)
clj-file? (re-find #"\.clj?$" (str file))]
(cond
(string? trace) [:row [:text trace]]
link-for-more [:row [:text "in "] [:button "..." link-for-more]]
(not= -1 row)
[:row
[:text
(str "in " (cond-> (str class) clj-file? demunge)
(when-not clj-file? (str "." method))
" (" file ":" row ")")]])))
(defrecord ExceptionObj [obj add-data repl editor-state]
proto/Renderable
(as-text [_ ratom root?]
(let [{:keys [type message trace]} obj
ex (proto/as-text @message message true)
ex (if (-> ex first (= :row))
(update-in ex [1 1] #(str type ": " %))
[:row (update ex 1 #(str type ": " %))])
traces (map (partial to-trace-row-txt repl ratom)
(range)
(eval/without-ellision trace))]
(if add-data
(apply conj ex (proto/as-text @add-data add-data root?) traces)
(apply conj ex traces))))
(as-html [_ ratom root?]
(let [{:keys [type message trace]} obj
p-source (memoize #(prepare-source-map editor-state %))]
[:div {:class "exception row"}
[:div {:class "description"}
[:span {:class "ex-kind"} (str type)] ": " [proto/as-html @message message root?]]
(when (and add-data root?)
[:div {:class "children additional"}
[proto/as-html @add-data add-data root?]])
(when root?
[:div {:class "children"}
(doall
(map (partial to-trace-row p-source repl ratom editor-state)
(range)
(eval/without-ellision trace)))
(when-let [more (eval/get-more-fn trace)]
[:a {:href "#" :on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(more repl #(swap! ratom assoc-in [:obj :trace] %)))}
"..."])])])))
(defrecord Patchable [id value]
proto/Renderable
(as-text [_ ratom root?] (proto/as-text @value value root?))
(as-html [self ratom root?]
[proto/as-html @(:value @ratom) (:value @ratom) root?]))
(extend-protocol proto/Parseable
helpers/Interactive
(as-renderable [self repl editor-state]
(r/atom (int/->Interactive (.-edn self) repl editor-state)))
helpers/Error
(as-renderable [self repl editor-state]
(let [obj (update self :message proto/as-renderable repl editor-state)
add-data (some-> self :add-data not-empty (proto/as-renderable repl editor-state))]
(r/atom (->ExceptionObj obj add-data repl editor-state))))
helpers/IncompleteObj
(as-renderable [self repl editor-state]
(r/atom (->IncompleteObj self repl editor-state)))
helpers/IncompleteStr
(as-renderable [self repl editor-state]
(r/atom (->IncompleteStr self repl editor-state)))
helpers/Browseable
(as-renderable [self repl editor-state]
(let [{:keys [object attributes]} self]
(r/atom (->ObjWithMore (proto/as-renderable object repl editor-state)
(eval/get-more-fn self)
(proto/as-renderable attributes repl editor-state)
false
repl
editor-state))))
helpers/WithTag
(as-renderable [self repl editor-state]
(let [tag (helpers/tag self)
subelement (-> self helpers/obj (proto/as-renderable repl editor-state))]
(r/atom (->Tagged tag subelement editor-state false))))
helpers/LiteralRender
(as-renderable [obj repl editor-state]
(r/atom (->Leaf obj editor-state)))
helpers/Patchable
(as-renderable [{:keys [id value]} repl editor-state]
(r/atom (->Patchable id (proto/as-renderable value repl editor-state))))
default
(as-renderable [obj repl editor-state]
(r/atom
(cond
(coll? obj) (->indexed obj repl editor-state)
:else (->Leaf obj editor-state)))))
(defn parse-result
"Will parse a result that comes from the REPL in a r/atom so that
it'll be suitable to be rendered with `view-for-result`"
[result repl editor-state]
(let [parsed (helpers/parse-result result)]
(if (contains? parsed :result)
(proto/as-renderable (:result parsed) repl editor-state)
(let [error (:error parsed)
; FIXME: is this really necessary? Can we use the exception renderer?
ex (cond-> error
(:ex error) :ex
(->> error :ex (instance? helpers/Browseable)) :object)]
(with-meta (proto/as-renderable ex repl editor-state) {:error true})))))
(defn view-for-result
"Renders a view for a result. If it's an error, will return a view
suitable for error backtraces. If it's a success, will return a success
view. Expects a r/atom that comes from `parse-result`"
[state]
[proto/as-html @state state true])
(defn txt-for-result
"Renders a view for a result, but in textual format. This view will be
in a pseudo-hiccup format, like so:
[:row [:expand \"+\" some-fn]
[:text \"(1 2 3 4 5 6\"]
[:button \"...\" some-fn]
[:text \")\"]]
Where :row defines a row of text, :text a fragment, :button a text that's
associated with some data (to be able to ellide things) and :expand is to
make a placeholder that we can expand (+) or collapse (-) the structure"
[state]
(assert-root (proto/as-text @state state true)))
(defn- parse-funs [funs last-elem curr-text elem]
(let [txt-size (-> elem (nth 1) count)
curr-row (count curr-text)
fun (peek elem)]
(reduce (fn [funs col] (assoc funs [last-elem col] fun))
funs (range curr-row (+ curr-row txt-size)))))
(defn- parse-elem [position lines funs depth]
(let [[elem text] position
last-elem (-> lines count dec)
indent (->> depth (* 2) range (map (constantly " ")) (apply str) delay)
last-line (peek lines)
curr-text (if (empty? last-line)
@indent
last-line)]
(case elem
:row (recur (rest position) (conj lines "") funs (inc depth))
:text [(assoc lines last-elem (str curr-text text)) funs]
:button [(assoc lines last-elem (str curr-text text))
(parse-funs funs last-elem curr-text position)]
:expand [(assoc lines last-elem (str curr-text text " "))
(parse-funs funs last-elem curr-text position)]
(reduce (fn [[lines funs] position] (parse-elem position lines funs depth))
[lines funs] position))))
(defn repr->lines [repr]
(parse-elem repr [] {} -1))
| null | https://raw.githubusercontent.com/mauricioszabo/repl-tooling/1cea9b411cc118d71266cb8e035e146325baf410/src/repl_tooling/editor_integration/renderer.cljs | clojure | FIXME - This may be possible now...
(.. (definition/resolve-possible-path
aux-repl {:file file :line row})
(then #(open-editor (assoc %
:else (trace-span file row))]])))
FIXME: is this really necessary? Can we use the exception renderer? | (ns repl-tooling.editor-integration.renderer
(:require [reagent.core :as r]
[promesa.core :as p]
[clojure.string :as str]
[repl-tooling.eval :as eval]
[repl-tooling.editor-integration.renderer.protocols :as proto]
[repl-tooling.editor-helpers :as helpers]
[repl-tooling.editor-integration.definition :as def]
[repl-tooling.editor-integration.renderer.interactive :as int]
[repl-tooling.editor-integration.commands :as cmds]
["source-map" :refer [SourceMapConsumer]]))
(defn- parse-inner-root [objs more-fn a-for-more]
(let [inner (cond-> (mapv #(proto/as-html (deref %) % false) objs)
more-fn (conj a-for-more))]
(->> inner
(interpose [:span {:class "whitespace"} " "])
(map #(with-meta %2 {:key %1}) (range)))))
(defn parse-inner-for-map [objs more-fn a-for-more]
(let [sep (cycle [[:span {:class "whitespace"} " "]
[:span {:class "coll whitespace"} ", "]])
inner (->> objs
(mapcat #(-> % deref :obj))
(map #(proto/as-html (deref %) % false)))]
(-> inner
(interleave sep)
butlast
vec
(cond-> more-fn (conj (second sep) a-for-more))
(->> (map #(with-meta %2 {:key %1}) (range))))))
(defn- assert-root [txt]
(if (-> txt first (= :row))
txt
[:row txt]))
(declare txt-for-result)
FIXME : why first - line - only ? is not being used
(defn textual->text [elements first-line-only?]
(let [els (cond->> elements first-line-only? (remove #(and (coll? %) (-> % first (= :row)))))]
(->> els
flatten
(partition 2 1)
(filter #(-> % first (= :text)))
(map second)
(apply str))))
(defn- copy-to-clipboard [ratom editor-state first-line-only?]
(let [copy (-> @editor-state :editor/callbacks (:on-copy #()))]
(-> ratom txt-for-result (textual->text first-line-only?) copy)))
(defn- obj-with-more-fn [more-fn ratom repl editor-state callback]
(more-fn repl (fn [res]
(swap! ratom assoc
:more-fn nil
:expanded? true
:attributes-atom (proto/as-renderable (:attributes res)
repl
editor-state))
(callback))))
(defrecord ObjWithMore [obj-atom more-fn attributes-atom expanded? repl editor-state]
proto/Renderable
(as-text [_ ratom root?]
(let [obj (assert-root (proto/as-text @obj-atom obj-atom root?))]
(if expanded?
(conj obj (proto/as-text @attributes-atom attributes-atom root?))
(conj obj [:button "..." #(obj-with-more-fn more-fn ratom repl editor-state %)]))))
(as-html [_ ratom root?]
[:div {:class ["browseable"]}
[:div {:class ["object"]}
(proto/as-html @obj-atom obj-atom root?)
(when more-fn
[:a {:href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(obj-with-more-fn more-fn ratom repl editor-state identity))}
(when root? "...")])]
(when (and root? expanded?)
[:div {:class "row children"}
[proto/as-html @attributes-atom attributes-atom true]])]))
(declare ->indexed)
(defn- reset-atom [repl ratom obj result editor-state]
(let [new-idx (->indexed result repl editor-state)]
(swap! ratom
(fn [indexed]
(assoc indexed
:obj (vec (concat obj (:obj new-idx)))
:more-fn (:more-fn new-idx))))))
(defn- link-to-copy [ratom editor-state first-line-only?]
[:a {:class "icon clipboard"
:href "#"
:on-click
(fn [^js evt]
(.preventDefault evt)
(.stopPropagation evt)
(copy-to-clipboard ratom editor-state first-line-only?))}])
(defrecord Indexed [open obj close kind expanded? more-fn repl editor-state]
proto/Renderable
(as-html [_ ratom root?]
(let [a-for-more [:a {:href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(more-fn repl false #(reset-atom repl ratom obj
% editor-state)))}
"..."]]
[:div {:class ["row" kind]}
[:div {:class ["coll" kind]}
(when root?
[:a {:class ["chevron" (if expanded? "opened" "closed")] :href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(swap! ratom update :expanded? not))}])
[:div {:class "delim opening"} open]
[:div {:class "inner"} (if (= "map" kind)
(parse-inner-for-map obj more-fn a-for-more)
(parse-inner-root obj more-fn a-for-more))]
[:div {:class "delim closing"} close]
(when root?
[link-to-copy ratom editor-state true])]
(when (and root? expanded?)
[:div {:class "children"}
[:<>
(cond-> (mapv #(proto/as-html (deref %) % true) obj)
more-fn (conj a-for-more)
:then (->> (map (fn [i e] [:div {:key i :class "row"} e]) (range))))]])]))
(as-text [_ ratom root?]
(let [children (map #(proto/as-text @% % false) obj)
toggle #(do (swap! ratom update :expanded? not) (%))
extract-map #(-> % (textual->text false)
(str/replace #"^\[" "")
(str/replace #"\]$" ""))
txt (if (= "map" kind)
[:text (->> children
(map extract-map)
(str/join ", "))]
[:text (->> children (map textual->text) (str/join " "))])
more-callback (fn [callback]
(more-fn repl false
#(do
(reset-atom repl ratom obj % editor-state)
(callback))))
complete-txt (delay (if more-fn
(update txt 1 #(str open % " ..." close))
(update txt 1 #(str open % close))))
root-part (delay [:expand (if expanded? "-" "+") toggle])
rows (cond
(not root?) @complete-txt
more-fn [:row
@root-part
(update txt 1 #(str open % " "))
[:button "..." more-callback]
[:text close]]
:else [:row @root-part @complete-txt])]
(if expanded?
(cond-> (apply conj rows (map #(assert-root (proto/as-text @% % true)) obj))
more-fn (conj [:row [:button "..." more-callback]]))
rows))))
(defrecord Leaf [obj editor-state]
proto/Renderable
(as-html [_ ratom root?]
(let [tp (cond
(string? obj) "string"
(number? obj) "number"
(boolean? obj) "bool"
(nil? obj) "nil"
:else "other")]
[:div {:class tp} (pr-str obj) (when root? [link-to-copy ratom editor-state true])]))
(as-text [_ _ _]
[:text (pr-str obj)]))
(defn- ->indexed [obj repl editor-state]
(let [more-fn (eval/get-more-fn obj)
children (mapv #(proto/as-renderable % repl editor-state) (eval/without-ellision obj))]
(cond
(vector? obj) (->Indexed "[" children "]" "vector" false more-fn repl editor-state)
(set? obj) (->Indexed "#{" (vec children) "}" "set" false more-fn repl editor-state)
(map? obj) (->Indexed "{" (vec children) "}" "map" false more-fn repl editor-state)
(seq? obj) (->Indexed "(" children ")" "list" false more-fn repl editor-state))))
(defrecord IncompleteStr [string repl editor-state]
proto/Renderable
(as-html [_ ratom root?]
[:div {:class "string big"}
[:span (-> string eval/without-ellision pr-str (str/replace #"\"$" ""))]
(when-let [get-more (eval/get-more-fn string)]
[:a {:href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(get-more repl #(swap! ratom assoc :string %)))}
"..."])
"\""
(when root? [link-to-copy ratom editor-state true])])
(as-text [_ ratom root?]
(if root?
[:row
[:text (-> string eval/without-ellision pr-str (str/replace #"\"$" ""))]
[:button "..." #(let [f (eval/get-more-fn string)]
(f repl (fn [obj]
(if (string? obj)
(reset! ratom (->Leaf obj editor-state))
(swap! ratom assoc :string obj))
(%))))]
[:text "\""]]
[:text (pr-str string)])))
(defrecord Tagged [tag subelement editor-state open?]
proto/Renderable
(as-text [_ ratom root?]
(let [toggle #(do (swap! ratom update :open? not) (%))]
(if open?
[:row [:expand "-" toggle]
[:text tag] (proto/as-text @subelement subelement false)
(assert-root (proto/as-text @subelement subelement true))]
[:row [:expand "+" toggle] [:text tag] (proto/as-text @subelement subelement false)])))
(as-html [_ ratom root?]
(let [will-be-open? (and root? open?)
copy-elem [link-to-copy ratom editor-state true]]
[:div {:class "tagged"}
(when root?
[:a {:class ["chevron" (if open? "opened" "closed")] :href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(swap! ratom update :open? not))}])
[:div {:class [(when will-be-open? "row")]}
[:div {:class "tag"} tag (when will-be-open? copy-elem)]
[:div {:class [(when will-be-open? "tag children")]}
[proto/as-html @subelement subelement will-be-open?]]
(when (and (not open?) root?) copy-elem)]])))
(defrecord IncompleteObj [incomplete repl editor-state]
proto/Renderable
(as-text [_ ratom _]
(let [more (eval/get-more-fn incomplete)]
[:button "..." (fn [callback]
(more repl #(do
(reset! ratom @(proto/as-renderable % repl editor-state))
(callback))))]))
(as-html [_ ratom _]
(let [more (eval/get-more-fn incomplete)]
[:div {:class "incomplete-obj"}
[:a {:href "#" :on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(more repl #(reset! ratom @(proto/as-renderable % repl editor-state))))}
"..."]])))
(defn- link-for-more-trace [repl ratom more-trace more-str callback?]
(cond
more-trace
(fn [e]
(when-not callback? (.preventDefault e) (.stopPropagation e))
(more-trace repl #(do
(reset! ratom %)
(when callback? (e)))))
more-str
(fn [e]
(when-not callback? (.preventDefault e) (.stopPropagation e))
(more-str repl #(do
(swap! ratom assoc 2 %)
(when callback? (e)))))))
(defn- trace-span [file row]
[:span {:class "file"} " (" file ":" row ")"])
(defn- trace-link [var file row editor-state cache-exists?]
(let [{:keys [open-editor notify]} (:editor/callbacks @editor-state)
{:keys [eql]} (:editor/features @editor-state)
aux-repl (:clj/aux @editor-state)]
[:a.file {:href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(if cache-exists?
(open-editor {:file-name file :line (dec row)})
(p/let [exists? (cmds/run-callback! editor-state
:file-exists file)]
(if exists?
(open-editor {:file-name file :line (dec row)})
(def/goto-definition editor-state
{:ex/function-name var
:ex/filename file
:ex/row row})))))}
" (" file ":" row ")"]))
(defn- prepare-source-map [editor-state js-filename]
(p/let [run-callback (:run-callback @editor-state)
file-name (str js-filename ".map")
contents (run-callback :read-file file-name)]
(when contents
(new SourceMapConsumer contents))))
(defn- resolve-source [^js sourcemap row col]
(when-let [source (some-> sourcemap
(.originalPositionFor #js {:line (int row)
:column (int col)}))]
(when (.-source ^js source)
[(.-source ^js source) (.-line ^js source) (.-column ^js source)])))
(defn- demunge-js-name [js-name]
(-> js-name
(str/replace #"\$" ".")
(str/replace #"(.*)\.(.*)$" "$1/$2")
demunge))
(defn- trace-string [p-source idx ratom editor-state]
(let [{:keys [open-editor notify]} (:editor/callbacks @editor-state)
aux-repl (:clj/aux @editor-state)
trace (get-in @ratom [:obj :trace idx])
info (str/replace trace #"\(.*" "")
filename-match (some-> (re-find #"\(.*\)" trace)
(str/replace #"[\(\)]" ""))
local-row (r/atom (str/split filename-match #":"))
loaded? (r/atom false)
fun
(fn []
(let [[file row col] @local-row]
(when-not @loaded?
(p/let [[file row col] @local-row
file-contents (p-source file)
data (resolve-source file-contents row col)]
(reset! loaded? true)
(when data (reset! local-row data))))
(if filename-match
[:span.class (demunge-js-name info) "("
[:a.file {:href "#"
:on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(p/let [exists? (cmds/run-callback! editor-state
:file-exists file)]
(if exists?
(open-editor {:file-name file
:line (dec row)
:column (dec col)})
: line ( dec row )
: column ( ) ) ) )
(notify {:type :error
:title "Can't find file to go"}))))}
file ":" row ":" col]
")"]
[:span.stack-line trace])))]
[:div {:key idx :class ["row" "clj-stack"]} [fun]]))
(defn- to-trace-row [p-source repl ratom editor-state idx trace]
(let [[class method file row] trace
link-for-more (link-for-more-trace repl
(r/cursor ratom [:obj :trace idx])
(eval/get-more-fn trace)
(eval/get-more-fn file)
false)
clj-file? (re-find #"\.clj.?$" (str file))
var (cond-> (str class) clj-file? demunge)]
(cond
(string? trace)
(trace-string p-source idx ratom editor-state)
link-for-more
[:div {:key idx :class ["row" "incomplete"]}
[:div "in " [:a {:href "#" :on-click link-for-more} "..."]]]
(not= -1 row)
[:div {:key idx :class ["row" (if clj-file? "clj-stack" "stack")]}
[:div
"in "
(when var [:span {:class "class"} var])
(when-not (or clj-file? (nil? method))
[:span {:class "method"} "." method])
(if clj-file?
(trace-link var file row editor-state nil)
(let [exists? (r/atom nil)
res (fn []
(if @exists?
(trace-link var file row editor-state true)
(trace-span file row)))]
(.then (cmds/run-callback! editor-state :file-exists (str file))
#(reset! exists? %))
[res]))]])))
(defn- to-trace-row-txt [repl ratom idx trace]
(let [[class method file row] trace
link-for-more (link-for-more-trace repl
(r/cursor ratom [:obj :trace idx])
(eval/get-more-fn trace)
(eval/get-more-fn file)
true)
clj-file? (re-find #"\.clj?$" (str file))]
(cond
(string? trace) [:row [:text trace]]
link-for-more [:row [:text "in "] [:button "..." link-for-more]]
(not= -1 row)
[:row
[:text
(str "in " (cond-> (str class) clj-file? demunge)
(when-not clj-file? (str "." method))
" (" file ":" row ")")]])))
(defrecord ExceptionObj [obj add-data repl editor-state]
proto/Renderable
(as-text [_ ratom root?]
(let [{:keys [type message trace]} obj
ex (proto/as-text @message message true)
ex (if (-> ex first (= :row))
(update-in ex [1 1] #(str type ": " %))
[:row (update ex 1 #(str type ": " %))])
traces (map (partial to-trace-row-txt repl ratom)
(range)
(eval/without-ellision trace))]
(if add-data
(apply conj ex (proto/as-text @add-data add-data root?) traces)
(apply conj ex traces))))
(as-html [_ ratom root?]
(let [{:keys [type message trace]} obj
p-source (memoize #(prepare-source-map editor-state %))]
[:div {:class "exception row"}
[:div {:class "description"}
[:span {:class "ex-kind"} (str type)] ": " [proto/as-html @message message root?]]
(when (and add-data root?)
[:div {:class "children additional"}
[proto/as-html @add-data add-data root?]])
(when root?
[:div {:class "children"}
(doall
(map (partial to-trace-row p-source repl ratom editor-state)
(range)
(eval/without-ellision trace)))
(when-let [more (eval/get-more-fn trace)]
[:a {:href "#" :on-click (fn [e]
(.preventDefault e)
(.stopPropagation e)
(more repl #(swap! ratom assoc-in [:obj :trace] %)))}
"..."])])])))
(defrecord Patchable [id value]
proto/Renderable
(as-text [_ ratom root?] (proto/as-text @value value root?))
(as-html [self ratom root?]
[proto/as-html @(:value @ratom) (:value @ratom) root?]))
(extend-protocol proto/Parseable
helpers/Interactive
(as-renderable [self repl editor-state]
(r/atom (int/->Interactive (.-edn self) repl editor-state)))
helpers/Error
(as-renderable [self repl editor-state]
(let [obj (update self :message proto/as-renderable repl editor-state)
add-data (some-> self :add-data not-empty (proto/as-renderable repl editor-state))]
(r/atom (->ExceptionObj obj add-data repl editor-state))))
helpers/IncompleteObj
(as-renderable [self repl editor-state]
(r/atom (->IncompleteObj self repl editor-state)))
helpers/IncompleteStr
(as-renderable [self repl editor-state]
(r/atom (->IncompleteStr self repl editor-state)))
helpers/Browseable
(as-renderable [self repl editor-state]
(let [{:keys [object attributes]} self]
(r/atom (->ObjWithMore (proto/as-renderable object repl editor-state)
(eval/get-more-fn self)
(proto/as-renderable attributes repl editor-state)
false
repl
editor-state))))
helpers/WithTag
(as-renderable [self repl editor-state]
(let [tag (helpers/tag self)
subelement (-> self helpers/obj (proto/as-renderable repl editor-state))]
(r/atom (->Tagged tag subelement editor-state false))))
helpers/LiteralRender
(as-renderable [obj repl editor-state]
(r/atom (->Leaf obj editor-state)))
helpers/Patchable
(as-renderable [{:keys [id value]} repl editor-state]
(r/atom (->Patchable id (proto/as-renderable value repl editor-state))))
default
(as-renderable [obj repl editor-state]
(r/atom
(cond
(coll? obj) (->indexed obj repl editor-state)
:else (->Leaf obj editor-state)))))
(defn parse-result
"Will parse a result that comes from the REPL in a r/atom so that
it'll be suitable to be rendered with `view-for-result`"
[result repl editor-state]
(let [parsed (helpers/parse-result result)]
(if (contains? parsed :result)
(proto/as-renderable (:result parsed) repl editor-state)
(let [error (:error parsed)
ex (cond-> error
(:ex error) :ex
(->> error :ex (instance? helpers/Browseable)) :object)]
(with-meta (proto/as-renderable ex repl editor-state) {:error true})))))
(defn view-for-result
"Renders a view for a result. If it's an error, will return a view
suitable for error backtraces. If it's a success, will return a success
view. Expects a r/atom that comes from `parse-result`"
[state]
[proto/as-html @state state true])
(defn txt-for-result
"Renders a view for a result, but in textual format. This view will be
in a pseudo-hiccup format, like so:
[:row [:expand \"+\" some-fn]
[:text \"(1 2 3 4 5 6\"]
[:button \"...\" some-fn]
[:text \")\"]]
Where :row defines a row of text, :text a fragment, :button a text that's
associated with some data (to be able to ellide things) and :expand is to
make a placeholder that we can expand (+) or collapse (-) the structure"
[state]
(assert-root (proto/as-text @state state true)))
(defn- parse-funs [funs last-elem curr-text elem]
(let [txt-size (-> elem (nth 1) count)
curr-row (count curr-text)
fun (peek elem)]
(reduce (fn [funs col] (assoc funs [last-elem col] fun))
funs (range curr-row (+ curr-row txt-size)))))
(defn- parse-elem [position lines funs depth]
(let [[elem text] position
last-elem (-> lines count dec)
indent (->> depth (* 2) range (map (constantly " ")) (apply str) delay)
last-line (peek lines)
curr-text (if (empty? last-line)
@indent
last-line)]
(case elem
:row (recur (rest position) (conj lines "") funs (inc depth))
:text [(assoc lines last-elem (str curr-text text)) funs]
:button [(assoc lines last-elem (str curr-text text))
(parse-funs funs last-elem curr-text position)]
:expand [(assoc lines last-elem (str curr-text text " "))
(parse-funs funs last-elem curr-text position)]
(reduce (fn [[lines funs] position] (parse-elem position lines funs depth))
[lines funs] position))))
(defn repr->lines [repr]
(parse-elem repr [] {} -1))
|
e7bbfde2977d50b684c79cbd2a8200291204eae28a90342d0e404638c899ce75 | kelsey-sorrels/robinson | fs.clj | (ns robinson.fs
(:require
clojure.string
[clojure.java.io :as io]
[taoensso.timbre :as log]))
(defn cwd []
(let [jar-path (->
*ns*
class
.getProtectionDomain
.getCodeSource
.getLocation
.toURI
.getPath)]
(if (clojure.string/includes? jar-path "robinson.jar")
(->
jar-path
io/file
.toPath
.getParent
(str "/"))
"")))
(defn cwd-path [path]
(str (cwd) path))
(defn cwd-file [path]
(io/file (cwd-path path)))
| null | https://raw.githubusercontent.com/kelsey-sorrels/robinson/337fd2646882708331257d1f3db78a3074ccc67a/src/robinson/fs.clj | clojure | (ns robinson.fs
(:require
clojure.string
[clojure.java.io :as io]
[taoensso.timbre :as log]))
(defn cwd []
(let [jar-path (->
*ns*
class
.getProtectionDomain
.getCodeSource
.getLocation
.toURI
.getPath)]
(if (clojure.string/includes? jar-path "robinson.jar")
(->
jar-path
io/file
.toPath
.getParent
(str "/"))
"")))
(defn cwd-path [path]
(str (cwd) path))
(defn cwd-file [path]
(io/file (cwd-path path)))
|
|
3f2fd420b5862d7ec696634bac48af5da77e07758da8c254429533a35ae4afff | qkrgud55/ocamlmulti | path.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : path.ml 12035 2012 - 01 - 18 09:15:27Z frisch $
type t =
Pident of Ident.t
| Pdot of t * string * int
| Papply of t * t
let nopos = -1
let rec same p1 p2 =
match (p1, p2) with
(Pident id1, Pident id2) -> Ident.same id1 id2
| (Pdot(p1, s1, pos1), Pdot(p2, s2, pos2)) -> s1 = s2 && same p1 p2
| (Papply(fun1, arg1), Papply(fun2, arg2)) ->
same fun1 fun2 && same arg1 arg2
| (_, _) -> false
let rec isfree id = function
Pident id' -> Ident.same id id'
| Pdot(p, s, pos) -> isfree id p
| Papply(p1, p2) -> isfree id p1 || isfree id p2
let rec binding_time = function
Pident id -> Ident.binding_time id
| Pdot(p, s, pos) -> binding_time p
| Papply(p1, p2) -> max (binding_time p1) (binding_time p2)
let kfalse x = false
let rec name ?(paren=kfalse) = function
Pident id -> Ident.name id
| Pdot(p, s, pos) ->
name ~paren p ^ if paren s then ".( " ^ s ^ " )" else "." ^ s
| Papply(p1, p2) -> name ~paren p1 ^ "(" ^ name ~paren p2 ^ ")"
let rec head = function
Pident id -> id
| Pdot(p, s, pos) -> head p
| Papply(p1, p2) -> assert false
let rec last = function
| Pident id -> Ident.name id
| Pdot(_, s, _) -> s
| Papply(_, p) -> last p
| null | https://raw.githubusercontent.com/qkrgud55/ocamlmulti/74fe84df0ce7be5ee03fb4ac0520fb3e9f4b6d1f/typing/path.ml | ocaml | *********************************************************************
OCaml
********************************************************************* | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : path.ml 12035 2012 - 01 - 18 09:15:27Z frisch $
type t =
Pident of Ident.t
| Pdot of t * string * int
| Papply of t * t
let nopos = -1
let rec same p1 p2 =
match (p1, p2) with
(Pident id1, Pident id2) -> Ident.same id1 id2
| (Pdot(p1, s1, pos1), Pdot(p2, s2, pos2)) -> s1 = s2 && same p1 p2
| (Papply(fun1, arg1), Papply(fun2, arg2)) ->
same fun1 fun2 && same arg1 arg2
| (_, _) -> false
let rec isfree id = function
Pident id' -> Ident.same id id'
| Pdot(p, s, pos) -> isfree id p
| Papply(p1, p2) -> isfree id p1 || isfree id p2
let rec binding_time = function
Pident id -> Ident.binding_time id
| Pdot(p, s, pos) -> binding_time p
| Papply(p1, p2) -> max (binding_time p1) (binding_time p2)
let kfalse x = false
let rec name ?(paren=kfalse) = function
Pident id -> Ident.name id
| Pdot(p, s, pos) ->
name ~paren p ^ if paren s then ".( " ^ s ^ " )" else "." ^ s
| Papply(p1, p2) -> name ~paren p1 ^ "(" ^ name ~paren p2 ^ ")"
let rec head = function
Pident id -> id
| Pdot(p, s, pos) -> head p
| Papply(p1, p2) -> assert false
let rec last = function
| Pident id -> Ident.name id
| Pdot(_, s, _) -> s
| Papply(_, p) -> last p
|
4ac1d00bf2b146ed85485ef54f9ea756c92489e9118ae1674f35f73685f3ed83 | goblint/analyzer | floatDomain.mli | (** Abstract Domains for floats. These are domains that support the C
* operations on double/float values. *)
open GoblintCil
exception ArithmeticOnFloatBot of string
module type FloatArith = sig
type t
val neg : t -> t
* Negating a float value : [ -x ]
val add : t -> t -> t
(** Addition: [x + y] *)
val sub : t -> t -> t
(** Subtraction: [x - y] *)
val mul : t -> t -> t
(** Multiplication: [x * y] *)
val div : t -> t -> t
(** Division: [x / y] *)
val fmax : t -> t -> t
(** Maximum *)
val fmin : t -> t -> t
(** Minimum *)
(** {unary functions} *)
val ceil: t -> t
(* ceil(x) *)
val floor: t -> t
(* floor(x) *)
val fabs : t -> t
(** fabs(x) *)
val acos : t -> t
(** acos(x) *)
val asin : t -> t
(** asin(x) *)
val atan : t -> t
(** atan(x) *)
val cos : t -> t
* )
val sin : t -> t
* )
val tan : t -> t
(** tan(x) *)
(** {b Comparison operators} *)
val lt : t -> t -> IntDomain.IntDomTuple.t
(** Less than: [x < y] *)
val gt : t -> t -> IntDomain.IntDomTuple.t
(** Greater than: [x > y] *)
val le : t -> t -> IntDomain.IntDomTuple.t
(** Less than or equal: [x <= y] *)
val ge : t -> t -> IntDomain.IntDomTuple.t
(** Greater than or equal: [x >= y] *)
val eq : t -> t -> IntDomain.IntDomTuple.t
(** Equal to: [x == y] *)
val ne : t -> t -> IntDomain.IntDomTuple.t
(** Not equal to: [x != y] *)
val unordered: t -> t -> IntDomain.IntDomTuple.t
(** Unordered *)
(** {unary functions returning int} *)
val isfinite : t -> IntDomain.IntDomTuple.t
(** __builtin_isfinite(x) *)
val isinf : t -> IntDomain.IntDomTuple.t
(** __builtin_isinf(x) *)
val isnan : t -> IntDomain.IntDomTuple.t
(** __builtin_isnan(x) *)
val isnormal : t -> IntDomain.IntDomTuple.t
(** __builtin_isnormal(x) *)
val signbit : t -> IntDomain.IntDomTuple.t
(** __builtin_signbit(x) *)
end
module type FloatDomainBase = sig
include Lattice.S
include FloatArith with type t := t
val to_int : Cil.ikind -> t -> IntDomain.IntDomTuple.t
val nan: unit -> t
val of_const : float -> t
val of_interval : float * float -> t
val of_string : string -> t
val of_int: IntDomain.IntDomTuple.t -> t
val ending : float -> t
val starting : float -> t
val ending_before : float -> t
val starting_after : float -> t
val minimal: t -> float option
val maximal: t -> float option
val is_exact : t -> bool
end
(* Only exposed for testing *)
module F64Interval : FloatDomainBase
module F32Interval : FloatDomainBase
module type FloatDomain = sig
include Lattice.S
include FloatArith with type t := t
val to_int : Cil.ikind -> t -> IntDomain.IntDomTuple.t
val cast_to : Cil.fkind -> t -> t
val of_const : Cil.fkind -> float -> t
val of_interval : Cil.fkind -> float*float -> t
val of_string : Cil.fkind -> string -> t
val of_int: Cil.fkind -> IntDomain.IntDomTuple.t -> t
val top_of: Cil.fkind -> t
val bot_of: Cil.fkind -> t
val nan_of: Cil.fkind -> t
val inf_of: Cil.fkind -> t
val minus_inf_of: Cil.fkind -> t
val ending : Cil.fkind -> float -> t
val starting : Cil.fkind -> float -> t
val ending_before : Cil.fkind -> float -> t
val starting_after : Cil.fkind -> float -> t
val minimal: t -> float option
val maximal: t -> float option
val is_exact : t -> bool
val get_fkind : t -> Cil.fkind
val invariant: Cil.exp -> t -> Invariant.t
end
module FloatDomTupleImpl : FloatDomain
| null | https://raw.githubusercontent.com/goblint/analyzer/2587de294aeda1b15fdb78f9c03cf4627ec3ba3f/src/cdomains/floatDomain.mli | ocaml | * Abstract Domains for floats. These are domains that support the C
* operations on double/float values.
* Addition: [x + y]
* Subtraction: [x - y]
* Multiplication: [x * y]
* Division: [x / y]
* Maximum
* Minimum
* {unary functions}
ceil(x)
floor(x)
* fabs(x)
* acos(x)
* asin(x)
* atan(x)
* tan(x)
* {b Comparison operators}
* Less than: [x < y]
* Greater than: [x > y]
* Less than or equal: [x <= y]
* Greater than or equal: [x >= y]
* Equal to: [x == y]
* Not equal to: [x != y]
* Unordered
* {unary functions returning int}
* __builtin_isfinite(x)
* __builtin_isinf(x)
* __builtin_isnan(x)
* __builtin_isnormal(x)
* __builtin_signbit(x)
Only exposed for testing | open GoblintCil
exception ArithmeticOnFloatBot of string
module type FloatArith = sig
type t
val neg : t -> t
* Negating a float value : [ -x ]
val add : t -> t -> t
val sub : t -> t -> t
val mul : t -> t -> t
val div : t -> t -> t
val fmax : t -> t -> t
val fmin : t -> t -> t
val ceil: t -> t
val floor: t -> t
val fabs : t -> t
val acos : t -> t
val asin : t -> t
val atan : t -> t
val cos : t -> t
* )
val sin : t -> t
* )
val tan : t -> t
val lt : t -> t -> IntDomain.IntDomTuple.t
val gt : t -> t -> IntDomain.IntDomTuple.t
val le : t -> t -> IntDomain.IntDomTuple.t
val ge : t -> t -> IntDomain.IntDomTuple.t
val eq : t -> t -> IntDomain.IntDomTuple.t
val ne : t -> t -> IntDomain.IntDomTuple.t
val unordered: t -> t -> IntDomain.IntDomTuple.t
val isfinite : t -> IntDomain.IntDomTuple.t
val isinf : t -> IntDomain.IntDomTuple.t
val isnan : t -> IntDomain.IntDomTuple.t
val isnormal : t -> IntDomain.IntDomTuple.t
val signbit : t -> IntDomain.IntDomTuple.t
end
module type FloatDomainBase = sig
include Lattice.S
include FloatArith with type t := t
val to_int : Cil.ikind -> t -> IntDomain.IntDomTuple.t
val nan: unit -> t
val of_const : float -> t
val of_interval : float * float -> t
val of_string : string -> t
val of_int: IntDomain.IntDomTuple.t -> t
val ending : float -> t
val starting : float -> t
val ending_before : float -> t
val starting_after : float -> t
val minimal: t -> float option
val maximal: t -> float option
val is_exact : t -> bool
end
module F64Interval : FloatDomainBase
module F32Interval : FloatDomainBase
module type FloatDomain = sig
include Lattice.S
include FloatArith with type t := t
val to_int : Cil.ikind -> t -> IntDomain.IntDomTuple.t
val cast_to : Cil.fkind -> t -> t
val of_const : Cil.fkind -> float -> t
val of_interval : Cil.fkind -> float*float -> t
val of_string : Cil.fkind -> string -> t
val of_int: Cil.fkind -> IntDomain.IntDomTuple.t -> t
val top_of: Cil.fkind -> t
val bot_of: Cil.fkind -> t
val nan_of: Cil.fkind -> t
val inf_of: Cil.fkind -> t
val minus_inf_of: Cil.fkind -> t
val ending : Cil.fkind -> float -> t
val starting : Cil.fkind -> float -> t
val ending_before : Cil.fkind -> float -> t
val starting_after : Cil.fkind -> float -> t
val minimal: t -> float option
val maximal: t -> float option
val is_exact : t -> bool
val get_fkind : t -> Cil.fkind
val invariant: Cil.exp -> t -> Invariant.t
end
module FloatDomTupleImpl : FloatDomain
|
24a7fd3941351223a6380e7641d288dbed465e9df890e6198c03682e275adedf | vseloved/cl-nlp | en.lisp | ( c ) 2019 Vsevolod Dyomkin
(in-package #:nlp.core)
(named-readtables:in-readtable rutilsx-readtable)
(def-lang-profile :en
:word-tags (dict-from-file (lang-file :en "word-tags.txt")
:test 'eql :key-transform 'tag:export-tag)
:dep-tags (dict-from-file (lang-file :en "dep-tags.txt")
:test 'eql :key-transform 'tag:export-tag)
:phrase-tags (dict-from-file (lang-file :en "phrase-tags.txt")
:test 'eql :key-transform 'tag:export-tag)
:word-tokenizer (make 'regex-word-tokenizer
:regex (regex-from-file
(lang-file :en "word-tok-rules.txt")))
:sent-splitter (make 'punct-sent-tokenizer
:abbrevs-with-dot (list-from-file
(lang-file :en "abbrevs-with-dot.txt")))
:dict-lemmatizer (nlex:load-mem-dict (lang-file :en "wikt-dict.txt"))
:stopwords (dict-from-file (lang-file :en "stopwords.txt")
:test 'equalp :val-transform (constantly t)))
| null | https://raw.githubusercontent.com/vseloved/cl-nlp/f180b6c3c0b9a3614ae43f53a11bc500767307d0/langs/en/en.lisp | lisp | ( c ) 2019 Vsevolod Dyomkin
(in-package #:nlp.core)
(named-readtables:in-readtable rutilsx-readtable)
(def-lang-profile :en
:word-tags (dict-from-file (lang-file :en "word-tags.txt")
:test 'eql :key-transform 'tag:export-tag)
:dep-tags (dict-from-file (lang-file :en "dep-tags.txt")
:test 'eql :key-transform 'tag:export-tag)
:phrase-tags (dict-from-file (lang-file :en "phrase-tags.txt")
:test 'eql :key-transform 'tag:export-tag)
:word-tokenizer (make 'regex-word-tokenizer
:regex (regex-from-file
(lang-file :en "word-tok-rules.txt")))
:sent-splitter (make 'punct-sent-tokenizer
:abbrevs-with-dot (list-from-file
(lang-file :en "abbrevs-with-dot.txt")))
:dict-lemmatizer (nlex:load-mem-dict (lang-file :en "wikt-dict.txt"))
:stopwords (dict-from-file (lang-file :en "stopwords.txt")
:test 'equalp :val-transform (constantly t)))
|
|
8a512be1945beb91f984cf7a4705b8d065893ab0df580c98419c89b492abadd7 | richhickey/clojure-contrib | test_with_ns.clj | (ns clojure.contrib.test-with-ns
(:use clojure.test
clojure.contrib.with-ns))
(deftest test-namespace-gets-removed
(let [all-ns-names (fn [] (map #(.name %) (all-ns)))]
(testing "unexceptional return"
(let [ns-name (with-temp-ns (ns-name *ns*))]
(is (not (some #{ns-name} (all-ns-names))))))
(testing "when an exception is thrown"
(let [ns-name-str
(try
(with-temp-ns
(throw (RuntimeException. (str (ns-name *ns*)))))
(catch clojure.lang.Compiler$CompilerException e
(-> e .getCause .getMessage)))]
(is (re-find #"^sym.*$" ns-name-str))
(is (not (some #{(symbol ns-name-str)} (all-ns-names))))))))
| null | https://raw.githubusercontent.com/richhickey/clojure-contrib/40b960bba41ba02811ef0e2c632d721eb199649f/src/test/clojure/clojure/contrib/test_with_ns.clj | clojure | (ns clojure.contrib.test-with-ns
(:use clojure.test
clojure.contrib.with-ns))
(deftest test-namespace-gets-removed
(let [all-ns-names (fn [] (map #(.name %) (all-ns)))]
(testing "unexceptional return"
(let [ns-name (with-temp-ns (ns-name *ns*))]
(is (not (some #{ns-name} (all-ns-names))))))
(testing "when an exception is thrown"
(let [ns-name-str
(try
(with-temp-ns
(throw (RuntimeException. (str (ns-name *ns*)))))
(catch clojure.lang.Compiler$CompilerException e
(-> e .getCause .getMessage)))]
(is (re-find #"^sym.*$" ns-name-str))
(is (not (some #{(symbol ns-name-str)} (all-ns-names))))))))
|
|
ba1c233c0c6b56a6a13541bace61ef917baac6332f792a1f73fa373c8eea55e5 | wlitwin/graphv | createFlags.mli | include Flags.S
val antialias : t
val stencil_strokes : t
val debug : t
val tesselate_afd : t
| null | https://raw.githubusercontent.com/wlitwin/graphv/d0a09575c5ff5ee3727c222dd6130d22e4cf62d9/webgl1/core/createFlags.mli | ocaml | include Flags.S
val antialias : t
val stencil_strokes : t
val debug : t
val tesselate_afd : t
|
|
bb444498b517671c7ff7c8e48cfee1ffbb515efdef693117aedf6ad8bc6965c7 | geremih/xcljb | xproto_internal.clj | This file is automatically generated . DO NOT MODIFY .
(clojure.core/ns
xcljb.gen.xproto-internal
(:require [xcljb common gen-common] [xcljb.gen xproto-types]))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 3]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetWindowAttributesReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 14]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetGeometryReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 15]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryTreeReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 16]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/InternAtomReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 17]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetAtomNameReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 20]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetPropertyReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 21]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ListPropertiesReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 23]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetSelectionOwnerReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 26]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GrabPointerReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 31]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GrabKeyboardReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 38]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryPointerReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 39]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetMotionEventsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 40]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/TranslateCoordinatesReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 43]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetInputFocusReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 44]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryKeymapReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 47]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryFontReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 48]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryTextExtentsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 49]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ListFontsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 50]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ListFontsWithInfoReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 52]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetFontPathReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 73]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetImageReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 83]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ListInstalledColormapsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 84]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AllocColorReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 85]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AllocNamedColorReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 86]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AllocColorCellsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 87]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AllocColorPlanesReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 91]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryColorsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 92]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/LookupColorReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 97]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryBestSizeReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 98]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryExtensionReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 99]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ListExtensionsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 101]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetKeyboardMappingReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 103]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetKeyboardControlReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 106]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetPointerControlReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 108]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetScreenSaverReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 110]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ListHostsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 116]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/SetPointerMappingReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 117]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetPointerMappingReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 118]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/SetModifierMappingReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 119]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetModifierMappingReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 2]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/KeyPressEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 3]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/KeyReleaseEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 4]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ButtonPressEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 5]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ButtonReleaseEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 6]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/MotionNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 7]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/EnterNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 8]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/LeaveNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 9]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/FocusInEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 10]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/FocusOutEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 11]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/KeymapNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 12]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ExposeEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 13]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GraphicsExposureEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 14]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/NoExposureEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 15]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/VisibilityNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 16]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/CreateNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 17]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/DestroyNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 18]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/UnmapNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 19]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/MapNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 20]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/MapRequestEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 21]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ReparentNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 22]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ConfigureNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 23]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ConfigureRequestEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 24]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GravityNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 25]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ResizeRequestEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 26]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/CirculateNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 27]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/CirculateRequestEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 28]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/PropertyNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 29]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/SelectionClearEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 30]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/SelectionRequestEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 31]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/SelectionNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 32]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ColormapNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 34]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/MappingNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 1]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/RequestError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 2]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ValueError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 3]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/WindowError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 4]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/PixmapError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 5]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AtomError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 6]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/CursorError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 7]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/FontError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 8]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/MatchError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 9]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/DrawableError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 10]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AccessError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 11]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AllocError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 12]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ColormapError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 13]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GContextError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 14]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/IDChoiceError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 15]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/NameError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 16]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/LengthError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 17]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ImplementationError
error-buf
nil))
;;; Manually written.
(clojure.core/defmethod
xcljb.common/read-event
[nil 33]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ClientMessageEvent
event-buf
nil))
| null | https://raw.githubusercontent.com/geremih/xcljb/59e9ff795bf00595a3d46231a7bb4ec976852396/src/xcljb/gen/xproto_internal.clj | clojure | Manually written. | This file is automatically generated . DO NOT MODIFY .
(clojure.core/ns
xcljb.gen.xproto-internal
(:require [xcljb common gen-common] [xcljb.gen xproto-types]))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 3]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetWindowAttributesReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 14]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetGeometryReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 15]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryTreeReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 16]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/InternAtomReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 17]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetAtomNameReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 20]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetPropertyReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 21]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ListPropertiesReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 23]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetSelectionOwnerReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 26]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GrabPointerReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 31]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GrabKeyboardReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 38]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryPointerReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 39]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetMotionEventsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 40]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/TranslateCoordinatesReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 43]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetInputFocusReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 44]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryKeymapReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 47]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryFontReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 48]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryTextExtentsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 49]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ListFontsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 50]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ListFontsWithInfoReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 52]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetFontPathReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 73]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetImageReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 83]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ListInstalledColormapsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 84]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AllocColorReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 85]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AllocNamedColorReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 86]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AllocColorCellsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 87]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AllocColorPlanesReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 91]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryColorsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 92]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/LookupColorReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 97]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryBestSizeReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 98]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/QueryExtensionReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 99]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ListExtensionsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 101]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetKeyboardMappingReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 103]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetKeyboardControlReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 106]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetPointerControlReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 108]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetScreenSaverReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 110]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ListHostsReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 116]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/SetPointerMappingReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 117]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetPointerMappingReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 118]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/SetModifierMappingReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-reply
[nil 119]
[_ _ reply-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GetModifierMappingReply
reply-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 2]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/KeyPressEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 3]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/KeyReleaseEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 4]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ButtonPressEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 5]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ButtonReleaseEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 6]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/MotionNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 7]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/EnterNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 8]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/LeaveNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 9]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/FocusInEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 10]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/FocusOutEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 11]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/KeymapNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 12]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ExposeEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 13]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GraphicsExposureEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 14]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/NoExposureEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 15]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/VisibilityNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 16]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/CreateNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 17]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/DestroyNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 18]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/UnmapNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 19]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/MapNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 20]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/MapRequestEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 21]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ReparentNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 22]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ConfigureNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 23]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ConfigureRequestEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 24]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GravityNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 25]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ResizeRequestEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 26]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/CirculateNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 27]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/CirculateRequestEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 28]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/PropertyNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 29]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/SelectionClearEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 30]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/SelectionRequestEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 31]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/SelectionNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 32]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ColormapNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 34]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/MappingNotifyEvent
event-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 1]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/RequestError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 2]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ValueError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 3]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/WindowError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 4]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/PixmapError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 5]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AtomError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 6]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/CursorError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 7]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/FontError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 8]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/MatchError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 9]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/DrawableError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 10]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AccessError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 11]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/AllocError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 12]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ColormapError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 13]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/GContextError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 14]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/IDChoiceError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 15]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/NameError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 16]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/LengthError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-error
[nil 17]
[_ _ error-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ImplementationError
error-buf
nil))
(clojure.core/defmethod
xcljb.common/read-event
[nil 33]
[_ _ event-buf]
(xcljb.gen-common/deserialize
xcljb.gen.xproto-types/ClientMessageEvent
event-buf
nil))
|
c8e2566375b3454e39fc01b2122b3f94fcc3e06eee4fe9a05be23728fe09d1df | wdebeaum/step | urge.lisp | ;;;;
;;;; W::urge
;;;;
(define-words :pos W::v :TEMPL AGENT-FORMAL-XP-TEMPL
:words (
(W::urge
(SENSES
((LF-PARENT ONT::suggest)
(example "Abrams urged Browne to hire Chiang")
(meta-data :origin csli-ts :entry-date 20070313 :change-date nil :comments nil :wn nil)
(SEM (F::Aspect F::unbounded) (F::Time-span F::extended))
(TEMPL AGENT-AGENT1-FORMAL-OBJCONTROL-TEMPL)
)
((LF-PARENT ONT::suggest)
(example "Abrams urged Browne")
(meta-data :origin csli-ts :entry-date 20070313 :change-date nil :comments nil :wn nil)
(SEM (F::Aspect F::unbounded) (F::Time-span F::extended))
(TEMPL AGENT-AGENT1-NP-TEMPL)
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/urge.lisp | lisp |
W::urge
|
(define-words :pos W::v :TEMPL AGENT-FORMAL-XP-TEMPL
:words (
(W::urge
(SENSES
((LF-PARENT ONT::suggest)
(example "Abrams urged Browne to hire Chiang")
(meta-data :origin csli-ts :entry-date 20070313 :change-date nil :comments nil :wn nil)
(SEM (F::Aspect F::unbounded) (F::Time-span F::extended))
(TEMPL AGENT-AGENT1-FORMAL-OBJCONTROL-TEMPL)
)
((LF-PARENT ONT::suggest)
(example "Abrams urged Browne")
(meta-data :origin csli-ts :entry-date 20070313 :change-date nil :comments nil :wn nil)
(SEM (F::Aspect F::unbounded) (F::Time-span F::extended))
(TEMPL AGENT-AGENT1-NP-TEMPL)
)
)
)
))
|
51d453d82fc86541da1451e505ef4b7461dfcb659f749866e1dd99e1a02adbd7 | input-output-hk/cardano-ledger | Deleg.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE NamedFieldPuns #
# LANGUAGE PatternSynonyms #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeSynonymInstances #-}
module Test.Cardano.Ledger.Shelley.Rules.Deleg (
tests,
)
where
import Cardano.Ledger.Coin
import Cardano.Ledger.Shelley.API (ShelleyDELEG)
import Cardano.Ledger.Shelley.Core
import qualified Cardano.Ledger.Shelley.HardForks as HardForks (allowMIRTransfer)
import Cardano.Ledger.Shelley.LedgerState (
DState (..),
InstantaneousRewards (..),
delegations,
rewards,
)
import Cardano.Ledger.Shelley.Rules (DelegEnv (..))
import Cardano.Ledger.Shelley.TxBody
import qualified Cardano.Ledger.UMapCompact as UM
import Control.SetAlgebra (eval, rng, (∈))
import Control.State.Transition.Trace (
SourceSignalTarget (..),
sourceSignalTargets,
)
import qualified Control.State.Transition.Trace.Generator.QuickCheck as QC
import Data.Foldable (fold)
import Data.List (foldl')
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Lens.Micro.Extras (view)
import Test.Cardano.Ledger.Shelley.Generator.Constants (defaultConstants)
import Test.Cardano.Ledger.Shelley.Generator.Core (GenEnv)
import Test.Cardano.Ledger.Shelley.Generator.EraGen (EraGen (..))
import Test.Cardano.Ledger.Shelley.Generator.ShelleyEraGen ()
import Test.Cardano.Ledger.Shelley.Rules.Chain (CHAIN)
import Test.QuickCheck (Property, conjoin, counterexample)
import Test.Cardano.Ledger.Shelley.Rules.TestChain (
delegTraceFromBlock,
forAllChainTrace,
traceLen,
)
import Test.Cardano.Ledger.Shelley.Utils (
ChainProperty,
)
import Test.QuickCheck (
Testable (..),
)
import Test.Tasty (TestTree)
import Test.Tasty.QuickCheck (testProperty)
-- | Various properties of the POOL STS Rule, tested on longer traces
-- (double the default length)
tests ::
forall era.
( EraGen era
, EraGovernance era
, QC.HasTrace (CHAIN era) (GenEnv era)
, ChainProperty era
, ProtVerAtMost era 8
) =>
TestTree
tests =
testProperty "properties of the DELEG STS" $
forAllChainTrace @era traceLen defaultConstants $ \tr -> do
conjoin $
map chainProp (sourceSignalTargets tr)
where
delegProp :: DelegEnv era -> SourceSignalTarget (ShelleyDELEG era) -> Property
delegProp denv delegSst =
conjoin $
[ keyRegistration delegSst
, keyDeRegistration delegSst
, keyDelegation delegSst
, rewardsSumInvariant delegSst
, checkInstantaneousRewards denv delegSst
]
chainProp :: SourceSignalTarget (CHAIN era) -> Property
chainProp (SourceSignalTarget {source = chainSt, signal = block}) =
let delegInfo = delegTraceFromBlock chainSt block
delegEnv = fst delegInfo
delegTr = snd delegInfo
delegSsts = sourceSignalTargets delegTr
in conjoin (map (delegProp delegEnv) delegSsts)
-- | Check stake key registration
keyRegistration :: SourceSignalTarget (ShelleyDELEG era) -> Property
keyRegistration
SourceSignalTarget
{ signal = (DCertDeleg (RegKey hk))
, target = targetSt
} =
conjoin
[ counterexample
"a newly registered key should have a reward account"
((UM.member hk (rewards targetSt)) :: Bool)
, counterexample
"a newly registered key should have a reward account with 0 balance"
((UM.rdReward <$> UM.lookup hk (rewards targetSt)) == Just mempty)
]
keyRegistration _ = property ()
-- | Check stake key de-registration
keyDeRegistration :: SourceSignalTarget (ShelleyDELEG era) -> Property
keyDeRegistration
SourceSignalTarget
{ signal = (DCertDeleg (DeRegKey hk))
, target = targetSt
} =
conjoin
[ counterexample
"a deregistered stake key should no longer be in the rewards mapping"
((UM.notMember hk (rewards targetSt)) :: Bool)
, counterexample
"a deregistered stake key should no longer be in the delegations mapping"
((UM.notMember hk (delegations targetSt)) :: Bool)
]
keyDeRegistration _ = property ()
-- | Check stake key delegation
keyDelegation :: SourceSignalTarget (ShelleyDELEG era) -> Property
keyDelegation
SourceSignalTarget
{ signal = (DCertDeleg (Delegate (Delegation from to)))
, target = targetSt
} =
let fromImage = eval (rng (Set.singleton from `UM.domRestrictedView` delegations targetSt))
in conjoin
[ counterexample
"a delegated key should have a reward account"
((UM.member from (rewards targetSt)) :: Bool)
, counterexample
"a registered stake credential should be delegated"
((eval (to ∈ fromImage)) :: Bool)
, counterexample
"a registered stake credential should be uniquely delegated"
(Set.size fromImage == 1)
]
keyDelegation _ = property ()
-- | Check that the sum of rewards does not change and that each element
that is either removed or added has a zero balance .
rewardsSumInvariant :: SourceSignalTarget (ShelleyDELEG era) -> Property
rewardsSumInvariant
SourceSignalTarget {source, target} =
let sourceRewards = UM.compactRewView (dsUnified source)
targetRewards = UM.compactRewView (dsUnified target)
rewardsSum = foldl' (<>) mempty
in conjoin
[ counterexample
"sum of rewards should not change"
(rewardsSum sourceRewards == rewardsSum targetRewards)
, counterexample
"dropped elements have a zero reward balance"
(null (Map.filter (/= UM.CompactCoin 0) $ sourceRewards `Map.difference` targetRewards))
, counterexample
"added elements have a zero reward balance"
(null (Map.filter (/= UM.CompactCoin 0) $ targetRewards `Map.difference` sourceRewards))
]
checkInstantaneousRewards ::
EraPParams era =>
DelegEnv era ->
SourceSignalTarget (ShelleyDELEG era) ->
Property
checkInstantaneousRewards
denv
SourceSignalTarget {source, signal, target} =
case signal of
DCertMir (MIRCert ReservesMIR (StakeAddressesMIR irwd)) ->
conjoin
[ counterexample
"a ReservesMIR certificate should add all entries to the `irwd` mapping"
(Map.keysSet irwd `Set.isSubsetOf` Map.keysSet (iRReserves $ dsIRewards target))
, counterexample
"a ReservesMIR certificate should add the total value to the `irwd` map, overwriting any existing entries"
( if (HardForks.allowMIRTransfer . view ppProtocolVersionL . ppDE $ denv)
In the era , repeated fields are added
( (fold $ iRReserves $ dsIRewards source)
`addDeltaCoin` (fold irwd)
== (fold $ (iRReserves $ dsIRewards target))
)
Prior to the era , repeated fields overridden
( (fold $ (iRReserves $ dsIRewards source) Map.\\ irwd)
`addDeltaCoin` (fold irwd)
== (fold $ (iRReserves $ dsIRewards target))
)
)
]
DCertMir (MIRCert TreasuryMIR (StakeAddressesMIR irwd)) ->
conjoin
[ counterexample
"a TreasuryMIR certificate should add all entries to the `irwd` mapping"
(Map.keysSet irwd `Set.isSubsetOf` Map.keysSet (iRTreasury $ dsIRewards target))
, counterexample
"a TreasuryMIR certificate should add* the total value to the `irwd` map"
( if HardForks.allowMIRTransfer . view ppProtocolVersionL . ppDE $ denv
In the era , repeated fields are added
( (fold $ iRTreasury $ dsIRewards source)
`addDeltaCoin` (fold irwd)
== (fold $ (iRTreasury $ dsIRewards target))
)
Prior to the era , repeated fields overridden
( (fold $ (iRTreasury $ dsIRewards source) Map.\\ irwd)
`addDeltaCoin` (fold irwd)
== (fold $ (iRTreasury $ dsIRewards target))
)
)
]
_ -> property ()
| null | https://raw.githubusercontent.com/input-output-hk/cardano-ledger/1e2ff13f02a989241f637fd9413f1852675b74f0/eras/shelley/test-suite/src/Test/Cardano/Ledger/Shelley/Rules/Deleg.hs | haskell | # LANGUAGE TypeSynonymInstances #
| Various properties of the POOL STS Rule, tested on longer traces
(double the default length)
| Check stake key registration
| Check stake key de-registration
| Check stake key delegation
| Check that the sum of rewards does not change and that each element | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE NamedFieldPuns #
# LANGUAGE PatternSynonyms #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Test.Cardano.Ledger.Shelley.Rules.Deleg (
tests,
)
where
import Cardano.Ledger.Coin
import Cardano.Ledger.Shelley.API (ShelleyDELEG)
import Cardano.Ledger.Shelley.Core
import qualified Cardano.Ledger.Shelley.HardForks as HardForks (allowMIRTransfer)
import Cardano.Ledger.Shelley.LedgerState (
DState (..),
InstantaneousRewards (..),
delegations,
rewards,
)
import Cardano.Ledger.Shelley.Rules (DelegEnv (..))
import Cardano.Ledger.Shelley.TxBody
import qualified Cardano.Ledger.UMapCompact as UM
import Control.SetAlgebra (eval, rng, (∈))
import Control.State.Transition.Trace (
SourceSignalTarget (..),
sourceSignalTargets,
)
import qualified Control.State.Transition.Trace.Generator.QuickCheck as QC
import Data.Foldable (fold)
import Data.List (foldl')
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Lens.Micro.Extras (view)
import Test.Cardano.Ledger.Shelley.Generator.Constants (defaultConstants)
import Test.Cardano.Ledger.Shelley.Generator.Core (GenEnv)
import Test.Cardano.Ledger.Shelley.Generator.EraGen (EraGen (..))
import Test.Cardano.Ledger.Shelley.Generator.ShelleyEraGen ()
import Test.Cardano.Ledger.Shelley.Rules.Chain (CHAIN)
import Test.QuickCheck (Property, conjoin, counterexample)
import Test.Cardano.Ledger.Shelley.Rules.TestChain (
delegTraceFromBlock,
forAllChainTrace,
traceLen,
)
import Test.Cardano.Ledger.Shelley.Utils (
ChainProperty,
)
import Test.QuickCheck (
Testable (..),
)
import Test.Tasty (TestTree)
import Test.Tasty.QuickCheck (testProperty)
tests ::
forall era.
( EraGen era
, EraGovernance era
, QC.HasTrace (CHAIN era) (GenEnv era)
, ChainProperty era
, ProtVerAtMost era 8
) =>
TestTree
tests =
testProperty "properties of the DELEG STS" $
forAllChainTrace @era traceLen defaultConstants $ \tr -> do
conjoin $
map chainProp (sourceSignalTargets tr)
where
delegProp :: DelegEnv era -> SourceSignalTarget (ShelleyDELEG era) -> Property
delegProp denv delegSst =
conjoin $
[ keyRegistration delegSst
, keyDeRegistration delegSst
, keyDelegation delegSst
, rewardsSumInvariant delegSst
, checkInstantaneousRewards denv delegSst
]
chainProp :: SourceSignalTarget (CHAIN era) -> Property
chainProp (SourceSignalTarget {source = chainSt, signal = block}) =
let delegInfo = delegTraceFromBlock chainSt block
delegEnv = fst delegInfo
delegTr = snd delegInfo
delegSsts = sourceSignalTargets delegTr
in conjoin (map (delegProp delegEnv) delegSsts)
keyRegistration :: SourceSignalTarget (ShelleyDELEG era) -> Property
keyRegistration
SourceSignalTarget
{ signal = (DCertDeleg (RegKey hk))
, target = targetSt
} =
conjoin
[ counterexample
"a newly registered key should have a reward account"
((UM.member hk (rewards targetSt)) :: Bool)
, counterexample
"a newly registered key should have a reward account with 0 balance"
((UM.rdReward <$> UM.lookup hk (rewards targetSt)) == Just mempty)
]
keyRegistration _ = property ()
keyDeRegistration :: SourceSignalTarget (ShelleyDELEG era) -> Property
keyDeRegistration
SourceSignalTarget
{ signal = (DCertDeleg (DeRegKey hk))
, target = targetSt
} =
conjoin
[ counterexample
"a deregistered stake key should no longer be in the rewards mapping"
((UM.notMember hk (rewards targetSt)) :: Bool)
, counterexample
"a deregistered stake key should no longer be in the delegations mapping"
((UM.notMember hk (delegations targetSt)) :: Bool)
]
keyDeRegistration _ = property ()
keyDelegation :: SourceSignalTarget (ShelleyDELEG era) -> Property
keyDelegation
SourceSignalTarget
{ signal = (DCertDeleg (Delegate (Delegation from to)))
, target = targetSt
} =
let fromImage = eval (rng (Set.singleton from `UM.domRestrictedView` delegations targetSt))
in conjoin
[ counterexample
"a delegated key should have a reward account"
((UM.member from (rewards targetSt)) :: Bool)
, counterexample
"a registered stake credential should be delegated"
((eval (to ∈ fromImage)) :: Bool)
, counterexample
"a registered stake credential should be uniquely delegated"
(Set.size fromImage == 1)
]
keyDelegation _ = property ()
that is either removed or added has a zero balance .
rewardsSumInvariant :: SourceSignalTarget (ShelleyDELEG era) -> Property
rewardsSumInvariant
SourceSignalTarget {source, target} =
let sourceRewards = UM.compactRewView (dsUnified source)
targetRewards = UM.compactRewView (dsUnified target)
rewardsSum = foldl' (<>) mempty
in conjoin
[ counterexample
"sum of rewards should not change"
(rewardsSum sourceRewards == rewardsSum targetRewards)
, counterexample
"dropped elements have a zero reward balance"
(null (Map.filter (/= UM.CompactCoin 0) $ sourceRewards `Map.difference` targetRewards))
, counterexample
"added elements have a zero reward balance"
(null (Map.filter (/= UM.CompactCoin 0) $ targetRewards `Map.difference` sourceRewards))
]
checkInstantaneousRewards ::
EraPParams era =>
DelegEnv era ->
SourceSignalTarget (ShelleyDELEG era) ->
Property
checkInstantaneousRewards
denv
SourceSignalTarget {source, signal, target} =
case signal of
DCertMir (MIRCert ReservesMIR (StakeAddressesMIR irwd)) ->
conjoin
[ counterexample
"a ReservesMIR certificate should add all entries to the `irwd` mapping"
(Map.keysSet irwd `Set.isSubsetOf` Map.keysSet (iRReserves $ dsIRewards target))
, counterexample
"a ReservesMIR certificate should add the total value to the `irwd` map, overwriting any existing entries"
( if (HardForks.allowMIRTransfer . view ppProtocolVersionL . ppDE $ denv)
In the era , repeated fields are added
( (fold $ iRReserves $ dsIRewards source)
`addDeltaCoin` (fold irwd)
== (fold $ (iRReserves $ dsIRewards target))
)
Prior to the era , repeated fields overridden
( (fold $ (iRReserves $ dsIRewards source) Map.\\ irwd)
`addDeltaCoin` (fold irwd)
== (fold $ (iRReserves $ dsIRewards target))
)
)
]
DCertMir (MIRCert TreasuryMIR (StakeAddressesMIR irwd)) ->
conjoin
[ counterexample
"a TreasuryMIR certificate should add all entries to the `irwd` mapping"
(Map.keysSet irwd `Set.isSubsetOf` Map.keysSet (iRTreasury $ dsIRewards target))
, counterexample
"a TreasuryMIR certificate should add* the total value to the `irwd` map"
( if HardForks.allowMIRTransfer . view ppProtocolVersionL . ppDE $ denv
In the era , repeated fields are added
( (fold $ iRTreasury $ dsIRewards source)
`addDeltaCoin` (fold irwd)
== (fold $ (iRTreasury $ dsIRewards target))
)
Prior to the era , repeated fields overridden
( (fold $ (iRTreasury $ dsIRewards source) Map.\\ irwd)
`addDeltaCoin` (fold irwd)
== (fold $ (iRTreasury $ dsIRewards target))
)
)
]
_ -> property ()
|
c11483c8624e1c6fb8d89b998f1b36625fc162c4e9f916a42302368b920635fa | robert-strandh/SICL | nunion-defun.lisp | (cl:in-package #:sicl-cons)
;;; We take advantage of the fact that the standard doesn't require
;;; this function to have any side effects.
(defun nunion (list1 list2
&key key (test nil test-given) (test-not nil test-not-given))
(when (and test-given test-not-given)
(error 'both-test-and-test-not-given))
(let ((use-hash (> (* (length list1) (length list2)) 1000)))
(if key
(if test-given
(cond ((or (eq test #'eq) (eq test 'eq))
(if use-hash
(|union key=other test=eq hash| 'nunion list1 list2 key)
(|union key=other test=eq| 'nunion list1 list2 key)))
((or (eq test #'eql) (eq test 'eql))
(if use-hash
(|union key=other test=eql hash| 'nunion list1 list2 key)
(|union key=other test=eql| 'nunion list1 list2 key)))
((or (eq test #'equal) (eq test 'equal))
(if use-hash
(|union key=other test=equal hash| 'nunion list1 list2 key)
(|union key=other test=other| 'nunion list1 list2 key #'equal)))
((or (eq test #'equalp) (eq test 'equalp))
(if use-hash
(|union key=other test=equalp hash| 'nunion list1 list2 key)
(|union key=other test=other| 'nunion list1 list2 key #'equalp)))
(t
(|union key=other test=other| 'nunion list1 list2 key test)))
(if test-not-given
(|union key=other test-not=other| 'nunion list1 list2 key test-not)
(if use-hash
(|union key=other test=eql hash| 'nunion list1 list2 key)
(|union key=other test=eql| 'nunion list1 list2 key))))
(if test-given
(cond ((or (eq test #'eq) (eq test 'eq))
(if use-hash
(|union key=identity test=eq hash| 'nunion list1 list2)
(|union key=identity test=eq| 'nunion list1 list2)))
((or (eq test #'eql) (eq test 'eql))
(if use-hash
(|union key=identity test=eql hash| 'nunion list1 list2)
(|union key=identity test=eql| 'nunion list1 list2)))
((or (eq test #'equal) (eq test 'equal))
(if use-hash
(|union key=identity test=equal hash| 'nunion list1 list2)
(|union key=identity test=other| 'nunion list1 list2 #'equal)))
((or (eq test #'equalp) (eq test 'equalp))
(if use-hash
(|union key=identity test=equalp hash| 'nunion list1 list2)
(|union key=identity test=other| 'nunion list1 list2 #'equalp)))
(t
(|union key=identity test=other| 'nunion list1 list2 test)))
(if test-not-given
(|union key=identity test-not=other| 'nunion list1 list2 test-not)
(if use-hash
(|union key=identity test=eql hash| 'nunion list1 list2)
(|union key=identity test=eql| 'nunion list1 list2)))))))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/32d995c4f8e7d228e9c0cda6f670b2fa53ad0287/Code/Cons/nunion-defun.lisp | lisp | We take advantage of the fact that the standard doesn't require
this function to have any side effects. | (cl:in-package #:sicl-cons)
(defun nunion (list1 list2
&key key (test nil test-given) (test-not nil test-not-given))
(when (and test-given test-not-given)
(error 'both-test-and-test-not-given))
(let ((use-hash (> (* (length list1) (length list2)) 1000)))
(if key
(if test-given
(cond ((or (eq test #'eq) (eq test 'eq))
(if use-hash
(|union key=other test=eq hash| 'nunion list1 list2 key)
(|union key=other test=eq| 'nunion list1 list2 key)))
((or (eq test #'eql) (eq test 'eql))
(if use-hash
(|union key=other test=eql hash| 'nunion list1 list2 key)
(|union key=other test=eql| 'nunion list1 list2 key)))
((or (eq test #'equal) (eq test 'equal))
(if use-hash
(|union key=other test=equal hash| 'nunion list1 list2 key)
(|union key=other test=other| 'nunion list1 list2 key #'equal)))
((or (eq test #'equalp) (eq test 'equalp))
(if use-hash
(|union key=other test=equalp hash| 'nunion list1 list2 key)
(|union key=other test=other| 'nunion list1 list2 key #'equalp)))
(t
(|union key=other test=other| 'nunion list1 list2 key test)))
(if test-not-given
(|union key=other test-not=other| 'nunion list1 list2 key test-not)
(if use-hash
(|union key=other test=eql hash| 'nunion list1 list2 key)
(|union key=other test=eql| 'nunion list1 list2 key))))
(if test-given
(cond ((or (eq test #'eq) (eq test 'eq))
(if use-hash
(|union key=identity test=eq hash| 'nunion list1 list2)
(|union key=identity test=eq| 'nunion list1 list2)))
((or (eq test #'eql) (eq test 'eql))
(if use-hash
(|union key=identity test=eql hash| 'nunion list1 list2)
(|union key=identity test=eql| 'nunion list1 list2)))
((or (eq test #'equal) (eq test 'equal))
(if use-hash
(|union key=identity test=equal hash| 'nunion list1 list2)
(|union key=identity test=other| 'nunion list1 list2 #'equal)))
((or (eq test #'equalp) (eq test 'equalp))
(if use-hash
(|union key=identity test=equalp hash| 'nunion list1 list2)
(|union key=identity test=other| 'nunion list1 list2 #'equalp)))
(t
(|union key=identity test=other| 'nunion list1 list2 test)))
(if test-not-given
(|union key=identity test-not=other| 'nunion list1 list2 test-not)
(if use-hash
(|union key=identity test=eql hash| 'nunion list1 list2)
(|union key=identity test=eql| 'nunion list1 list2)))))))
|
c417728958f1af6be7716761f5e0f012b242c763f77dca726516610998f6a907 | rajasegar/cl-djula-tailwind | tailwind-backgrounds.lisp | (defpackage cl-djula-tailwind.backgrounds
(:use :cl
:cl-djula-tailwind.colors)
(:export :*backgrounds*))
(in-package cl-djula-tailwind.backgrounds)
(defun get-list-key (prefix key)
(ppcre:regex-replace-all "\\\"" (concatenate 'string prefix (write-to-string key)) ""))
(defun get-list-value (prefix key value)
(list (ppcre:regex-replace-all "\\\"" (concatenate 'string "." prefix (write-to-string key)) "") :background-color value))
(defun get-list (prefix key value)
`(,(get-list-key prefix key) . (,(get-list-value prefix key value))))
(defun collect-colors (colors prefix)
(loop for i in colors
collect (get-list prefix (car i) (cdr i))))
(defvar *bg-others* '(("bg-inherit" . ((".bg-inherit" :background-color "inherit")))
("bg-current" . ((".bg-current" :background-color "currentColor")))
("bg-transparent" . ((".bg-transparent" :background-color "transparent")))
("bg-black" . ((".bg-black" :background-color "rgb(0 0 0)")))
("bg-white" . ((".bg-white" :background-color "rgb(255 255 255)")))))
(defvar *bg-color-slate* (collect-colors *slate-colors* "bg-slate-"))
(defvar *bg-color-gray* (collect-colors *gray-colors* "bg-gray-"))
(defvar *bg-color-zinc* (collect-colors *zinc-colors* "bg-zinc-"))
(defvar *bg-color-neutral* (collect-colors *neutral-colors* "bg-neutral-"))
(defvar *bg-color-stone* (collect-colors *stone-colors* "bg-stone-"))
(defvar *bg-color-red* (collect-colors *red-colors* "bg-red-"))
(defvar *bg-color-orange* (collect-colors *orange-colors* "bg-orange-"))
(defvar *bg-color-amber* (collect-colors *amber-colors* "bg-amber-"))
(defvar *bg-color-yellow* (collect-colors *yellow-colors* "bg-yellow-"))
(defvar *bg-color-lime* (collect-colors *lime-colors* "bg-lime-"))
(defvar *bg-color-green* (collect-colors *green-colors* "bg-green-"))
(defvar *bg-color-emerald* (collect-colors *emerald-colors* "bg-emerald-"))
(defvar *bg-color-teal* (collect-colors *teal-colors* "bg-teal-"))
(defvar *bg-color-cyan* (collect-colors *cyan-colors* "bg-cyan-"))
(defvar *bg-color-sky* (collect-colors *sky-colors* "bg-sky-"))
(defvar *bg-color-blue* (collect-colors *blue-colors* "bg-blue-"))
(defvar *bg-color-indigo* (collect-colors *indigo-colors* "bg-indigo-"))
(defvar *bg-color-violet* (collect-colors *violet-colors* "bg-violet-"))
(defvar *bg-color-purple* (collect-colors *purple-colors* "bg-purple-"))
(defvar *bg-color-fuchsia* (collect-colors *fuchsia-colors* "bg-fuchsia-"))
(defvar *bg-color-pink* (collect-colors *pink-colors* "bg-pink-"))
(defvar *bg-color-rose* (collect-colors *rose-colors* "bg-rose-"))
(defvar *background-attachment* '(("bg-fixed" . ((".bg-fixed" :background-attachment "fixed")))
("bg-local" . ((".bg-local" :background-attachment "local")))
("bg-scroll" . ((".bg-scroll" :background-attachment "scroll")))))
(defvar *background-clip* '(("bg-clip-border" . ((".bg-clip-border" :background-clip "border-box")))
("bg-clip-padding" . ((".bg-clip-padding" :background-clip "padding-box")))
("bg-clip-content" . ((".bg-clip-content" :background-clip "content-box")))
("bg-clip-text" . ((".bg-clip-text" :background-clip "text")))))
(defvar *background-origin* '(("bg-origin-border" . ((".bg-origin-border" :background-origin "border-box")))
("bg-origin-padding" . ((".bg-origin-padding" :background-origin "padding-box")))
("bg-origin-content" . ((".bg-origin-content" :background-origin "content-box")))))
(defvar *background-position* '(("bg-bottom" . ((".bg-bottom" :background-position "bottom")))
("bg-center" . ((".bg-center" :background-position "center")))
("bg-left" . ((".bg-left" :background-position "left")))
("bg-left-bottom" . ((".bg-left-bottom" :background-position "left bottom")))
("bg-left-top" . ((".bg-left-top" :background-position "left top")))
("bg-right" . ((".bg-right" :background-position "right")))
("bg-right-bottom" . ((".bg-right-bottom" :background-position "right bottom")))
("bg-right-top" . ((".bg-right-top" :background-position "right top")))
("bg-top" . ((".bg-top" :background-position "top")))))
(defvar *background-repeat* '(("bg-repeat" . ((".bg-repeat" :background-repeat "repeat")))
("bg-no-repeat" . ((".bg-no-repeat" :background-repeat "no-repeat")))
("bg-repeat-x" . ((".bg-repeat-x" :background-repeat "repeat-x")))
("bg-repeat-y" . ((".bg-repeat-y" :background-repeat "repeat-y")))
("bg-repeat-round" . ((".bg-repeat-round" :background-repeat "round")))
("bg-repeat-space" . ((".bg-repeat-space" :background-repeat "space")))))
(defvar *background-size* '(("bg-auto" . ((".bg-auto" :background-size "auto")))
("bg-cover" . ((".bg-cover" :background-size "cover")))
("bg-contain" . ((".bg-contain" :background-size "contain")))))
(defvar *backgrounds* (append
;; background colors
*bg-color-slate*
*bg-color-gray*
*bg-color-zinc*
*bg-color-neutral*
*bg-color-stone*
*bg-color-red*
*bg-color-orange*
*bg-color-amber*
*bg-color-yellow*
*bg-color-lime*
*bg-color-green*
*bg-color-emerald*
*bg-color-teal*
*bg-color-cyan*
*bg-color-sky*
*bg-color-blue*
*bg-color-indigo*
*bg-color-violet*
*bg-color-purple*
*bg-color-fuchsia*
*bg-color-pink*
*bg-color-rose*
*bg-others*
*background-attachment*
*background-clip*
*background-origin*
*background-position*
*background-repeat*
*background-size*
))
| null | https://raw.githubusercontent.com/rajasegar/cl-djula-tailwind/c51fafc76b898525b207eecf061ceacb7bbaf7e9/src/tailwind-backgrounds.lisp | lisp | background colors | (defpackage cl-djula-tailwind.backgrounds
(:use :cl
:cl-djula-tailwind.colors)
(:export :*backgrounds*))
(in-package cl-djula-tailwind.backgrounds)
(defun get-list-key (prefix key)
(ppcre:regex-replace-all "\\\"" (concatenate 'string prefix (write-to-string key)) ""))
(defun get-list-value (prefix key value)
(list (ppcre:regex-replace-all "\\\"" (concatenate 'string "." prefix (write-to-string key)) "") :background-color value))
(defun get-list (prefix key value)
`(,(get-list-key prefix key) . (,(get-list-value prefix key value))))
(defun collect-colors (colors prefix)
(loop for i in colors
collect (get-list prefix (car i) (cdr i))))
(defvar *bg-others* '(("bg-inherit" . ((".bg-inherit" :background-color "inherit")))
("bg-current" . ((".bg-current" :background-color "currentColor")))
("bg-transparent" . ((".bg-transparent" :background-color "transparent")))
("bg-black" . ((".bg-black" :background-color "rgb(0 0 0)")))
("bg-white" . ((".bg-white" :background-color "rgb(255 255 255)")))))
(defvar *bg-color-slate* (collect-colors *slate-colors* "bg-slate-"))
(defvar *bg-color-gray* (collect-colors *gray-colors* "bg-gray-"))
(defvar *bg-color-zinc* (collect-colors *zinc-colors* "bg-zinc-"))
(defvar *bg-color-neutral* (collect-colors *neutral-colors* "bg-neutral-"))
(defvar *bg-color-stone* (collect-colors *stone-colors* "bg-stone-"))
(defvar *bg-color-red* (collect-colors *red-colors* "bg-red-"))
(defvar *bg-color-orange* (collect-colors *orange-colors* "bg-orange-"))
(defvar *bg-color-amber* (collect-colors *amber-colors* "bg-amber-"))
(defvar *bg-color-yellow* (collect-colors *yellow-colors* "bg-yellow-"))
(defvar *bg-color-lime* (collect-colors *lime-colors* "bg-lime-"))
(defvar *bg-color-green* (collect-colors *green-colors* "bg-green-"))
(defvar *bg-color-emerald* (collect-colors *emerald-colors* "bg-emerald-"))
(defvar *bg-color-teal* (collect-colors *teal-colors* "bg-teal-"))
(defvar *bg-color-cyan* (collect-colors *cyan-colors* "bg-cyan-"))
(defvar *bg-color-sky* (collect-colors *sky-colors* "bg-sky-"))
(defvar *bg-color-blue* (collect-colors *blue-colors* "bg-blue-"))
(defvar *bg-color-indigo* (collect-colors *indigo-colors* "bg-indigo-"))
(defvar *bg-color-violet* (collect-colors *violet-colors* "bg-violet-"))
(defvar *bg-color-purple* (collect-colors *purple-colors* "bg-purple-"))
(defvar *bg-color-fuchsia* (collect-colors *fuchsia-colors* "bg-fuchsia-"))
(defvar *bg-color-pink* (collect-colors *pink-colors* "bg-pink-"))
(defvar *bg-color-rose* (collect-colors *rose-colors* "bg-rose-"))
(defvar *background-attachment* '(("bg-fixed" . ((".bg-fixed" :background-attachment "fixed")))
("bg-local" . ((".bg-local" :background-attachment "local")))
("bg-scroll" . ((".bg-scroll" :background-attachment "scroll")))))
(defvar *background-clip* '(("bg-clip-border" . ((".bg-clip-border" :background-clip "border-box")))
("bg-clip-padding" . ((".bg-clip-padding" :background-clip "padding-box")))
("bg-clip-content" . ((".bg-clip-content" :background-clip "content-box")))
("bg-clip-text" . ((".bg-clip-text" :background-clip "text")))))
(defvar *background-origin* '(("bg-origin-border" . ((".bg-origin-border" :background-origin "border-box")))
("bg-origin-padding" . ((".bg-origin-padding" :background-origin "padding-box")))
("bg-origin-content" . ((".bg-origin-content" :background-origin "content-box")))))
(defvar *background-position* '(("bg-bottom" . ((".bg-bottom" :background-position "bottom")))
("bg-center" . ((".bg-center" :background-position "center")))
("bg-left" . ((".bg-left" :background-position "left")))
("bg-left-bottom" . ((".bg-left-bottom" :background-position "left bottom")))
("bg-left-top" . ((".bg-left-top" :background-position "left top")))
("bg-right" . ((".bg-right" :background-position "right")))
("bg-right-bottom" . ((".bg-right-bottom" :background-position "right bottom")))
("bg-right-top" . ((".bg-right-top" :background-position "right top")))
("bg-top" . ((".bg-top" :background-position "top")))))
(defvar *background-repeat* '(("bg-repeat" . ((".bg-repeat" :background-repeat "repeat")))
("bg-no-repeat" . ((".bg-no-repeat" :background-repeat "no-repeat")))
("bg-repeat-x" . ((".bg-repeat-x" :background-repeat "repeat-x")))
("bg-repeat-y" . ((".bg-repeat-y" :background-repeat "repeat-y")))
("bg-repeat-round" . ((".bg-repeat-round" :background-repeat "round")))
("bg-repeat-space" . ((".bg-repeat-space" :background-repeat "space")))))
(defvar *background-size* '(("bg-auto" . ((".bg-auto" :background-size "auto")))
("bg-cover" . ((".bg-cover" :background-size "cover")))
("bg-contain" . ((".bg-contain" :background-size "contain")))))
(defvar *backgrounds* (append
*bg-color-slate*
*bg-color-gray*
*bg-color-zinc*
*bg-color-neutral*
*bg-color-stone*
*bg-color-red*
*bg-color-orange*
*bg-color-amber*
*bg-color-yellow*
*bg-color-lime*
*bg-color-green*
*bg-color-emerald*
*bg-color-teal*
*bg-color-cyan*
*bg-color-sky*
*bg-color-blue*
*bg-color-indigo*
*bg-color-violet*
*bg-color-purple*
*bg-color-fuchsia*
*bg-color-pink*
*bg-color-rose*
*bg-others*
*background-attachment*
*background-clip*
*background-origin*
*background-position*
*background-repeat*
*background-size*
))
|
0e8f10af3b457cba5a6e999bf276feff536912efcb3b883eb949911f9ad0b592 | flexsurfer/re-frisk | interop.cljs | (ns ^{:mranderson/inlined true} re-frisk.inlined-deps.reagent.v1v0v0.reagent.interop
(:require-macros [re-frisk.inlined-deps.reagent.v1v0v0.reagent.interop]))
| null | https://raw.githubusercontent.com/flexsurfer/re-frisk/638d820c84e23be79b8c52f8f136a611d942443f/re-frisk/src/re_frisk/inlined_deps/reagent/v1v0v0/reagent/interop.cljs | clojure | (ns ^{:mranderson/inlined true} re-frisk.inlined-deps.reagent.v1v0v0.reagent.interop
(:require-macros [re-frisk.inlined-deps.reagent.v1v0v0.reagent.interop]))
|
|
249485a0cb56d4fdb64e6e087e0cdf14e706749a8379c9cbc271a08f12f449bd | astanin/moo | moo-tests.hs | import System.Exit
import Test.HUnit
import Tests.Internals.TestFundamentals (testFundamentals)
import Tests.Internals.TestControl (testControl)
import Tests.Internals.TestSelection (testSelection)
import Tests.Internals.TestCrossover (testCrossover)
import Tests.Internals.TestConstraints (testConstraints)
import Tests.Internals.TestMultiobjective (testMultiobjective)
import Tests.Problems.Rosenbrock (testRosenbrock)
allTests = TestList
[ testFundamentals
, testControl
, testSelection
, testCrossover
, testConstraints
, testRosenbrock
, testMultiobjective
]
main = do
result <- runTestTT allTests
if (errors result + failures result) > 0
then exitFailure
else exitSuccess
| null | https://raw.githubusercontent.com/astanin/moo/2e77a94a543d21360f7610c1ee0dda52813997c4/moo-tests.hs | haskell | import System.Exit
import Test.HUnit
import Tests.Internals.TestFundamentals (testFundamentals)
import Tests.Internals.TestControl (testControl)
import Tests.Internals.TestSelection (testSelection)
import Tests.Internals.TestCrossover (testCrossover)
import Tests.Internals.TestConstraints (testConstraints)
import Tests.Internals.TestMultiobjective (testMultiobjective)
import Tests.Problems.Rosenbrock (testRosenbrock)
allTests = TestList
[ testFundamentals
, testControl
, testSelection
, testCrossover
, testConstraints
, testRosenbrock
, testMultiobjective
]
main = do
result <- runTestTT allTests
if (errors result + failures result) > 0
then exitFailure
else exitSuccess
|
|
1b540e6e544055fcd85591ba9c8f4e71a7f6ded4826243e5752033d7a1966c51 | ChrisTitusTech/gimphelp | 210_sharpness-softer_blur-non-edges.scm | 210_sharpness-softer_blur-non-edges.scm
last modified / tested by [ gimphelp.org ]
05/11/2019 on GIMP 2.10.10
;==================================================
;
; Installation:
; This script should be placed in the user or system-wide script folder.
;
; Windows 7/10
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
; or
C:\Users\YOUR - NAME\AppData\Roaming\GIMP\2.10\scripts
;
;
; Linux
; /home/yourname/.config/GIMP/2.10/scripts
; or
; Linux system-wide
; /usr/share/gimp/2.0/scripts
;
;==================================================
; Original information
;
Blur Non - Edges version 0.9.1
;
Blurs those areas of a picture which are considered not edges , that
; is are more or less uniform color areas. This is somewhat like the
standard Selective Gaussian Blur plugin , but gives better results in
some situations . Also try running this script first , and then
; Selective Gaussian Blur on the resulting image.
;
; Technically, the script works as following.
;
; - find edges
; - make a selection that doesn't include the edges
; - shrink and feather the selection in proportion to blur radius
; - perform gaussian blur
;
; End original information ------------------------------------------
(define (210-blur-non-edges image layer select-threshold blur-strength show-used-selection)
(gimp-image-undo-group-start image)
(let* ((saved-selection (car (gimp-selection-save image)))
(saved-selection-empty (car (gimp-selection-is-empty image))))
(let* ((dup-layer (car (gimp-layer-copy layer 1))))
(gimp-image-insert-layer image dup-layer 0 -1)
(plug-in-edge 1 image dup-layer 2 2 0)
(gimp-image-select-color image CHANNEL-OP-REPLACE dup-layer '(0 0 0))
(if (= TRUE saved-selection-empty)
'()
(gimp-selection-combine saved-selection CHANNEL-OP-INTERSECT))
(gimp-image-remove-layer image dup-layer)
)
(gimp-selection-shrink image (/ blur-strength 2))
(gimp-selection-feather image blur-strength)
(gimp-image-set-active-layer image layer)
(plug-in-gauss-iir2 1 image layer blur-strength blur-strength)
(if (= TRUE show-used-selection)
'()
(gimp-image-select-item image CHANNEL-OP-REPLACE saved-selection))
(gimp-image-remove-channel image saved-selection)
(gimp-displays-flush)
(gimp-image-undo-group-end image))
)
(script-fu-register "210-blur-non-edges"
"Blur Non-Edges"
"Gaussian blur smooth, non-edge areas of the image"
"Samuli Kärkkäinen"
"Samuli Kärkkäinen"
"2005-01-08"
"RGB* GRAY*"
SF-IMAGE "Font" 0
SF-DRAWABLE "Font Size" 0
SF-ADJUSTMENT "Non-edge selection threshold" '(60 0 255 1 10 0 0)
SF-ADJUSTMENT "Blur radius" '(5 0.1 999 0.1 1 1 1)
SF-TOGGLE "Show used selection" FALSE
)
(script-fu-menu-register "210-blur-non-edges" "<Image>/Script-Fu/Sharpness/Softer")
| null | https://raw.githubusercontent.com/ChrisTitusTech/gimphelp/fdbc7e3671ce6bd74cefd83ecf7216e5ee0f1542/gimp_scripts-2.10/210_sharpness-softer_blur-non-edges.scm | scheme | ==================================================
Installation:
This script should be placed in the user or system-wide script folder.
Windows 7/10
or
Linux
/home/yourname/.config/GIMP/2.10/scripts
or
Linux system-wide
/usr/share/gimp/2.0/scripts
==================================================
Original information
is are more or less uniform color areas. This is somewhat like the
Selective Gaussian Blur on the resulting image.
Technically, the script works as following.
- find edges
- make a selection that doesn't include the edges
- shrink and feather the selection in proportion to blur radius
- perform gaussian blur
End original information ------------------------------------------ | 210_sharpness-softer_blur-non-edges.scm
last modified / tested by [ gimphelp.org ]
05/11/2019 on GIMP 2.10.10
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
C:\Users\YOUR - NAME\AppData\Roaming\GIMP\2.10\scripts
Blur Non - Edges version 0.9.1
Blurs those areas of a picture which are considered not edges , that
standard Selective Gaussian Blur plugin , but gives better results in
some situations . Also try running this script first , and then
(define (210-blur-non-edges image layer select-threshold blur-strength show-used-selection)
(gimp-image-undo-group-start image)
(let* ((saved-selection (car (gimp-selection-save image)))
(saved-selection-empty (car (gimp-selection-is-empty image))))
(let* ((dup-layer (car (gimp-layer-copy layer 1))))
(gimp-image-insert-layer image dup-layer 0 -1)
(plug-in-edge 1 image dup-layer 2 2 0)
(gimp-image-select-color image CHANNEL-OP-REPLACE dup-layer '(0 0 0))
(if (= TRUE saved-selection-empty)
'()
(gimp-selection-combine saved-selection CHANNEL-OP-INTERSECT))
(gimp-image-remove-layer image dup-layer)
)
(gimp-selection-shrink image (/ blur-strength 2))
(gimp-selection-feather image blur-strength)
(gimp-image-set-active-layer image layer)
(plug-in-gauss-iir2 1 image layer blur-strength blur-strength)
(if (= TRUE show-used-selection)
'()
(gimp-image-select-item image CHANNEL-OP-REPLACE saved-selection))
(gimp-image-remove-channel image saved-selection)
(gimp-displays-flush)
(gimp-image-undo-group-end image))
)
(script-fu-register "210-blur-non-edges"
"Blur Non-Edges"
"Gaussian blur smooth, non-edge areas of the image"
"Samuli Kärkkäinen"
"Samuli Kärkkäinen"
"2005-01-08"
"RGB* GRAY*"
SF-IMAGE "Font" 0
SF-DRAWABLE "Font Size" 0
SF-ADJUSTMENT "Non-edge selection threshold" '(60 0 255 1 10 0 0)
SF-ADJUSTMENT "Blur radius" '(5 0.1 999 0.1 1 1 1)
SF-TOGGLE "Show used selection" FALSE
)
(script-fu-menu-register "210-blur-non-edges" "<Image>/Script-Fu/Sharpness/Softer")
|
65d4e20a590e6b1e41b7a300b34399edb59698135e0d2c5db1e58b5098243d41 | yogthos/memory-hole | md_editor.cljs | (ns memory-hole.widgets.md-editor
(:require [reagent.core :as r]
[re-frame.core :refer [dispatch subscribe]]))
(def ^{:private true} hint-limit 10)
(def ^{:private true} word-pattern-left #".*(#.*)$")
(def ^{:private true} word-pattern-right #"^(#?.*).*")
(defn- current-word [cm]
"Returns current word and its coordinates from editor cm."
(let [cursor (.getCursor cm "from")
line (.-line cursor)
char (.-ch cursor)
text (.getLine (.-doc cm) line)
parts (split-at char text)
leftp (->> (first parts) (apply str) (re-matches word-pattern-left) second)
rightp (->> (second parts) (apply str) (re-matches word-pattern-right) second)]
{:word (str leftp rightp)
:from (- char (count leftp))
:to (+ char (count rightp))}))
(defn- apply-hint [editor self data]
"Applies hint data to editor by replacing its sub-part."
(let [cursor (.getCursor editor "from")
pos (current-word editor)
from (:from pos)
to (:to pos)
word (:word pos)]
(.replaceRange editor
(str "[#" (.-text data) "](/issue/" (.-text data) ")")
(clj->js {:line (.-line cursor)
:ch from})
(clj->js {:line (.-line cursor)
:ch to}))))
(defn- render-hint [element self data]
"Renders hint data into element."
(r/render
[:div.list-group-item
[:span "#" (get-in (js->clj data) ["displayText" "support-issue-id"])]
" "
[:span (get-in (js->clj data) ["displayText" "title"])]]
element))
(defn- create-hint [hint]
"Creates hint for show-hint extension."
{:text (str (:support-issue-id hint))
:displayText hint
:render render-hint
:hint apply-hint})
(defn- markdown-hints [hints]
"Show-hint handler."
(fn [c o]
(clj->js {:list (map create-hint hints)
:from (.getCursor c "from")})))
(defn- show-hint [cm]
"Shows hints for editor cm via show-hint extension."
(fn [k r os ns]
(.showHint
cm
(clj->js {:hint (markdown-hints (:issues @ns))
:completeSingle false}))))
(defn- sent-hint-request [cm]
"Sends hint request to server."
(let [current (:word (current-word cm))]
(if (not (empty? current))
(dispatch [:get-issue-hints (subs current 1) hint-limit]))))
(defn- editor-set-shortcut [editor]
"Sets shortcut for issue hints into editor."
(aset
editor
"options"
"extraKeys"
(clj->js
{"Ctrl-Space" sent-hint-request})))
(extend-type js/NodeList
IIndexed
(-nth
([array n]
(if (< n (alength array)) (aget array n)))
([array n not-found]
(if (< n (alength array)) (aget array n)
not-found))))
(defn- inject-editor-implementation
"Injects CodeMirror editor instance into SimpleMDE, which can be then
extended by plugins. This is a hack and can be removed if SimpleMDE
changes availability of CodeMirror."
[editor]
(do
;; move editor into text area
(-> editor .-codemirror .toTextArea)
;; create new instance via fromTextArea (recommended)
(aset
editor
"codemirror"
(.fromTextArea js/CodeMirror (-> editor .-codemirror .getTextArea) (clj->js {:lineWrapping true})))
manipulate DOM so element is on right place
(.insertBefore (-> editor
.-codemirror
.getScrollerElement
.-parentNode
.-parentNode)
(-> editor
.-codemirror
.getScrollerElement
.-parentNode)
(-> editor
.-codemirror
.getScrollerElement
.-parentNode
.-parentNode
.-childNodes
(nth 3)))))
(defn editor [text issue-hints]
(r/create-class
{:component-did-mount
#(let [editor (js/SimpleMDE.
(clj->js
{:autofocus true
:spellChecker false
:status false
:placeholder "Issue details"
:toolbar ["bold"
"italic"
"strikethrough"
"|"
"heading"
"code"
"quote"
"|"
"unordered-list"
"ordered-list"
"|"
"link"
"image"]
:element (r/dom-node %)
:initialValue @text}))
hints-shown (atom false)]
(do
(inject-editor-implementation editor)
(editor-set-shortcut (-> editor .-codemirror))
(add-watch issue-hints :watch-issue-hints (show-hint (-> editor .-codemirror)))
(-> editor .-codemirror (.on "change" (fn [] (reset! text (.value editor)))))
(-> editor .-codemirror (.on "change" (fn [] (when @hints-shown (sent-hint-request (-> editor .-codemirror))))))
(-> editor .-codemirror (.on "startCompletion" (fn [] (reset! hints-shown true))))
(-> editor .-codemirror (.on "endCompletion" (fn [] (reset! hints-shown false))))))
:reagent-render
(fn [text issue-hints]
(do
@issue-hints ;; dereference hints, so add-watch is not optimized out
[:textarea]))}))
| null | https://raw.githubusercontent.com/yogthos/memory-hole/925e399b0002d59998d10bd6f54ff3464a4b4ddb/src/cljs/memory_hole/widgets/md_editor.cljs | clojure | move editor into text area
create new instance via fromTextArea (recommended)
dereference hints, so add-watch is not optimized out | (ns memory-hole.widgets.md-editor
(:require [reagent.core :as r]
[re-frame.core :refer [dispatch subscribe]]))
(def ^{:private true} hint-limit 10)
(def ^{:private true} word-pattern-left #".*(#.*)$")
(def ^{:private true} word-pattern-right #"^(#?.*).*")
(defn- current-word [cm]
"Returns current word and its coordinates from editor cm."
(let [cursor (.getCursor cm "from")
line (.-line cursor)
char (.-ch cursor)
text (.getLine (.-doc cm) line)
parts (split-at char text)
leftp (->> (first parts) (apply str) (re-matches word-pattern-left) second)
rightp (->> (second parts) (apply str) (re-matches word-pattern-right) second)]
{:word (str leftp rightp)
:from (- char (count leftp))
:to (+ char (count rightp))}))
(defn- apply-hint [editor self data]
"Applies hint data to editor by replacing its sub-part."
(let [cursor (.getCursor editor "from")
pos (current-word editor)
from (:from pos)
to (:to pos)
word (:word pos)]
(.replaceRange editor
(str "[#" (.-text data) "](/issue/" (.-text data) ")")
(clj->js {:line (.-line cursor)
:ch from})
(clj->js {:line (.-line cursor)
:ch to}))))
(defn- render-hint [element self data]
"Renders hint data into element."
(r/render
[:div.list-group-item
[:span "#" (get-in (js->clj data) ["displayText" "support-issue-id"])]
" "
[:span (get-in (js->clj data) ["displayText" "title"])]]
element))
(defn- create-hint [hint]
"Creates hint for show-hint extension."
{:text (str (:support-issue-id hint))
:displayText hint
:render render-hint
:hint apply-hint})
(defn- markdown-hints [hints]
"Show-hint handler."
(fn [c o]
(clj->js {:list (map create-hint hints)
:from (.getCursor c "from")})))
(defn- show-hint [cm]
"Shows hints for editor cm via show-hint extension."
(fn [k r os ns]
(.showHint
cm
(clj->js {:hint (markdown-hints (:issues @ns))
:completeSingle false}))))
(defn- sent-hint-request [cm]
"Sends hint request to server."
(let [current (:word (current-word cm))]
(if (not (empty? current))
(dispatch [:get-issue-hints (subs current 1) hint-limit]))))
(defn- editor-set-shortcut [editor]
"Sets shortcut for issue hints into editor."
(aset
editor
"options"
"extraKeys"
(clj->js
{"Ctrl-Space" sent-hint-request})))
(extend-type js/NodeList
IIndexed
(-nth
([array n]
(if (< n (alength array)) (aget array n)))
([array n not-found]
(if (< n (alength array)) (aget array n)
not-found))))
(defn- inject-editor-implementation
"Injects CodeMirror editor instance into SimpleMDE, which can be then
extended by plugins. This is a hack and can be removed if SimpleMDE
changes availability of CodeMirror."
[editor]
(do
(-> editor .-codemirror .toTextArea)
(aset
editor
"codemirror"
(.fromTextArea js/CodeMirror (-> editor .-codemirror .getTextArea) (clj->js {:lineWrapping true})))
manipulate DOM so element is on right place
(.insertBefore (-> editor
.-codemirror
.getScrollerElement
.-parentNode
.-parentNode)
(-> editor
.-codemirror
.getScrollerElement
.-parentNode)
(-> editor
.-codemirror
.getScrollerElement
.-parentNode
.-parentNode
.-childNodes
(nth 3)))))
(defn editor [text issue-hints]
(r/create-class
{:component-did-mount
#(let [editor (js/SimpleMDE.
(clj->js
{:autofocus true
:spellChecker false
:status false
:placeholder "Issue details"
:toolbar ["bold"
"italic"
"strikethrough"
"|"
"heading"
"code"
"quote"
"|"
"unordered-list"
"ordered-list"
"|"
"link"
"image"]
:element (r/dom-node %)
:initialValue @text}))
hints-shown (atom false)]
(do
(inject-editor-implementation editor)
(editor-set-shortcut (-> editor .-codemirror))
(add-watch issue-hints :watch-issue-hints (show-hint (-> editor .-codemirror)))
(-> editor .-codemirror (.on "change" (fn [] (reset! text (.value editor)))))
(-> editor .-codemirror (.on "change" (fn [] (when @hints-shown (sent-hint-request (-> editor .-codemirror))))))
(-> editor .-codemirror (.on "startCompletion" (fn [] (reset! hints-shown true))))
(-> editor .-codemirror (.on "endCompletion" (fn [] (reset! hints-shown false))))))
:reagent-render
(fn [text issue-hints]
(do
[:textarea]))}))
|
063cb82ae2717134e36160febdfe2c523fdb59b51938fad7e039a2371731cadd | xapi-project/xenopsd | xenops_server_plugin.ml |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
open Xenops_interface
open Xenops_utils
open Xenops_task
type domain_action_request =
| Needs_poweroff
| Needs_reboot
| Needs_suspend
| Needs_crashdump
| Needs_softreset
[@@deriving rpcty]
type device_action_request = Needs_unplug | Needs_set_qos
type shutdown_request = Halt | Reboot | PowerOff | S3Suspend | Suspend
[@@deriving rpcty]
type rename_when = Pre_migration | Post_migration [@@deriving rpcty]
let rpc_of : type x. x Rpc.Types.def -> x -> Rpc.t =
fun def x -> Rpcmarshal.marshal def.Rpc.Types.ty x
let string_of_shutdown_request x =
x |> rpc_of shutdown_request |> Jsonrpc.to_string
let test = Updates.empty
let string_of_disk d = d |> rpc_of disk |> Jsonrpc.to_string
type data = Disk of disk | FD of Unix.file_descr [@@deriving rpcty]
let string_of_data x = x |> rpc_of data |> Jsonrpc.to_string
type flag = Live [@@deriving rpcty]
let string_of_flag = function Live -> "Live"
type progress_cb = float -> unit
module type S = sig
val init : unit -> unit
module HOST : sig
val stat : unit -> Host.t
val get_console_data : unit -> string
val get_total_memory_mib : unit -> int64
val send_debug_keys : string -> unit
val update_guest_agent_features : Host.guest_agent_feature list -> unit
val upgrade_cpu_features : int64 array -> bool -> int64 array
end
module VM : sig
val add : Vm.t -> unit
val remove : Vm.t -> unit
val rename : Vm.id -> Vm.id -> rename_when -> unit
val create :
Xenops_task.task_handle
-> int64 option
-> Vm.t
-> Vm.id option
-> bool (* no_sharept*)
-> unit
val build :
?restore_fd:Unix.file_descr
-> Xenops_task.task_handle
-> Vm.t
-> Vbd.t list
-> Vif.t list
-> Vgpu.t list
-> Vusb.t list
-> string list
-> bool
-> unit
(* XXX cancel *)
val create_device_model :
Xenops_task.task_handle
-> Vm.t
-> Vbd.t list
-> Vif.t list
-> Vgpu.t list
-> Vusb.t list
-> bool
-> unit
val destroy_device_model : Xenops_task.task_handle -> Vm.t -> unit
val destroy : Xenops_task.task_handle -> Vm.t -> unit
val pause : Xenops_task.task_handle -> Vm.t -> unit
val unpause : Xenops_task.task_handle -> Vm.t -> unit
val set_xsdata :
Xenops_task.task_handle -> Vm.t -> (string * string) list -> unit
val set_vcpus : Xenops_task.task_handle -> Vm.t -> int -> unit
val set_shadow_multiplier : Xenops_task.task_handle -> Vm.t -> float -> unit
val set_memory_dynamic_range :
Xenops_task.task_handle -> Vm.t -> int64 -> int64 -> unit
val request_shutdown :
Xenops_task.task_handle -> Vm.t -> shutdown_request -> float -> bool
val wait_shutdown :
Xenops_task.task_handle -> Vm.t -> shutdown_request -> float -> bool
val assert_can_save : Vm.t -> unit
val save :
Xenops_task.task_handle
-> progress_cb
-> Vm.t
-> flag list
-> data
-> data option
-> (Xenops_task.task_handle -> unit)
-> unit
val restore :
Xenops_task.task_handle
-> progress_cb
-> Vm.t
-> Vbd.t list
-> Vif.t list
-> data
-> data option
-> string list
-> unit
val s3suspend : Xenops_task.task_handle -> Vm.t -> unit
val s3resume : Xenops_task.task_handle -> Vm.t -> unit
val soft_reset : Xenops_task.task_handle -> Vm.t -> unit
val get_state : Vm.t -> Vm.state
val request_rdp : Vm.t -> bool -> unit
val run_script : Xenops_task.task_handle -> Vm.t -> string -> Rpc.t
val set_domain_action_request : Vm.t -> domain_action_request option -> unit
val get_domain_action_request : Vm.t -> domain_action_request option
val get_hook_args : Vm.id -> string list
val generate_state_string : Vm.t -> string
val get_internal_state :
(string * string) list -> (string * Network.t) list -> Vm.t -> string
val set_internal_state : Vm.t -> string -> unit
val wait_ballooning : Xenops_task.task_handle -> Vm.t -> unit
val minimum_reboot_delay : float
end
module PCI : sig
val get_state : Vm.id -> Pci.t -> Pci.state
val plug : Xenops_task.task_handle -> Vm.id -> Pci.t -> bool -> unit
val unplug : Xenops_task.task_handle -> Vm.id -> Pci.t -> unit
val get_device_action_request :
Vm.id -> Pci.t -> device_action_request option
val dequarantine : Pci.address -> unit
end
module VBD : sig
val set_active : Xenops_task.task_handle -> Vm.id -> Vbd.t -> bool -> unit
val epoch_begin : Xenops_task.task_handle -> Vm.id -> disk -> bool -> unit
val epoch_end : Xenops_task.task_handle -> Vm.id -> disk -> unit
val plug : Xenops_task.task_handle -> Vm.id -> Vbd.t -> unit
val unplug : Xenops_task.task_handle -> Vm.id -> Vbd.t -> bool -> unit
val insert : Xenops_task.task_handle -> Vm.id -> Vbd.t -> disk -> unit
val eject : Xenops_task.task_handle -> Vm.id -> Vbd.t -> unit
val set_qos : Xenops_task.task_handle -> Vm.id -> Vbd.t -> unit
val get_state : Vm.id -> Vbd.t -> Vbd.state
val get_device_action_request :
Vm.id -> Vbd.t -> device_action_request option
end
module VIF : sig
val set_active : Xenops_task.task_handle -> Vm.id -> Vif.t -> bool -> unit
val plug : Xenops_task.task_handle -> Vm.id -> Vif.t -> unit
val unplug : Xenops_task.task_handle -> Vm.id -> Vif.t -> bool -> unit
val move : Xenops_task.task_handle -> Vm.id -> Vif.t -> Network.t -> unit
val set_carrier : Xenops_task.task_handle -> Vm.id -> Vif.t -> bool -> unit
val set_locking_mode :
Xenops_task.task_handle -> Vm.id -> Vif.t -> Vif.locking_mode -> unit
val set_ipv4_configuration :
Xenops_task.task_handle
-> Vm.id
-> Vif.t
-> Vif.ipv4_configuration
-> unit
val set_ipv6_configuration :
Xenops_task.task_handle
-> Vm.id
-> Vif.t
-> Vif.ipv6_configuration
-> unit
val set_pvs_proxy :
Xenops_task.task_handle
-> Vm.id
-> Vif.t
-> Vif.PVS_proxy.t option
-> unit
val get_state : Vm.id -> Vif.t -> Vif.state
val get_device_action_request :
Vm.id -> Vif.t -> device_action_request option
end
module VGPU : sig
val start : Xenops_task.task_handle -> Vm.id -> Vgpu.t list -> bool -> unit
val set_active : Xenops_task.task_handle -> Vm.id -> Vgpu.t -> bool -> unit
val get_state : Vm.id -> Vgpu.t -> Vgpu.state
end
module VUSB : sig
val plug : Xenops_task.task_handle -> Vm.id -> Vusb.t -> unit
val unplug : Xenops_task.task_handle -> Vm.id -> Vusb.t -> unit
val get_state : Vm.id -> Vusb.t -> Vusb.state
val get_device_action_request :
Vm.id -> Vusb.t -> device_action_request option
end
module UPDATES : sig
val get :
Updates.id option
-> int option
-> Dynamic.barrier list * Dynamic.id list * Updates.id
end
module DEBUG : sig
val trigger : string -> string list -> unit
end
end
| null | https://raw.githubusercontent.com/xapi-project/xenopsd/f4da21a4ead7c6a7082af5ec32f778faf368cf1c/lib/xenops_server_plugin.ml | ocaml | no_sharept
XXX cancel |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
open Xenops_interface
open Xenops_utils
open Xenops_task
type domain_action_request =
| Needs_poweroff
| Needs_reboot
| Needs_suspend
| Needs_crashdump
| Needs_softreset
[@@deriving rpcty]
type device_action_request = Needs_unplug | Needs_set_qos
type shutdown_request = Halt | Reboot | PowerOff | S3Suspend | Suspend
[@@deriving rpcty]
type rename_when = Pre_migration | Post_migration [@@deriving rpcty]
let rpc_of : type x. x Rpc.Types.def -> x -> Rpc.t =
fun def x -> Rpcmarshal.marshal def.Rpc.Types.ty x
let string_of_shutdown_request x =
x |> rpc_of shutdown_request |> Jsonrpc.to_string
let test = Updates.empty
let string_of_disk d = d |> rpc_of disk |> Jsonrpc.to_string
type data = Disk of disk | FD of Unix.file_descr [@@deriving rpcty]
let string_of_data x = x |> rpc_of data |> Jsonrpc.to_string
type flag = Live [@@deriving rpcty]
let string_of_flag = function Live -> "Live"
type progress_cb = float -> unit
module type S = sig
val init : unit -> unit
module HOST : sig
val stat : unit -> Host.t
val get_console_data : unit -> string
val get_total_memory_mib : unit -> int64
val send_debug_keys : string -> unit
val update_guest_agent_features : Host.guest_agent_feature list -> unit
val upgrade_cpu_features : int64 array -> bool -> int64 array
end
module VM : sig
val add : Vm.t -> unit
val remove : Vm.t -> unit
val rename : Vm.id -> Vm.id -> rename_when -> unit
val create :
Xenops_task.task_handle
-> int64 option
-> Vm.t
-> Vm.id option
-> unit
val build :
?restore_fd:Unix.file_descr
-> Xenops_task.task_handle
-> Vm.t
-> Vbd.t list
-> Vif.t list
-> Vgpu.t list
-> Vusb.t list
-> string list
-> bool
-> unit
val create_device_model :
Xenops_task.task_handle
-> Vm.t
-> Vbd.t list
-> Vif.t list
-> Vgpu.t list
-> Vusb.t list
-> bool
-> unit
val destroy_device_model : Xenops_task.task_handle -> Vm.t -> unit
val destroy : Xenops_task.task_handle -> Vm.t -> unit
val pause : Xenops_task.task_handle -> Vm.t -> unit
val unpause : Xenops_task.task_handle -> Vm.t -> unit
val set_xsdata :
Xenops_task.task_handle -> Vm.t -> (string * string) list -> unit
val set_vcpus : Xenops_task.task_handle -> Vm.t -> int -> unit
val set_shadow_multiplier : Xenops_task.task_handle -> Vm.t -> float -> unit
val set_memory_dynamic_range :
Xenops_task.task_handle -> Vm.t -> int64 -> int64 -> unit
val request_shutdown :
Xenops_task.task_handle -> Vm.t -> shutdown_request -> float -> bool
val wait_shutdown :
Xenops_task.task_handle -> Vm.t -> shutdown_request -> float -> bool
val assert_can_save : Vm.t -> unit
val save :
Xenops_task.task_handle
-> progress_cb
-> Vm.t
-> flag list
-> data
-> data option
-> (Xenops_task.task_handle -> unit)
-> unit
val restore :
Xenops_task.task_handle
-> progress_cb
-> Vm.t
-> Vbd.t list
-> Vif.t list
-> data
-> data option
-> string list
-> unit
val s3suspend : Xenops_task.task_handle -> Vm.t -> unit
val s3resume : Xenops_task.task_handle -> Vm.t -> unit
val soft_reset : Xenops_task.task_handle -> Vm.t -> unit
val get_state : Vm.t -> Vm.state
val request_rdp : Vm.t -> bool -> unit
val run_script : Xenops_task.task_handle -> Vm.t -> string -> Rpc.t
val set_domain_action_request : Vm.t -> domain_action_request option -> unit
val get_domain_action_request : Vm.t -> domain_action_request option
val get_hook_args : Vm.id -> string list
val generate_state_string : Vm.t -> string
val get_internal_state :
(string * string) list -> (string * Network.t) list -> Vm.t -> string
val set_internal_state : Vm.t -> string -> unit
val wait_ballooning : Xenops_task.task_handle -> Vm.t -> unit
val minimum_reboot_delay : float
end
module PCI : sig
val get_state : Vm.id -> Pci.t -> Pci.state
val plug : Xenops_task.task_handle -> Vm.id -> Pci.t -> bool -> unit
val unplug : Xenops_task.task_handle -> Vm.id -> Pci.t -> unit
val get_device_action_request :
Vm.id -> Pci.t -> device_action_request option
val dequarantine : Pci.address -> unit
end
module VBD : sig
val set_active : Xenops_task.task_handle -> Vm.id -> Vbd.t -> bool -> unit
val epoch_begin : Xenops_task.task_handle -> Vm.id -> disk -> bool -> unit
val epoch_end : Xenops_task.task_handle -> Vm.id -> disk -> unit
val plug : Xenops_task.task_handle -> Vm.id -> Vbd.t -> unit
val unplug : Xenops_task.task_handle -> Vm.id -> Vbd.t -> bool -> unit
val insert : Xenops_task.task_handle -> Vm.id -> Vbd.t -> disk -> unit
val eject : Xenops_task.task_handle -> Vm.id -> Vbd.t -> unit
val set_qos : Xenops_task.task_handle -> Vm.id -> Vbd.t -> unit
val get_state : Vm.id -> Vbd.t -> Vbd.state
val get_device_action_request :
Vm.id -> Vbd.t -> device_action_request option
end
module VIF : sig
val set_active : Xenops_task.task_handle -> Vm.id -> Vif.t -> bool -> unit
val plug : Xenops_task.task_handle -> Vm.id -> Vif.t -> unit
val unplug : Xenops_task.task_handle -> Vm.id -> Vif.t -> bool -> unit
val move : Xenops_task.task_handle -> Vm.id -> Vif.t -> Network.t -> unit
val set_carrier : Xenops_task.task_handle -> Vm.id -> Vif.t -> bool -> unit
val set_locking_mode :
Xenops_task.task_handle -> Vm.id -> Vif.t -> Vif.locking_mode -> unit
val set_ipv4_configuration :
Xenops_task.task_handle
-> Vm.id
-> Vif.t
-> Vif.ipv4_configuration
-> unit
val set_ipv6_configuration :
Xenops_task.task_handle
-> Vm.id
-> Vif.t
-> Vif.ipv6_configuration
-> unit
val set_pvs_proxy :
Xenops_task.task_handle
-> Vm.id
-> Vif.t
-> Vif.PVS_proxy.t option
-> unit
val get_state : Vm.id -> Vif.t -> Vif.state
val get_device_action_request :
Vm.id -> Vif.t -> device_action_request option
end
module VGPU : sig
val start : Xenops_task.task_handle -> Vm.id -> Vgpu.t list -> bool -> unit
val set_active : Xenops_task.task_handle -> Vm.id -> Vgpu.t -> bool -> unit
val get_state : Vm.id -> Vgpu.t -> Vgpu.state
end
module VUSB : sig
val plug : Xenops_task.task_handle -> Vm.id -> Vusb.t -> unit
val unplug : Xenops_task.task_handle -> Vm.id -> Vusb.t -> unit
val get_state : Vm.id -> Vusb.t -> Vusb.state
val get_device_action_request :
Vm.id -> Vusb.t -> device_action_request option
end
module UPDATES : sig
val get :
Updates.id option
-> int option
-> Dynamic.barrier list * Dynamic.id list * Updates.id
end
module DEBUG : sig
val trigger : string -> string list -> unit
end
end
|
e98a66b636a2420dc60d1dabdb10de5ffe3ffe4aadf0e262e039c8332f2334b2 | glondu/belenios | election.mli | include Belenios_core.Versioned_sig.ELECTION_SIG
| null | https://raw.githubusercontent.com/glondu/belenios/d267ee3c410855a0936f8f435f9961022ab885e0/src/lib/v1/election.mli | ocaml | include Belenios_core.Versioned_sig.ELECTION_SIG
|
|
9660b7ec554e642fcf4991baf7ec30d69ff1cbe4a491f1a80ef8c49c1b240994 | probcomp/haskell-trace-types | BasicExamples.hs | # LANGUAGE DataKinds , GADTs , KindSignatures , TypeFamilies , TypeOperators , TypeApplications , ScopedTypeVariables , MultiParamTypeClasses , OverloadedLabels , InstanceSigs , FlexibleContexts , FlexibleInstances , RankNTypes , UndecidableInstances , ConstraintKinds , OverlappingInstances , TypeFamilyDependencies #
# LANGUAGE RebindableSyntax #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE PartialTypeSignatures, NoMonomorphismRestriction #-}
# LANGUAGE RecordWildCards , , ConstraintKinds #
module BasicExamples where
import TraceTypes
import Control.Monad.Bayes.Class
import Control.Monad.Bayes.Weighted (runWeighted)
import Control.Monad.Bayes.Sampler
import Data.Row.Records (Rec, (.==), type (.==), (.!), (.+), type (.+), Empty)
import Data.Row.Internal (LT(..), Row(..))
import qualified Data.Vector.Sized as V
import Data.Vector.Sized (Vector)
import Prelude hiding ((>>=), (>>), return)
import Numeric.Log
import Control.Monad.Bayes.Inference.SMC
import Control.Monad.Bayes.Population
import Control.Monad.Bayes.Sequential
f >>= g = pBind f g
return :: Monad m => a -> P m Empty a
return = pReturn
f >> g = f >>= \_ -> g
-------------------------------
-------------------------------
-- --
EXAMPLES FROM FIGURE 1 --
-- Valid & Invalid Inference --
-- --
-------------------------------
-------------------------------
-- weight_model :: MonadInfer m => P m ("weight" .== Log Double .+ "measurement" .== Double) Double
weight_model = do
w <- sample #weight (gmma 2 1)
sample #measurement (nrm (realToFrac w) 0.2)
obs = #measurement .== 0.5
-- Importance Sampling
-- q1 :: MonadInfer m => P m ("weight" .== Unit) Unit
q1 = sample #weight unif
-- appliedQ1 :: Type Error
-- appliedQ1 = importance weight_model obs q1
-- q1' :: MonadInfer m => P m ("weight" .== Log Double) (Log Double)
q1' = sample #weight (gmma 2 0.25)
-- appliedQ1' :: MonadInfer m => m (Rec ("weight" .== Log Double))
appliedQ1' = importance weight_model obs q1'
MCMC
-- k1 :: MonadInfer m => K m ("weight" .== Log Double) ("weight" .== Log Double)
k1 = mh (\t -> sample #weight (truncnrm (t .! #weight) 0.2))
-- k2 :: MonadInfer m => K m ("weight" .== Log Double) ("weight" .== Log Double)
k2 = mh (\t -> sample #weight (truncnrm (t .! #weight) 1.0))
-- shouldUseK1 :: Rec ("weight" .== Log Double) -> Bool
shouldUseK1 t = t .! #weight <= 2
-- k :: Type Error
k = seqK ( ifK shouldUseK1 k1 )
-- (ifK (not . shouldUseK1) k2)
-- k' :: MonadInfer m => K m ("weight" .== Log Double) ("weight" .== Log Double)
k' = mh (\t -> let w = t .! #weight in
sample #weight (truncnrm w (if w < 2 then 0.2 else 1)))
-- appliedK' :: MonadInfer m => Rec ("weight" .== Log Double) -> m (Rec ("weight" .== Log Double))
appliedK' = k' (observe weight_model obs)
SVI
-- q2 :: MonadInfer m => (Double, Log Double) -> P m ("weight" .== Double) Double
q2 (a, b) = sample #weight (nrm a b)
-- appliedQ2 :: Type Error
appliedQ2 = svi weight_model obs q2
q2 ' : : MonadInfer m = > ( Log Double , Log Double ) - > P m ( " weight " .== Log Double ) ( Log Double )
q2' (a, b) = sample #weight (truncnrm a b)
-- appliedQ2' :: MonadInfer m => (Log Double, Log Double) -> m (Log Double, Log Double)
appliedQ2' = svi weight_model obs q2'
------------------------------
------------------------------
-- --
EXAMPLES FROM FIGURE 3 --
Control Flow Constructs --
-- --
------------------------------
------------------------------
-- simple1 :: MonadInfer m => P m ("x" .== Double .+ "z" .== Double) Double
simple1 = do
x <- sample #x (nrm 0 1)
z <- sample #z (nrm x 1)
return $ x + z
simple2 : : MonadInfer m = > P m ( " x " .== Double .+ " z " .== Double ) Double
simple2 = do
z <- sample #z (nrm 0 1)
x <- sample #x (nrm z 1)
return $ x + z
: : MonadInfer m = > P m ( " b " .== Bool .+ " p " .== Unit .+ " coin " .== Bool ) Bool
branch1 = do
isBiased <- sample #b (brn $ mkUnit 0.1)
p <- if isBiased then
sample #p (bta 1 2)
else
sample #p (unif)
sample #coin (brn p)
-- branch2
-- :: MonadInfer m
= > P m ( " p " .== Either ( Rec ( " isLow " .== Bool ) ) ( Rec Empty ) .+ " coin " .== Bool ) Bool
branch2 = do
p <- withProbability #p (mkUnit 0.1) (do {
isLow <- sample #isLow (brn (mkUnit 0.5));
return (if isLow then (mkUnit 0.01) else (mkUnit 0.99))
}) (return $ mkUnit 0.5)
sample #coin (brn p)
-- loop1 :: MonadInfer m => P m ("pts" .== [Rec ("x" .== Double .+ "y" .== Double)]) [Double]
loop1 = do
pts <- forRandomRange #pts (pois 3) (\i -> do {
x <- sample #x (nrm (fromIntegral i) 1);
sample #y (nrm x 1)
})
return $ map (\y -> 2 * y) pts
-- loop2 :: MonadInfer m => P m ("pts" .== Vector 3 (Rec ("y" .== Double))) [Double]
loop2 = do
pts <- forEach #pts (V.generate id :: Vector 3 Int) (\x -> do {
sample #y (nrm (fromIntegral x) 1)
})
return $ map (\y -> 2 * y) (V.toList pts)
------------------------------
------------------------------
-- --
EXAMPLES FROM FIGURE 4 --
-- End-to-End Example --
-- --
------------------------------
------------------------------
xs = V.generate (\i ->
case i of
0 -> -3.0
1 -> -2.0
2 -> -1.0
3 -> 0.0
4 -> 1.0
5 -> 2.0
6 -> 3.0) :: Vector 7 Double
ys = V.generate (\i ->
case i of
0 -> #y .== 3.1
1 -> #y .== 1.8
2 -> #y .== 1.1
3 -> #y .== (-0.2)
4 -> #y .== (-1.2)
5 -> #y .== (-2.1)
6 -> #y .== (-3.0)) :: Vector 7 (Rec ("y" .== Double))
-- prior
-- :: MonadInfer m
-- => P m ("noise" .== Log Double .+ "coeffs" .== [Rec ("c" .== Double)]) (Double -> Double, Log Double)
prior = do z <- sample #noise (gmma 1 1)
terms <- forRandomRange #coeffs (geom $ mkUnit 0.4) (\i -> do {
coeff <- sample #c (nrm 0 1);
return (\x -> coeff * (x ^ i))
})
let f = \x -> foldr (\t y -> y + (t x)) 0 terms
return (f, z)
-- p :: MonadInfer m
= > P m ( " noise " .== Log Double .+ " coeffs " .== [ Rec ( " c " .== Double ) ] .+ " data " .== Vector 7 ( Rec ( " y " .== Double ) ) ) ( Vector 7 Double )
p = do (f, z) <- prior
forEach #data xs (\x -> sample #y (nrm (f x) z))
data NNResult = NN { nnPi :: Unit, nnMu :: Double, nnSig :: Log Double, nnNoise :: Log Double }
data QState = Q { qN :: Int, qResids :: Vector 7 Double, qNN:: NNResult }
nn = undefined :: Vector 384 Double -> Vector 7 (Double, Double) -> NNResult
-- q :: MonadInfer m
-- => (Vector 384 Double, Log Double)
- > Rec ( " data " .== Vector 7 ( Rec ( " y " .== Double ) ) )
-- -> P m ("noise" .== Log Double .+ "coeffs" .== [Rec ("c" .== Double)]) (Log Double)
q (theta, sigma) obs =
do let ys = V.map (\d -> d .! #y) (obs .! #data)
let nnInputs n resids = V.zip (V.map (\x -> x^n) xs) resids
let initialState = Q { qN = 0, qResids = ys, qNN = nn theta (nnInputs 0 ys) }
finalState <- while #coeffs initialState (nnPi . qNN) (mkUnit 0.99) (\s -> do {
c <- sample #c $ nrm (nnMu (qNN s)) (nnSig (qNN s));
let newResids = V.map (\(x, y) -> y - c * (x ^ (qN s))) (V.zip xs (qResids s)) in
return (Q {qN = qN s + 1, qResids = newResids, qNN = nn theta (nnInputs (qN s + 1) newResids)})
})
sample #noise (lognormal (nnNoise (qNN finalState)) sigma)
-- sampleCurve = sampleIO $ runWeighted $ sampler $ traced p
-- j = trainAmortized p q
h = importance p ( # data .== ys ) prior
------------------------------
------------------------------
-- --
HIDDEN MARKOV MODEL SMC --
-- --
------------------------------
------------------------------
-- simple_hmm_init :: MonadInfer m => P m ("init" .== Double) Double
simple_hmm_init = sample #init (nrm 0 10)
simple_hmm_trans : : MonadInfer m = > Double - > P m ( " x " .== Double .+ " y " .== Double ) Double
simple_hmm_trans state = do
newState <- sample #x (nrm state 1)
noisyObs <- sample #y (nrm newState 0.2)
return newState
hmm_steps = [#y .== 3.2, #y .== 5.1, #y .== 6.8, #y .== 8.9, #y .== 10.3]
-- normalNormalPosterior :: MonadInfer m => (Double, Double) -> Double -> Double -> D m Double
normalNormalPosterior (mu1, sigma1) sigma2 obs =
let var = 1 / ((1 / sigma1^2) + (1 / sigma2^2))
mu = var * (mu1 / sigma1^2 + obs / sigma2^2)
in nrm mu (Exp (log var / 2))
-- hmm_proposal :: MonadInfer m => Rec ("y" .== Double) -> Double -> P m ("x" .== Double) Double
hmm_proposal o x = sample #x $ normalNormalPosterior (x, 1) 0.2 (o .! #y)
-- hmm_proposals :: MonadInfer m => [(Rec ("y" .== Double), Double -> P m ("x" .== Double) Double)]
hmm_proposals = fmap (\o -> (o, hmm_proposal o)) hmm_steps
-- hmm_init_proposal :: MonadInfer m => P m ("init" .== Double) Double
hmm_init_proposal = sample #init (nrm 0 10)
-- customInference :: Int -> IO (Log Double)
customInference n = sampleIO $ evidence $ smcMultinomial 5 n $
particleFilter simple_hmm_init hmm_init_proposal simple_hmm_trans hmm_proposals
| null | https://raw.githubusercontent.com/probcomp/haskell-trace-types/d7b209a61f31f6d77d3e285716abe1d96244e1ae/src/BasicExamples.hs | haskell | # LANGUAGE PartialTypeSignatures, NoMonomorphismRestriction #
-----------------------------
-----------------------------
--
Valid & Invalid Inference --
--
-----------------------------
-----------------------------
weight_model :: MonadInfer m => P m ("weight" .== Log Double .+ "measurement" .== Double) Double
Importance Sampling
q1 :: MonadInfer m => P m ("weight" .== Unit) Unit
appliedQ1 :: Type Error
appliedQ1 = importance weight_model obs q1
q1' :: MonadInfer m => P m ("weight" .== Log Double) (Log Double)
appliedQ1' :: MonadInfer m => m (Rec ("weight" .== Log Double))
k1 :: MonadInfer m => K m ("weight" .== Log Double) ("weight" .== Log Double)
k2 :: MonadInfer m => K m ("weight" .== Log Double) ("weight" .== Log Double)
shouldUseK1 :: Rec ("weight" .== Log Double) -> Bool
k :: Type Error
(ifK (not . shouldUseK1) k2)
k' :: MonadInfer m => K m ("weight" .== Log Double) ("weight" .== Log Double)
appliedK' :: MonadInfer m => Rec ("weight" .== Log Double) -> m (Rec ("weight" .== Log Double))
q2 :: MonadInfer m => (Double, Log Double) -> P m ("weight" .== Double) Double
appliedQ2 :: Type Error
appliedQ2' :: MonadInfer m => (Log Double, Log Double) -> m (Log Double, Log Double)
----------------------------
----------------------------
--
--
----------------------------
----------------------------
simple1 :: MonadInfer m => P m ("x" .== Double .+ "z" .== Double) Double
branch2
:: MonadInfer m
loop1 :: MonadInfer m => P m ("pts" .== [Rec ("x" .== Double .+ "y" .== Double)]) [Double]
loop2 :: MonadInfer m => P m ("pts" .== Vector 3 (Rec ("y" .== Double))) [Double]
----------------------------
----------------------------
--
End-to-End Example --
--
----------------------------
----------------------------
prior
:: MonadInfer m
=> P m ("noise" .== Log Double .+ "coeffs" .== [Rec ("c" .== Double)]) (Double -> Double, Log Double)
p :: MonadInfer m
q :: MonadInfer m
=> (Vector 384 Double, Log Double)
-> P m ("noise" .== Log Double .+ "coeffs" .== [Rec ("c" .== Double)]) (Log Double)
sampleCurve = sampleIO $ runWeighted $ sampler $ traced p
j = trainAmortized p q
----------------------------
----------------------------
--
--
----------------------------
----------------------------
simple_hmm_init :: MonadInfer m => P m ("init" .== Double) Double
normalNormalPosterior :: MonadInfer m => (Double, Double) -> Double -> Double -> D m Double
hmm_proposal :: MonadInfer m => Rec ("y" .== Double) -> Double -> P m ("x" .== Double) Double
hmm_proposals :: MonadInfer m => [(Rec ("y" .== Double), Double -> P m ("x" .== Double) Double)]
hmm_init_proposal :: MonadInfer m => P m ("init" .== Double) Double
customInference :: Int -> IO (Log Double) | # LANGUAGE DataKinds , GADTs , KindSignatures , TypeFamilies , TypeOperators , TypeApplications , ScopedTypeVariables , MultiParamTypeClasses , OverloadedLabels , InstanceSigs , FlexibleContexts , FlexibleInstances , RankNTypes , UndecidableInstances , ConstraintKinds , OverlappingInstances , TypeFamilyDependencies #
# LANGUAGE RebindableSyntax #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards , , ConstraintKinds #
module BasicExamples where
import TraceTypes
import Control.Monad.Bayes.Class
import Control.Monad.Bayes.Weighted (runWeighted)
import Control.Monad.Bayes.Sampler
import Data.Row.Records (Rec, (.==), type (.==), (.!), (.+), type (.+), Empty)
import Data.Row.Internal (LT(..), Row(..))
import qualified Data.Vector.Sized as V
import Data.Vector.Sized (Vector)
import Prelude hiding ((>>=), (>>), return)
import Numeric.Log
import Control.Monad.Bayes.Inference.SMC
import Control.Monad.Bayes.Population
import Control.Monad.Bayes.Sequential
f >>= g = pBind f g
return :: Monad m => a -> P m Empty a
return = pReturn
f >> g = f >>= \_ -> g
weight_model = do
w <- sample #weight (gmma 2 1)
sample #measurement (nrm (realToFrac w) 0.2)
obs = #measurement .== 0.5
q1 = sample #weight unif
q1' = sample #weight (gmma 2 0.25)
appliedQ1' = importance weight_model obs q1'
MCMC
k1 = mh (\t -> sample #weight (truncnrm (t .! #weight) 0.2))
k2 = mh (\t -> sample #weight (truncnrm (t .! #weight) 1.0))
shouldUseK1 t = t .! #weight <= 2
k = seqK ( ifK shouldUseK1 k1 )
k' = mh (\t -> let w = t .! #weight in
sample #weight (truncnrm w (if w < 2 then 0.2 else 1)))
appliedK' = k' (observe weight_model obs)
SVI
q2 (a, b) = sample #weight (nrm a b)
appliedQ2 = svi weight_model obs q2
q2 ' : : MonadInfer m = > ( Log Double , Log Double ) - > P m ( " weight " .== Log Double ) ( Log Double )
q2' (a, b) = sample #weight (truncnrm a b)
appliedQ2' = svi weight_model obs q2'
simple1 = do
x <- sample #x (nrm 0 1)
z <- sample #z (nrm x 1)
return $ x + z
simple2 : : MonadInfer m = > P m ( " x " .== Double .+ " z " .== Double ) Double
simple2 = do
z <- sample #z (nrm 0 1)
x <- sample #x (nrm z 1)
return $ x + z
: : MonadInfer m = > P m ( " b " .== Bool .+ " p " .== Unit .+ " coin " .== Bool ) Bool
branch1 = do
isBiased <- sample #b (brn $ mkUnit 0.1)
p <- if isBiased then
sample #p (bta 1 2)
else
sample #p (unif)
sample #coin (brn p)
= > P m ( " p " .== Either ( Rec ( " isLow " .== Bool ) ) ( Rec Empty ) .+ " coin " .== Bool ) Bool
branch2 = do
p <- withProbability #p (mkUnit 0.1) (do {
isLow <- sample #isLow (brn (mkUnit 0.5));
return (if isLow then (mkUnit 0.01) else (mkUnit 0.99))
}) (return $ mkUnit 0.5)
sample #coin (brn p)
loop1 = do
pts <- forRandomRange #pts (pois 3) (\i -> do {
x <- sample #x (nrm (fromIntegral i) 1);
sample #y (nrm x 1)
})
return $ map (\y -> 2 * y) pts
loop2 = do
pts <- forEach #pts (V.generate id :: Vector 3 Int) (\x -> do {
sample #y (nrm (fromIntegral x) 1)
})
return $ map (\y -> 2 * y) (V.toList pts)
xs = V.generate (\i ->
case i of
0 -> -3.0
1 -> -2.0
2 -> -1.0
3 -> 0.0
4 -> 1.0
5 -> 2.0
6 -> 3.0) :: Vector 7 Double
ys = V.generate (\i ->
case i of
0 -> #y .== 3.1
1 -> #y .== 1.8
2 -> #y .== 1.1
3 -> #y .== (-0.2)
4 -> #y .== (-1.2)
5 -> #y .== (-2.1)
6 -> #y .== (-3.0)) :: Vector 7 (Rec ("y" .== Double))
prior = do z <- sample #noise (gmma 1 1)
terms <- forRandomRange #coeffs (geom $ mkUnit 0.4) (\i -> do {
coeff <- sample #c (nrm 0 1);
return (\x -> coeff * (x ^ i))
})
let f = \x -> foldr (\t y -> y + (t x)) 0 terms
return (f, z)
= > P m ( " noise " .== Log Double .+ " coeffs " .== [ Rec ( " c " .== Double ) ] .+ " data " .== Vector 7 ( Rec ( " y " .== Double ) ) ) ( Vector 7 Double )
p = do (f, z) <- prior
forEach #data xs (\x -> sample #y (nrm (f x) z))
data NNResult = NN { nnPi :: Unit, nnMu :: Double, nnSig :: Log Double, nnNoise :: Log Double }
data QState = Q { qN :: Int, qResids :: Vector 7 Double, qNN:: NNResult }
nn = undefined :: Vector 384 Double -> Vector 7 (Double, Double) -> NNResult
- > Rec ( " data " .== Vector 7 ( Rec ( " y " .== Double ) ) )
q (theta, sigma) obs =
do let ys = V.map (\d -> d .! #y) (obs .! #data)
let nnInputs n resids = V.zip (V.map (\x -> x^n) xs) resids
let initialState = Q { qN = 0, qResids = ys, qNN = nn theta (nnInputs 0 ys) }
finalState <- while #coeffs initialState (nnPi . qNN) (mkUnit 0.99) (\s -> do {
c <- sample #c $ nrm (nnMu (qNN s)) (nnSig (qNN s));
let newResids = V.map (\(x, y) -> y - c * (x ^ (qN s))) (V.zip xs (qResids s)) in
return (Q {qN = qN s + 1, qResids = newResids, qNN = nn theta (nnInputs (qN s + 1) newResids)})
})
sample #noise (lognormal (nnNoise (qNN finalState)) sigma)
h = importance p ( # data .== ys ) prior
simple_hmm_init = sample #init (nrm 0 10)
simple_hmm_trans : : MonadInfer m = > Double - > P m ( " x " .== Double .+ " y " .== Double ) Double
simple_hmm_trans state = do
newState <- sample #x (nrm state 1)
noisyObs <- sample #y (nrm newState 0.2)
return newState
hmm_steps = [#y .== 3.2, #y .== 5.1, #y .== 6.8, #y .== 8.9, #y .== 10.3]
normalNormalPosterior (mu1, sigma1) sigma2 obs =
let var = 1 / ((1 / sigma1^2) + (1 / sigma2^2))
mu = var * (mu1 / sigma1^2 + obs / sigma2^2)
in nrm mu (Exp (log var / 2))
hmm_proposal o x = sample #x $ normalNormalPosterior (x, 1) 0.2 (o .! #y)
hmm_proposals = fmap (\o -> (o, hmm_proposal o)) hmm_steps
hmm_init_proposal = sample #init (nrm 0 10)
customInference n = sampleIO $ evidence $ smcMultinomial 5 n $
particleFilter simple_hmm_init hmm_init_proposal simple_hmm_trans hmm_proposals
|
a124b818e4b5475d1b2d8ec04bde23a1f31da417e9af4e7d0df9bdaa0d126522 | leftaroundabout/manifolds | PseudoAffine.hs | -- |
-- Module : Data.Manifold.PseudoAffine
Copyright : ( c ) 2015
-- License : GPL v3
--
-- Maintainer : (@) jsag $ hvl.no
-- Stability : experimental
-- Portability : portable
--
This is the second prototype of a manifold class . It appears to give considerable
-- advantages over 'Data.Manifold.Manifold', so that class will probably soon be replaced
-- with the one we define here (though 'PseudoAffine' does not follow the standard notion
-- of a manifold very closely, it should work quite equivalently for pretty much all
-- Haskell types that qualify as manifolds).
--
-- Manifolds are interesting as objects of various categories, from continuous to
-- diffeomorphic. At the moment, we mainly focus on /region-wise differentiable functions/,
-- which are a promising compromise between flexibility of definition and provability of
-- analytic properties. In particular, they are well-suited for visualisation purposes.
--
-- The classes in this module are mostly aimed at manifolds /without boundary/.
Manifolds with boundary ( which we call , never /manifold/ ! )
-- are more or less treated as a disjoint sum of the interior and the boundary.
To understand how this module works , best first forget about boundaries – in this case ,
@'Interior ' x ~ , ' fromInterior ' and ' toInterior ' are trivial , and
-- '.+~|', '|-~.' and 'betweenBounds' are irrelevant.
-- The manifold structure of the boundary itself is not considered at all here.
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
{-# LANGUAGE TypeFamilies #-}
# LANGUAGE FunctionalDependencies #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE LiberalTypeSynonyms #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TupleSections #
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DefaultSignatures #
# LANGUAGE PatternGuards #
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UnicodeSyntax #
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeApplications #
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE CPP #-}
module Data.Manifold.PseudoAffine (
-- * Manifold class
Manifold
, Semimanifold(..), Needle'
, PseudoAffine(..)
, LinearManifold, ScalarManifold
, Num', RealFrac', RealFloat'
, Num'', RealFrac'', RealFloat''
-- * Type definitions
-- ** Needles
, Local(..)
#if !MIN_VERSION_manifolds_core(0,6,0)
, (!+~^)
#endif
-- ** Metrics
, Metric, Metric'
, RieMetric, RieMetric'
-- ** Constraints
, SemimanifoldWitness(..)
, PseudoAffineWitness(..)
, DualNeedleWitness
, WithField
, LocallyScalable
-- ** Local functions
, LocalLinear, LocalBilinear, LocalAffine
-- * Misc
, alerpB, palerp, palerpB, LocallyCoercible(..), CanonicalDiffeomorphism(..)
, ImpliesMetric(..), coerceMetric, coerceMetric'
, Connected (..)
) where
import Math.Manifold.Core.PseudoAffine
import Data.Manifold.WithBoundary.Class
import Data.Maybe
import Data.Fixed
import Data.VectorSpace
import Linear.V0
import Linear.V1
import Linear.V2
import Linear.V3
import Linear.V4
import qualified Linear.Affine as LinAff
import Data.Embedding
import Data.LinearMap
import Data.VectorSpace.Free
import Math.LinearMap.Category
import Data.AffineSpace
import Data.Tagged
import Data.Manifold.Types.Primitive
import qualified Prelude as Hask
import qualified Control.Applicative as Hask
import Control.Category.Constrained.Prelude hiding ((^))
import Control.Arrow.Constrained
import Control.Monad.Constrained
import Data.Foldable.Constrained
import Control.Lens (Lens', lens, (^.), (&), (%~), (.~))
import Data.CallStack (HasCallStack)
import GHC.Exts (Constraint)
-- | See 'Semimanifold' and 'PseudoAffine' for the methods.
-- As a 'Manifold' we understand a pseudo-affine space whose 'Needle'
-- space is a well-behaved vector space that is isomorphic to
-- all of the manifold's tangent spaces.
-- It must also be an instance of the 'SemimanifoldWithBoundary' class
-- with explicitly empty boundary (in other words, with /no/ boundary).
class (OpenManifold m, ProjectableBoundary m, LSpace (Needle m))
=> Manifold m where
instance (OpenManifold m, ProjectableBoundary m, LSpace (Needle m))
=> Manifold m
-- | Instances of this class must be diffeomorphic manifolds, and even have
-- /canonically isomorphic/ tangent spaces, so that
@'fromPackedVector ' . ' ' : : ' Needle ' x - > ' Needle ' ξ@
-- defines a meaningful “representational identity“ between these spaces.
class ( Semimanifold x, Semimanifold ξ, LSpace (Needle x), LSpace (Needle ξ)
, Scalar (Needle x) ~ Scalar (Needle ξ) )
=> LocallyCoercible x ξ where
-- | Must be compatible with the isomorphism on the tangent spaces, i.e.
-- @
locallyTrivialDiffeomorphism ( p .+~^ v )
-- ≡ locallyTrivialDiffeomorphism p .+~^ 'coerceNeedle' v
-- @
locallyTrivialDiffeomorphism :: x -> ξ
coerceNeedle :: Hask.Functor p => p (x,ξ) -> (Needle x -+> Needle ξ)
coerceNeedle' :: Hask.Functor p => p (x,ξ) -> (Needle' x -+> Needle' ξ)
coerceNorm :: Hask.Functor p => p (x,ξ) -> Metric x -> Metric ξ
coerceNorm p = case ( oppositeLocalCoercion :: CanonicalDiffeomorphism ξ x
, dualSpaceWitness :: DualSpaceWitness (Needle x)
, dualSpaceWitness :: DualSpaceWitness (Needle ξ) ) of
(CanonicalDiffeomorphism, DualSpaceWitness, DualSpaceWitness)
-> case ( coerceNeedle (swap<$>p), coerceNeedle' p ) of
(f, f') -> \(Norm n) -> Norm $ f' . n . f
coerceVariance :: Hask.Functor p => p (x,ξ) -> Metric' x -> Metric' ξ
coerceVariance p = case ( oppositeLocalCoercion :: CanonicalDiffeomorphism ξ x
, dualSpaceWitness :: DualSpaceWitness (Needle x)
, dualSpaceWitness :: DualSpaceWitness (Needle ξ) ) of
(CanonicalDiffeomorphism, DualSpaceWitness, DualSpaceWitness)
-> case ( coerceNeedle p, coerceNeedle' (swap<$>p) ) of
(f, f') -> \(Norm n) -> Norm $ f . n . f'
oppositeLocalCoercion :: CanonicalDiffeomorphism ξ x
default oppositeLocalCoercion :: LocallyCoercible ξ x => CanonicalDiffeomorphism ξ x
oppositeLocalCoercion = CanonicalDiffeomorphism
type NumPrime n = (Num' n, Eq n)
#define identityCoercion(c,t) \
instance (c) => LocallyCoercible (t) (t) where { \
locallyTrivialDiffeomorphism = id; \
coerceNeedle _ = id; \
coerceNeedle' _ = id; \
oppositeLocalCoercion = CanonicalDiffeomorphism }
identityCoercion(NumPrime s, ZeroDim s)
identityCoercion(NumPrime s, V0 s)
identityCoercion((), ℝ)
identityCoercion(NumPrime s, V1 s)
identityCoercion((), (ℝ,ℝ))
identityCoercion(NumPrime s, V2 s)
identityCoercion((), (ℝ,(ℝ,ℝ)))
identityCoercion((), ((ℝ,ℝ),ℝ))
identityCoercion(NumPrime s, V3 s)
identityCoercion(NumPrime s, V4 s)
data CanonicalDiffeomorphism a b where
CanonicalDiffeomorphism :: LocallyCoercible a b => CanonicalDiffeomorphism a b
-- | A point on a manifold, as seen from a nearby reference point.
newtype Local x = Local { getLocalOffset :: Needle x }
deriving instance (Show (Needle x)) => Show (Local x)
type LocallyScalable s x = ( PseudoAffine x
, LSpace (Needle x)
, s ~ Scalar (Needle x)
, s ~ Scalar (Needle' x)
, Num' s )
type LocalLinear x y = LinearMap (Scalar (Needle x)) (Needle x) (Needle y)
type LocalBilinear x y = LinearMap (Scalar (Needle x))
(SymmetricTensor (Scalar (Needle x)) (Needle x))
(Needle y)
type LocalAffine x y = (Needle y, LocalLinear x y)
-- | Require some constraint on a manifold, and also fix the type of the manifold's
underlying field . For example , @WithField & # x211d ; ' HilbertManifold ' v@ constrains
@v@ to be a real ( i.e. , ' ) space .
-- Note that for this to compile, you will in
general need the extension ( except if the constraint
-- is an actual type class (like 'Manifold'): only those can always be partially
-- applied, for @type@ constraints this is by default not allowed).
type WithField s c x = ( c x, s ~ Scalar (Needle x), s ~ Scalar (Needle' x) )
-- | A co-needle can be understood as a “paper stack”, with which you can measure
-- the length that a needle reaches in a given direction by counting the number
-- of holes punched through them.
type Needle' x = DualVector (Needle x)
-- | The word “metric” is used in the sense as in general relativity.
-- Actually this is just the type of scalar products on the tangent space.
-- The actual metric is the function @x -> x -> Scalar (Needle x)@ defined by
--
-- @
-- \\p q -> m '|$|' (p.-~!q)
-- @
type Metric x = Norm (Needle x)
type Metric' x = Variance (Needle x)
| A Riemannian metric assigns each point on a manifold a scalar product on the tangent space .
Note that this association is /not/ continuous , because the charts / tangent spaces in the bundle
are a priori disjoint . However , for a proper Riemannian metric , all arising expressions
-- of scalar products from needles between points on the manifold ought to be differentiable.
type RieMetric x = x -> Metric x
type RieMetric' x = x -> Metric' x
coerceMetric :: ∀ x ξ . (LocallyCoercible x ξ, LSpace (Needle ξ))
=> RieMetric ξ -> RieMetric x
coerceMetric = case ( dualSpaceWitness :: DualNeedleWitness x
, dualSpaceWitness :: DualNeedleWitness ξ ) of
(DualSpaceWitness, DualSpaceWitness)
-> \m x -> case m $ locallyTrivialDiffeomorphism x of
Norm sc -> Norm $ bw . sc . fw
where fw = coerceNeedle ([]::[(x,ξ)])
bw = case oppositeLocalCoercion :: CanonicalDiffeomorphism ξ x of
CanonicalDiffeomorphism -> coerceNeedle' ([]::[(ξ,x)])
coerceMetric' :: ∀ x ξ . (LocallyCoercible x ξ, LSpace (Needle ξ))
=> RieMetric' ξ -> RieMetric' x
coerceMetric' = case ( dualSpaceWitness :: DualNeedleWitness x
, dualSpaceWitness :: DualNeedleWitness ξ ) of
(DualSpaceWitness, DualSpaceWitness)
-> \m x -> case m $ locallyTrivialDiffeomorphism x of
Norm sc -> Norm $ bw . sc . fw
where fw = coerceNeedle' ([]::[(x,ξ)])
bw = case oppositeLocalCoercion :: CanonicalDiffeomorphism ξ x of
CanonicalDiffeomorphism -> coerceNeedle ([]::[(ξ,x)])
hugeℝVal :: ℝ
hugeℝVal = 1e+100
#define deriveAffine(c,t) \
instance (c) => Semimanifold (t) where { \
type Needle (t) = Diff (t); \
fromInterior = id; \
toInterior = pure; \
translateP = Tagged (.+^); \
(.+~^) = (.+^) }; \
instance (c) => PseudoAffine (t) where { \
a.-~.b = pure (a.-.b); }
instance (NumPrime s) => LocallyCoercible (ZeroDim s) (V0 s) where
locallyTrivialDiffeomorphism Origin = V0
coerceNeedle _ = LinearFunction $ \Origin -> V0
coerceNeedle' _ = LinearFunction $ \Origin -> V0
instance (NumPrime s) => LocallyCoercible (V0 s) (ZeroDim s) where
locallyTrivialDiffeomorphism V0 = Origin
coerceNeedle _ = LinearFunction $ \V0 -> Origin
coerceNeedle' _ = LinearFunction $ \V0 -> Origin
instance LocallyCoercible ℝ (V1 ℝ) where
locallyTrivialDiffeomorphism = V1
coerceNeedle _ = LinearFunction V1
coerceNeedle' _ = LinearFunction V1
instance LocallyCoercible (V1 ℝ) ℝ where
locallyTrivialDiffeomorphism (V1 n) = n
coerceNeedle _ = LinearFunction $ \(V1 n) -> n
coerceNeedle' _ = LinearFunction $ \(V1 n) -> n
instance LocallyCoercible (ℝ,ℝ) (V2 ℝ) where
locallyTrivialDiffeomorphism = uncurry V2
coerceNeedle _ = LinearFunction $ uncurry V2
coerceNeedle' _ = LinearFunction $ uncurry V2
instance LocallyCoercible (V2 ℝ) (ℝ,ℝ) where
locallyTrivialDiffeomorphism (V2 x y) = (x,y)
coerceNeedle _ = LinearFunction $ \(V2 x y) -> (x,y)
coerceNeedle' _ = LinearFunction $ \(V2 x y) -> (x,y)
instance LocallyCoercible ((ℝ,ℝ),ℝ) (V3 ℝ) where
locallyTrivialDiffeomorphism ((x,y),z) = V3 x y z
coerceNeedle _ = LinearFunction $ \((x,y),z) -> V3 x y z
coerceNeedle' _ = LinearFunction $ \((x,y),z) -> V3 x y z
instance LocallyCoercible (ℝ,(ℝ,ℝ)) (V3 ℝ) where
locallyTrivialDiffeomorphism (x,(y,z)) = V3 x y z
coerceNeedle _ = LinearFunction $ \(x,(y,z)) -> V3 x y z
coerceNeedle' _ = LinearFunction $ \(x,(y,z)) -> V3 x y z
instance LocallyCoercible (V3 ℝ) ((ℝ,ℝ),ℝ) where
locallyTrivialDiffeomorphism (V3 x y z) = ((x,y),z)
coerceNeedle _ = LinearFunction $ \(V3 x y z) -> ((x,y),z)
coerceNeedle' _ = LinearFunction $ \(V3 x y z) -> ((x,y),z)
instance LocallyCoercible (V3 ℝ) (ℝ,(ℝ,ℝ)) where
locallyTrivialDiffeomorphism (V3 x y z) = (x,(y,z))
coerceNeedle _ = LinearFunction $ \(V3 x y z) -> (x,(y,z))
coerceNeedle' _ = LinearFunction $ \(V3 x y z) -> (x,(y,z))
instance LocallyCoercible ((ℝ,ℝ),(ℝ,ℝ)) (V4 ℝ) where
locallyTrivialDiffeomorphism ((x,y),(z,w)) = V4 x y z w
coerceNeedle _ = LinearFunction $ \((x,y),(z,w)) -> V4 x y z w
coerceNeedle' _ = LinearFunction $ \((x,y),(z,w)) -> V4 x y z w
instance LocallyCoercible (V4 ℝ) ((ℝ,ℝ),(ℝ,ℝ)) where
locallyTrivialDiffeomorphism (V4 x y z w) = ((x,y),(z,w))
coerceNeedle _ = LinearFunction $ \(V4 x y z w) -> ((x,y),(z,w))
coerceNeedle' _ = LinearFunction $ \(V4 x y z w) -> ((x,y),(z,w))
instance ∀ a b c .
( Semimanifold a, Semimanifold b, Semimanifold c
, LSpace (Needle a), LSpace (Needle b), LSpace (Needle c)
, Scalar (Needle a) ~ Scalar (Needle b), Scalar (Needle b) ~ Scalar (Needle c)
)
=> LocallyCoercible (a,(b,c)) ((a,b),c) where
locallyTrivialDiffeomorphism = regroup
coerceNeedle _ = regroup
coerceNeedle' _ = case ( dualSpaceWitness @(Needle a)
, dualSpaceWitness @(Needle b)
, dualSpaceWitness @(Needle c) ) of
(DualSpaceWitness, DualSpaceWitness, DualSpaceWitness) -> regroup
oppositeLocalCoercion = CanonicalDiffeomorphism
instance ∀ a b c .
( Semimanifold a, Semimanifold b, Semimanifold c
, LSpace (Needle a), LSpace (Needle b), LSpace (Needle c)
, Scalar (Needle a) ~ Scalar (Needle b), Scalar (Needle b) ~ Scalar (Needle c)
)
=> LocallyCoercible ((a,b),c) (a,(b,c)) where
locallyTrivialDiffeomorphism = regroup'
coerceNeedle _ = regroup'
coerceNeedle' _ = case ( dualSpaceWitness @(Needle a)
, dualSpaceWitness @(Needle b)
, dualSpaceWitness @(Needle c) ) of
(DualSpaceWitness, DualSpaceWitness, DualSpaceWitness) -> regroup'
oppositeLocalCoercion = CanonicalDiffeomorphism
instance (LinearSpace (a n), Needle (a n) ~ a n)
=> Semimanifold (LinAff.Point a n) where
type Needle (LinAff.Point a n) = a n
LinAff.P v .+~^ w = LinAff.P $ v ^+^ w
instance (LinearSpace (a n), Needle (a n) ~ a n)
=> PseudoAffine (LinAff.Point a n) where
LinAff.P v .-~. LinAff.P w = return $ v ^-^ w
LinAff.P v .-~! LinAff.P w = v ^-^ w
instance RealFloat' r => Semimanifold (S⁰_ r) where
type Needle (S⁰_ r) = ZeroDim r
p .+~^ Origin = p
p .-~^ Origin = p
instance RealFloat' r => PseudoAffine (S⁰_ r) where
PositiveHalfSphere .-~. PositiveHalfSphere = pure Origin
NegativeHalfSphere .-~. NegativeHalfSphere = pure Origin
_ .-~. _ = Nothing
PositiveHalfSphere .-~! PositiveHalfSphere = Origin
NegativeHalfSphere .-~! NegativeHalfSphere = Origin
_ .-~! _ = error "There is no path between the two 0-dimensional half spheres."
instance RealFloat' r => Semimanifold (S¹_ r) where
type Needle (S¹_ r) = r
S¹Polar φ₀ .+~^ δφ = S¹Polar $ φ'
where φ' = toS¹range $ φ₀ + δφ
semimanifoldWitness = case linearManifoldWitness @r of
LinearManifoldWitness -> SemimanifoldWitness
instance RealFloat' r => PseudoAffine (S¹_ r) where
p .-~. q = pure (p.-~!q)
S¹Polar φ₁ .-~! S¹Polar φ₀
| δφ > pi = δφ - tau
| δφ < (-pi) = δφ + tau
| otherwise = δφ
where δφ = φ₁ - φ₀
instance RealFloat' s => Semimanifold (S²_ s) where
type Needle (S²_ s) = V2 s
(.+~^) = case linearManifoldWitness @s of
LinearManifoldWitness ->
let addS² (S²Polar θ₀ φ₀) 𝐯 = S²Polar θ₁ φ₁
where -- See images/constructions/sphericoords-needles.svg.
S¹Polar γc = coEmbed 𝐯
γ | θ₀ < pi/2 = γc - φ₀
| otherwise = γc + φ₀
d = magnitude 𝐯
S¹Polar φ₁ = S¹Polar φ₀ .+~^ δφ
Cartesian coordinates of p₁ in the system whose north pole is p₀
with φ₀ as the zero meridian
V3 bx by bz = embed $ S²Polar d γ
sθ₀ = sin θ₀; cθ₀ = cos θ₀
Cartesian coordinates of p₁ in the system with the standard north pole ,
but still φ₀ as the zero meridian
(qx,qz) = ( cθ₀ * bx + sθ₀ * bz
,-sθ₀ * bx + cθ₀ * bz )
qy = by
S²Polar θ₁ δφ = coEmbed $ V3 qx qy qz
in addS²
instance RealFloat' s => PseudoAffine (S²_ s) where
p.-~.q = pure (p.-~!q)
S²Polar θ₁ φ₁ .-~! S²Polar θ₀ φ₀ = d *^ embed(S¹Polar γc)
where -- See images/constructions/sphericoords-needles.svg.
V3 qx qy qz = embed $ S²Polar θ₁ (φ₁-φ₀)
sθ₀ = sin θ₀; cθ₀ = cos θ₀
(bx,bz) = ( cθ₀ * qx - sθ₀ * qz
, sθ₀ * qx + cθ₀ * qz )
by = qy
S²Polar d γ = coEmbed $ V3 bx by bz
γc | θ₀ < pi/2 = γ + φ₀
| otherwise = γ - φ₀
instance Semimanifold ℝP² where
type Needle ℝP² = ℝ²
HemisphereℝP²Polar θ₀ φ₀ .+~^ v
= case S²Polar θ₀ φ₀ .+~^ v of
S²Polar θ₁ φ₁
| θ₁ > pi/2 -> HemisphereℝP²Polar (pi-θ₁) (-φ₁)
| otherwise -> HemisphereℝP²Polar θ₁ φ₁
instance PseudoAffine ℝP² where
p.-~.q = pure (p.-~!q)
HemisphereℝP²Polar θ₁ φ₁ .-~! HemisphereℝP²Polar θ₀ φ₀
= case S²Polar θ₁ φ₁ .-~! S²Polar θ₀ φ₀ of
v -> let r² = magnitudeSq v
in if r²>pi^2/4
then S²Polar (pi-θ₁) (-φ₁) .-~! S²Polar θ₀ φ₀
else v
instance ( PseudoAffine m , ( Needle m ) , Scalar ( Needle m ) ~ ℝ )
= > ( CD¹ m ) where
-- type Needle (CD¹ m) = (Needle m, ℝ)
-- CD¹ h₀ m₀ .+~^ (h₁δm, δh)
-- = let h₁ = min 1 . max 1e-300 $ h₀+δh; δm = h₁δm^/h₁
-- in CD¹ h₁ (m₀.+~^δm)
instance ( PseudoAffine m , ( Needle m ) , Scalar ( Needle m ) ~ ℝ )
-- => PseudoAffine (CD¹ m) where
-- CD¹ h₁ m₁ .-~. CD¹ h₀ m₀
-- = fmap ( \δm -> (h₁*^δm, h₁-h₀) ) $ m₁.-~.m₀
class ImpliesMetric s where
type MetricRequirement s x :: Constraint
type MetricRequirement s x = Semimanifold x
inferMetric :: (MetricRequirement s x, LSpace (Needle x))
=> s x -> Metric x
inferMetric' :: (MetricRequirement s x, LSpace (Needle x))
=> s x -> Metric' x
instance ImpliesMetric Norm where
type MetricRequirement Norm x = (SimpleSpace x, x ~ Needle x)
inferMetric = id
inferMetric' = dualNorm
type DualNeedleWitness x = DualSpaceWitness (Needle x)
#if !MIN_VERSION_manifolds_core(0,6,0)
infixl 6 !+~^
-- | Boundary-unsafe version of `.+~^`.
(!+~^) :: ∀ x . (Semimanifold x, HasCallStack) => x -> Needle x -> x
p!+~^v = case toInterior p of
Just p' -> p'.+~^v
#endif
infix 6 .−.
-- | A connected manifold is one where any point can be reached by translation from
-- any other point.
class (PseudoAffine m) => Connected m where
# MINIMAL #
-- | Safe version of '(.-~.)'.
(.−.) :: m -> m -> Needle m
(.−.) = (.-~!)
instance Connected ℝ⁰
instance Connected ℝ
instance Connected ℝ¹
instance Connected ℝ²
instance Connected ℝ³
instance Connected ℝ⁴
instance Connected S¹
instance Connected S²
instance Connected ℝP⁰
instance Connected ℝP¹
instance Connected ℝP²
instance (Connected x, Connected y) => Connected (x,y)
instance (Connected x, Connected y, PseudoAffine (FibreBundle x y))
=> Connected (FibreBundle x y)
type LinearManifold m = (LinearSpace m, Manifold m)
type ScalarManifold s = (Num' s, Manifold s, Manifold (ZeroDim s))
type Num'' s = ScalarManifold s
type RealFrac'' s = (RealFrac' s, ScalarManifold s)
type RealFloat'' s = (RealFloat' s, SimpleSpace s, ScalarManifold s)
| null | https://raw.githubusercontent.com/leftaroundabout/manifolds/4bcf39ee970cf437458dadc8f9b0dc66d2ae09ed/manifolds/Data/Manifold/PseudoAffine.hs | haskell | |
Module : Data.Manifold.PseudoAffine
License : GPL v3
Maintainer : (@) jsag $ hvl.no
Stability : experimental
Portability : portable
advantages over 'Data.Manifold.Manifold', so that class will probably soon be replaced
with the one we define here (though 'PseudoAffine' does not follow the standard notion
of a manifold very closely, it should work quite equivalently for pretty much all
Haskell types that qualify as manifolds).
Manifolds are interesting as objects of various categories, from continuous to
diffeomorphic. At the moment, we mainly focus on /region-wise differentiable functions/,
which are a promising compromise between flexibility of definition and provability of
analytic properties. In particular, they are well-suited for visualisation purposes.
The classes in this module are mostly aimed at manifolds /without boundary/.
are more or less treated as a disjoint sum of the interior and the boundary.
'.+~|', '|-~.' and 'betweenBounds' are irrelevant.
The manifold structure of the boundary itself is not considered at all here.
# LANGUAGE TypeFamilies #
# LANGUAGE LiberalTypeSynonyms #
# LANGUAGE DataKinds #
# LANGUAGE GADTs #
# LANGUAGE StandaloneDeriving #
# LANGUAGE RankNTypes #
# LANGUAGE ConstraintKinds #
# LANGUAGE TypeOperators #
# LANGUAGE MultiWayIf #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE RecordWildCards #
# LANGUAGE CPP #
* Manifold class
* Type definitions
** Needles
** Metrics
** Constraints
** Local functions
* Misc
| See 'Semimanifold' and 'PseudoAffine' for the methods.
As a 'Manifold' we understand a pseudo-affine space whose 'Needle'
space is a well-behaved vector space that is isomorphic to
all of the manifold's tangent spaces.
It must also be an instance of the 'SemimanifoldWithBoundary' class
with explicitly empty boundary (in other words, with /no/ boundary).
| Instances of this class must be diffeomorphic manifolds, and even have
/canonically isomorphic/ tangent spaces, so that
defines a meaningful “representational identity“ between these spaces.
| Must be compatible with the isomorphism on the tangent spaces, i.e.
@
≡ locallyTrivialDiffeomorphism p .+~^ 'coerceNeedle' v
@
| A point on a manifold, as seen from a nearby reference point.
| Require some constraint on a manifold, and also fix the type of the manifold's
Note that for this to compile, you will in
is an actual type class (like 'Manifold'): only those can always be partially
applied, for @type@ constraints this is by default not allowed).
| A co-needle can be understood as a “paper stack”, with which you can measure
the length that a needle reaches in a given direction by counting the number
of holes punched through them.
| The word “metric” is used in the sense as in general relativity.
Actually this is just the type of scalar products on the tangent space.
The actual metric is the function @x -> x -> Scalar (Needle x)@ defined by
@
\\p q -> m '|$|' (p.-~!q)
@
of scalar products from needles between points on the manifold ought to be differentiable.
See images/constructions/sphericoords-needles.svg.
See images/constructions/sphericoords-needles.svg.
type Needle (CD¹ m) = (Needle m, ℝ)
CD¹ h₀ m₀ .+~^ (h₁δm, δh)
= let h₁ = min 1 . max 1e-300 $ h₀+δh; δm = h₁δm^/h₁
in CD¹ h₁ (m₀.+~^δm)
=> PseudoAffine (CD¹ m) where
CD¹ h₁ m₁ .-~. CD¹ h₀ m₀
= fmap ( \δm -> (h₁*^δm, h₁-h₀) ) $ m₁.-~.m₀
| Boundary-unsafe version of `.+~^`.
| A connected manifold is one where any point can be reached by translation from
any other point.
| Safe version of '(.-~.)'. | Copyright : ( c ) 2015
This is the second prototype of a manifold class . It appears to give considerable
Manifolds with boundary ( which we call , never /manifold/ ! )
To understand how this module works , best first forget about boundaries – in this case ,
@'Interior ' x ~ , ' fromInterior ' and ' toInterior ' are trivial , and
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE FlexibleContexts #
# LANGUAGE TupleSections #
# LANGUAGE DefaultSignatures #
# LANGUAGE PatternGuards #
# LANGUAGE UnicodeSyntax #
# LANGUAGE TypeApplications #
module Data.Manifold.PseudoAffine (
Manifold
, Semimanifold(..), Needle'
, PseudoAffine(..)
, LinearManifold, ScalarManifold
, Num', RealFrac', RealFloat'
, Num'', RealFrac'', RealFloat''
, Local(..)
#if !MIN_VERSION_manifolds_core(0,6,0)
, (!+~^)
#endif
, Metric, Metric'
, RieMetric, RieMetric'
, SemimanifoldWitness(..)
, PseudoAffineWitness(..)
, DualNeedleWitness
, WithField
, LocallyScalable
, LocalLinear, LocalBilinear, LocalAffine
, alerpB, palerp, palerpB, LocallyCoercible(..), CanonicalDiffeomorphism(..)
, ImpliesMetric(..), coerceMetric, coerceMetric'
, Connected (..)
) where
import Math.Manifold.Core.PseudoAffine
import Data.Manifold.WithBoundary.Class
import Data.Maybe
import Data.Fixed
import Data.VectorSpace
import Linear.V0
import Linear.V1
import Linear.V2
import Linear.V3
import Linear.V4
import qualified Linear.Affine as LinAff
import Data.Embedding
import Data.LinearMap
import Data.VectorSpace.Free
import Math.LinearMap.Category
import Data.AffineSpace
import Data.Tagged
import Data.Manifold.Types.Primitive
import qualified Prelude as Hask
import qualified Control.Applicative as Hask
import Control.Category.Constrained.Prelude hiding ((^))
import Control.Arrow.Constrained
import Control.Monad.Constrained
import Data.Foldable.Constrained
import Control.Lens (Lens', lens, (^.), (&), (%~), (.~))
import Data.CallStack (HasCallStack)
import GHC.Exts (Constraint)
class (OpenManifold m, ProjectableBoundary m, LSpace (Needle m))
=> Manifold m where
instance (OpenManifold m, ProjectableBoundary m, LSpace (Needle m))
=> Manifold m
@'fromPackedVector ' . ' ' : : ' Needle ' x - > ' Needle ' ξ@
class ( Semimanifold x, Semimanifold ξ, LSpace (Needle x), LSpace (Needle ξ)
, Scalar (Needle x) ~ Scalar (Needle ξ) )
=> LocallyCoercible x ξ where
locallyTrivialDiffeomorphism ( p .+~^ v )
locallyTrivialDiffeomorphism :: x -> ξ
coerceNeedle :: Hask.Functor p => p (x,ξ) -> (Needle x -+> Needle ξ)
coerceNeedle' :: Hask.Functor p => p (x,ξ) -> (Needle' x -+> Needle' ξ)
coerceNorm :: Hask.Functor p => p (x,ξ) -> Metric x -> Metric ξ
coerceNorm p = case ( oppositeLocalCoercion :: CanonicalDiffeomorphism ξ x
, dualSpaceWitness :: DualSpaceWitness (Needle x)
, dualSpaceWitness :: DualSpaceWitness (Needle ξ) ) of
(CanonicalDiffeomorphism, DualSpaceWitness, DualSpaceWitness)
-> case ( coerceNeedle (swap<$>p), coerceNeedle' p ) of
(f, f') -> \(Norm n) -> Norm $ f' . n . f
coerceVariance :: Hask.Functor p => p (x,ξ) -> Metric' x -> Metric' ξ
coerceVariance p = case ( oppositeLocalCoercion :: CanonicalDiffeomorphism ξ x
, dualSpaceWitness :: DualSpaceWitness (Needle x)
, dualSpaceWitness :: DualSpaceWitness (Needle ξ) ) of
(CanonicalDiffeomorphism, DualSpaceWitness, DualSpaceWitness)
-> case ( coerceNeedle p, coerceNeedle' (swap<$>p) ) of
(f, f') -> \(Norm n) -> Norm $ f . n . f'
oppositeLocalCoercion :: CanonicalDiffeomorphism ξ x
default oppositeLocalCoercion :: LocallyCoercible ξ x => CanonicalDiffeomorphism ξ x
oppositeLocalCoercion = CanonicalDiffeomorphism
type NumPrime n = (Num' n, Eq n)
#define identityCoercion(c,t) \
instance (c) => LocallyCoercible (t) (t) where { \
locallyTrivialDiffeomorphism = id; \
coerceNeedle _ = id; \
coerceNeedle' _ = id; \
oppositeLocalCoercion = CanonicalDiffeomorphism }
identityCoercion(NumPrime s, ZeroDim s)
identityCoercion(NumPrime s, V0 s)
identityCoercion((), ℝ)
identityCoercion(NumPrime s, V1 s)
identityCoercion((), (ℝ,ℝ))
identityCoercion(NumPrime s, V2 s)
identityCoercion((), (ℝ,(ℝ,ℝ)))
identityCoercion((), ((ℝ,ℝ),ℝ))
identityCoercion(NumPrime s, V3 s)
identityCoercion(NumPrime s, V4 s)
data CanonicalDiffeomorphism a b where
CanonicalDiffeomorphism :: LocallyCoercible a b => CanonicalDiffeomorphism a b
newtype Local x = Local { getLocalOffset :: Needle x }
deriving instance (Show (Needle x)) => Show (Local x)
type LocallyScalable s x = ( PseudoAffine x
, LSpace (Needle x)
, s ~ Scalar (Needle x)
, s ~ Scalar (Needle' x)
, Num' s )
type LocalLinear x y = LinearMap (Scalar (Needle x)) (Needle x) (Needle y)
type LocalBilinear x y = LinearMap (Scalar (Needle x))
(SymmetricTensor (Scalar (Needle x)) (Needle x))
(Needle y)
type LocalAffine x y = (Needle y, LocalLinear x y)
underlying field . For example , @WithField & # x211d ; ' HilbertManifold ' v@ constrains
@v@ to be a real ( i.e. , ' ) space .
general need the extension ( except if the constraint
type WithField s c x = ( c x, s ~ Scalar (Needle x), s ~ Scalar (Needle' x) )
type Needle' x = DualVector (Needle x)
type Metric x = Norm (Needle x)
type Metric' x = Variance (Needle x)
| A Riemannian metric assigns each point on a manifold a scalar product on the tangent space .
Note that this association is /not/ continuous , because the charts / tangent spaces in the bundle
are a priori disjoint . However , for a proper Riemannian metric , all arising expressions
type RieMetric x = x -> Metric x
type RieMetric' x = x -> Metric' x
coerceMetric :: ∀ x ξ . (LocallyCoercible x ξ, LSpace (Needle ξ))
=> RieMetric ξ -> RieMetric x
coerceMetric = case ( dualSpaceWitness :: DualNeedleWitness x
, dualSpaceWitness :: DualNeedleWitness ξ ) of
(DualSpaceWitness, DualSpaceWitness)
-> \m x -> case m $ locallyTrivialDiffeomorphism x of
Norm sc -> Norm $ bw . sc . fw
where fw = coerceNeedle ([]::[(x,ξ)])
bw = case oppositeLocalCoercion :: CanonicalDiffeomorphism ξ x of
CanonicalDiffeomorphism -> coerceNeedle' ([]::[(ξ,x)])
coerceMetric' :: ∀ x ξ . (LocallyCoercible x ξ, LSpace (Needle ξ))
=> RieMetric' ξ -> RieMetric' x
coerceMetric' = case ( dualSpaceWitness :: DualNeedleWitness x
, dualSpaceWitness :: DualNeedleWitness ξ ) of
(DualSpaceWitness, DualSpaceWitness)
-> \m x -> case m $ locallyTrivialDiffeomorphism x of
Norm sc -> Norm $ bw . sc . fw
where fw = coerceNeedle' ([]::[(x,ξ)])
bw = case oppositeLocalCoercion :: CanonicalDiffeomorphism ξ x of
CanonicalDiffeomorphism -> coerceNeedle ([]::[(ξ,x)])
hugeℝVal :: ℝ
hugeℝVal = 1e+100
#define deriveAffine(c,t) \
instance (c) => Semimanifold (t) where { \
type Needle (t) = Diff (t); \
fromInterior = id; \
toInterior = pure; \
translateP = Tagged (.+^); \
(.+~^) = (.+^) }; \
instance (c) => PseudoAffine (t) where { \
a.-~.b = pure (a.-.b); }
instance (NumPrime s) => LocallyCoercible (ZeroDim s) (V0 s) where
locallyTrivialDiffeomorphism Origin = V0
coerceNeedle _ = LinearFunction $ \Origin -> V0
coerceNeedle' _ = LinearFunction $ \Origin -> V0
instance (NumPrime s) => LocallyCoercible (V0 s) (ZeroDim s) where
locallyTrivialDiffeomorphism V0 = Origin
coerceNeedle _ = LinearFunction $ \V0 -> Origin
coerceNeedle' _ = LinearFunction $ \V0 -> Origin
instance LocallyCoercible ℝ (V1 ℝ) where
locallyTrivialDiffeomorphism = V1
coerceNeedle _ = LinearFunction V1
coerceNeedle' _ = LinearFunction V1
instance LocallyCoercible (V1 ℝ) ℝ where
locallyTrivialDiffeomorphism (V1 n) = n
coerceNeedle _ = LinearFunction $ \(V1 n) -> n
coerceNeedle' _ = LinearFunction $ \(V1 n) -> n
instance LocallyCoercible (ℝ,ℝ) (V2 ℝ) where
locallyTrivialDiffeomorphism = uncurry V2
coerceNeedle _ = LinearFunction $ uncurry V2
coerceNeedle' _ = LinearFunction $ uncurry V2
instance LocallyCoercible (V2 ℝ) (ℝ,ℝ) where
locallyTrivialDiffeomorphism (V2 x y) = (x,y)
coerceNeedle _ = LinearFunction $ \(V2 x y) -> (x,y)
coerceNeedle' _ = LinearFunction $ \(V2 x y) -> (x,y)
instance LocallyCoercible ((ℝ,ℝ),ℝ) (V3 ℝ) where
locallyTrivialDiffeomorphism ((x,y),z) = V3 x y z
coerceNeedle _ = LinearFunction $ \((x,y),z) -> V3 x y z
coerceNeedle' _ = LinearFunction $ \((x,y),z) -> V3 x y z
instance LocallyCoercible (ℝ,(ℝ,ℝ)) (V3 ℝ) where
locallyTrivialDiffeomorphism (x,(y,z)) = V3 x y z
coerceNeedle _ = LinearFunction $ \(x,(y,z)) -> V3 x y z
coerceNeedle' _ = LinearFunction $ \(x,(y,z)) -> V3 x y z
instance LocallyCoercible (V3 ℝ) ((ℝ,ℝ),ℝ) where
locallyTrivialDiffeomorphism (V3 x y z) = ((x,y),z)
coerceNeedle _ = LinearFunction $ \(V3 x y z) -> ((x,y),z)
coerceNeedle' _ = LinearFunction $ \(V3 x y z) -> ((x,y),z)
instance LocallyCoercible (V3 ℝ) (ℝ,(ℝ,ℝ)) where
locallyTrivialDiffeomorphism (V3 x y z) = (x,(y,z))
coerceNeedle _ = LinearFunction $ \(V3 x y z) -> (x,(y,z))
coerceNeedle' _ = LinearFunction $ \(V3 x y z) -> (x,(y,z))
instance LocallyCoercible ((ℝ,ℝ),(ℝ,ℝ)) (V4 ℝ) where
locallyTrivialDiffeomorphism ((x,y),(z,w)) = V4 x y z w
coerceNeedle _ = LinearFunction $ \((x,y),(z,w)) -> V4 x y z w
coerceNeedle' _ = LinearFunction $ \((x,y),(z,w)) -> V4 x y z w
instance LocallyCoercible (V4 ℝ) ((ℝ,ℝ),(ℝ,ℝ)) where
locallyTrivialDiffeomorphism (V4 x y z w) = ((x,y),(z,w))
coerceNeedle _ = LinearFunction $ \(V4 x y z w) -> ((x,y),(z,w))
coerceNeedle' _ = LinearFunction $ \(V4 x y z w) -> ((x,y),(z,w))
instance ∀ a b c .
( Semimanifold a, Semimanifold b, Semimanifold c
, LSpace (Needle a), LSpace (Needle b), LSpace (Needle c)
, Scalar (Needle a) ~ Scalar (Needle b), Scalar (Needle b) ~ Scalar (Needle c)
)
=> LocallyCoercible (a,(b,c)) ((a,b),c) where
locallyTrivialDiffeomorphism = regroup
coerceNeedle _ = regroup
coerceNeedle' _ = case ( dualSpaceWitness @(Needle a)
, dualSpaceWitness @(Needle b)
, dualSpaceWitness @(Needle c) ) of
(DualSpaceWitness, DualSpaceWitness, DualSpaceWitness) -> regroup
oppositeLocalCoercion = CanonicalDiffeomorphism
instance ∀ a b c .
( Semimanifold a, Semimanifold b, Semimanifold c
, LSpace (Needle a), LSpace (Needle b), LSpace (Needle c)
, Scalar (Needle a) ~ Scalar (Needle b), Scalar (Needle b) ~ Scalar (Needle c)
)
=> LocallyCoercible ((a,b),c) (a,(b,c)) where
locallyTrivialDiffeomorphism = regroup'
coerceNeedle _ = regroup'
coerceNeedle' _ = case ( dualSpaceWitness @(Needle a)
, dualSpaceWitness @(Needle b)
, dualSpaceWitness @(Needle c) ) of
(DualSpaceWitness, DualSpaceWitness, DualSpaceWitness) -> regroup'
oppositeLocalCoercion = CanonicalDiffeomorphism
instance (LinearSpace (a n), Needle (a n) ~ a n)
=> Semimanifold (LinAff.Point a n) where
type Needle (LinAff.Point a n) = a n
LinAff.P v .+~^ w = LinAff.P $ v ^+^ w
instance (LinearSpace (a n), Needle (a n) ~ a n)
=> PseudoAffine (LinAff.Point a n) where
LinAff.P v .-~. LinAff.P w = return $ v ^-^ w
LinAff.P v .-~! LinAff.P w = v ^-^ w
instance RealFloat' r => Semimanifold (S⁰_ r) where
type Needle (S⁰_ r) = ZeroDim r
p .+~^ Origin = p
p .-~^ Origin = p
instance RealFloat' r => PseudoAffine (S⁰_ r) where
PositiveHalfSphere .-~. PositiveHalfSphere = pure Origin
NegativeHalfSphere .-~. NegativeHalfSphere = pure Origin
_ .-~. _ = Nothing
PositiveHalfSphere .-~! PositiveHalfSphere = Origin
NegativeHalfSphere .-~! NegativeHalfSphere = Origin
_ .-~! _ = error "There is no path between the two 0-dimensional half spheres."
instance RealFloat' r => Semimanifold (S¹_ r) where
type Needle (S¹_ r) = r
S¹Polar φ₀ .+~^ δφ = S¹Polar $ φ'
where φ' = toS¹range $ φ₀ + δφ
semimanifoldWitness = case linearManifoldWitness @r of
LinearManifoldWitness -> SemimanifoldWitness
instance RealFloat' r => PseudoAffine (S¹_ r) where
p .-~. q = pure (p.-~!q)
S¹Polar φ₁ .-~! S¹Polar φ₀
| δφ > pi = δφ - tau
| δφ < (-pi) = δφ + tau
| otherwise = δφ
where δφ = φ₁ - φ₀
instance RealFloat' s => Semimanifold (S²_ s) where
type Needle (S²_ s) = V2 s
(.+~^) = case linearManifoldWitness @s of
LinearManifoldWitness ->
let addS² (S²Polar θ₀ φ₀) 𝐯 = S²Polar θ₁ φ₁
S¹Polar γc = coEmbed 𝐯
γ | θ₀ < pi/2 = γc - φ₀
| otherwise = γc + φ₀
d = magnitude 𝐯
S¹Polar φ₁ = S¹Polar φ₀ .+~^ δφ
Cartesian coordinates of p₁ in the system whose north pole is p₀
with φ₀ as the zero meridian
V3 bx by bz = embed $ S²Polar d γ
sθ₀ = sin θ₀; cθ₀ = cos θ₀
Cartesian coordinates of p₁ in the system with the standard north pole ,
but still φ₀ as the zero meridian
(qx,qz) = ( cθ₀ * bx + sθ₀ * bz
,-sθ₀ * bx + cθ₀ * bz )
qy = by
S²Polar θ₁ δφ = coEmbed $ V3 qx qy qz
in addS²
instance RealFloat' s => PseudoAffine (S²_ s) where
p.-~.q = pure (p.-~!q)
S²Polar θ₁ φ₁ .-~! S²Polar θ₀ φ₀ = d *^ embed(S¹Polar γc)
V3 qx qy qz = embed $ S²Polar θ₁ (φ₁-φ₀)
sθ₀ = sin θ₀; cθ₀ = cos θ₀
(bx,bz) = ( cθ₀ * qx - sθ₀ * qz
, sθ₀ * qx + cθ₀ * qz )
by = qy
S²Polar d γ = coEmbed $ V3 bx by bz
γc | θ₀ < pi/2 = γ + φ₀
| otherwise = γ - φ₀
instance Semimanifold ℝP² where
type Needle ℝP² = ℝ²
HemisphereℝP²Polar θ₀ φ₀ .+~^ v
= case S²Polar θ₀ φ₀ .+~^ v of
S²Polar θ₁ φ₁
| θ₁ > pi/2 -> HemisphereℝP²Polar (pi-θ₁) (-φ₁)
| otherwise -> HemisphereℝP²Polar θ₁ φ₁
instance PseudoAffine ℝP² where
p.-~.q = pure (p.-~!q)
HemisphereℝP²Polar θ₁ φ₁ .-~! HemisphereℝP²Polar θ₀ φ₀
= case S²Polar θ₁ φ₁ .-~! S²Polar θ₀ φ₀ of
v -> let r² = magnitudeSq v
in if r²>pi^2/4
then S²Polar (pi-θ₁) (-φ₁) .-~! S²Polar θ₀ φ₀
else v
instance ( PseudoAffine m , ( Needle m ) , Scalar ( Needle m ) ~ ℝ )
= > ( CD¹ m ) where
instance ( PseudoAffine m , ( Needle m ) , Scalar ( Needle m ) ~ ℝ )
class ImpliesMetric s where
type MetricRequirement s x :: Constraint
type MetricRequirement s x = Semimanifold x
inferMetric :: (MetricRequirement s x, LSpace (Needle x))
=> s x -> Metric x
inferMetric' :: (MetricRequirement s x, LSpace (Needle x))
=> s x -> Metric' x
instance ImpliesMetric Norm where
type MetricRequirement Norm x = (SimpleSpace x, x ~ Needle x)
inferMetric = id
inferMetric' = dualNorm
type DualNeedleWitness x = DualSpaceWitness (Needle x)
#if !MIN_VERSION_manifolds_core(0,6,0)
infixl 6 !+~^
(!+~^) :: ∀ x . (Semimanifold x, HasCallStack) => x -> Needle x -> x
p!+~^v = case toInterior p of
Just p' -> p'.+~^v
#endif
infix 6 .−.
class (PseudoAffine m) => Connected m where
# MINIMAL #
(.−.) :: m -> m -> Needle m
(.−.) = (.-~!)
instance Connected ℝ⁰
instance Connected ℝ
instance Connected ℝ¹
instance Connected ℝ²
instance Connected ℝ³
instance Connected ℝ⁴
instance Connected S¹
instance Connected S²
instance Connected ℝP⁰
instance Connected ℝP¹
instance Connected ℝP²
instance (Connected x, Connected y) => Connected (x,y)
instance (Connected x, Connected y, PseudoAffine (FibreBundle x y))
=> Connected (FibreBundle x y)
type LinearManifold m = (LinearSpace m, Manifold m)
type ScalarManifold s = (Num' s, Manifold s, Manifold (ZeroDim s))
type Num'' s = ScalarManifold s
type RealFrac'' s = (RealFrac' s, ScalarManifold s)
type RealFloat'' s = (RealFloat' s, SimpleSpace s, ScalarManifold s)
|
0015a089d756ae721aa4fb1ae21969b1e2182494bec822f2a01795a0290229db | brendanhay/amazonka | Amazonka.hs | # OPTIONS_GHC -fno - warn - duplicate - exports #
-- |
-- Module : Amazonka
Copyright : ( c ) 2013 - 2021
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : provisional
Portability : non - portable ( GHC extensions )
--
-- This module provides simple 'Env' and 'IO'-based operations which
can be performed against remote Amazon Web Services APIs , for use with the types
supplied by the various @amazonka-*@ libraries .
module Amazonka
( -- * Usage
-- $usage
-- * Authentication and Environment
Env.Env' (..),
Env.Env,
Env.EnvNoAuth,
Env.newEnv,
Env.newEnvFromManager,
Env.newEnvNoAuth,
Env.newEnvNoAuthFromManager,
Env.authMaybe,
-- ** Service Configuration
-- $service
Env.overrideService,
Env.configureService,
Env.globalTimeout,
Env.once,
-- ** Running AWS Actions
runResourceT,
* * Credential Discovery
AccessKey (..),
SecretKey (..),
SessionToken (..),
discover,
-- $discovery
-- ** Supported Regions
Region (..),
-- ** Service Endpoints
Endpoint (..),
Endpoint.setEndpoint,
-- * Sending Requests
-- $sending
send,
sendEither,
-- ** Pagination
-- $pagination
paginate,
paginateEither,
-- ** Waiters
-- $waiters
await,
awaitEither,
-- ** Unsigned
sendUnsigned,
sendUnsignedEither,
-- ** Streaming
-- $streaming
ToBody (..),
RequestBody (..),
ResponseBody (..),
-- *** Hashed Request Bodies
ToHashedBody (..),
HashedBody (..),
Body.hashedFile,
Body.hashedFileRange,
Body.hashedBody,
-- *** Chunked Request Bodies
ChunkedBody (..),
ChunkSize (..),
defaultChunkSize,
Body.chunkedFile,
Body.chunkedFileRange,
Body.unsafeChunkedBody,
-- *** Response Bodies
Body.sinkBody,
-- *** File Size and MD5/SHA256
Body.getFileSize,
Crypto.sinkMD5,
Crypto.sinkSHA256,
-- * Presigning Requests
-- $presigning
presignURL,
presign,
-- * EC2 Instance Metadata
-- $metadata
EC2.Dynamic (..),
dynamic,
EC2.Metadata (..),
metadata,
userdata,
-- * Running Asynchronous Actions
-- $async
-- * Handling Errors
-- $errors
AsError (..),
AsAuthError (..),
Lens.trying,
Lens.catching,
-- ** Building Error Prisms
Error._MatchServiceError,
Error.hasService,
Error.hasStatus,
Error.hasCode,
-- * Logging
-- $logging
LogLevel (..),
Logger,
-- ** Constructing a Logger
newLogger,
-- * Re-exported Types
module Amazonka.Core,
)
where
import Amazonka.Auth
import Amazonka.Core hiding (presign)
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Crypto as Crypto
import qualified Amazonka.Data.Body as Body
import qualified Amazonka.EC2.Metadata as EC2
import qualified Amazonka.Endpoint as Endpoint
import qualified Amazonka.Env as Env
import qualified Amazonka.Error as Error
import Amazonka.Logger
import Amazonka.Prelude
import qualified Amazonka.Presign as Presign
import Amazonka.Request (clientRequestURL)
import Amazonka.Send
( await,
awaitEither,
paginate,
paginateEither,
send,
sendEither,
sendUnsigned,
sendUnsignedEither,
)
import Control.Monad.Trans.Resource (runResourceT)
-- $usage
-- The key functions dealing with the request/response lifecycle are:
--
-- * 'send', 'sendEither'
--
-- * 'paginate', 'paginateEither'
--
-- * 'await', 'awaitEither'
--
These functions have constraints that types from the @amazonka-*@ libraries
-- satisfy. To utilise these, you will need to specify what 'Region' you wish to
operate in and your Amazon credentials for AuthN / AuthZ purposes .
--
-- 'Credentials' can be supplied in a number of ways. Either via explicit keys,
-- via session profiles, or have Amazonka retrieve the credentials from an
underlying IAM Role / Profile .
--
-- As a basic example, you might wish to store an object in an S3 bucket using
< -s3 amazonka - s3 > :
--
-- @
{ - # LANGUAGE OverloadedStrings # - }
--
-- import qualified Amazonka as AWS
-- import qualified Amazonka.S3 as S3
import qualified System . IO as IO
--
example : : IO
-- example = do
-- -- A new 'Logger' to replace the default noop logger is created, with the logger
-- -- set to print debug information and errors to stdout:
-- logger <- AWS.newLogger AWS.Debug IO.stdout
--
-- -- To specify configuration preferences, 'newEnv' is used to create a new
-- -- configuration environment. The argument to 'newEnv' is used to specify the
-- mechanism for supplying or retrieving AuthN / AuthZ information .
-- -- In this case 'discover' will cause the library to try a number of options such
-- as default environment variables , or an instance 's IAM Profile and identity document :
-- discoveredEnv <- AWS.newEnv AWS.discover
--
-- let env =
-- discoveredEnv
-- { AWS.logger = logger
, AWS.region = AWS.Frankfurt
-- }
--
-- -- The payload (and hash) for the S3 object is retrieved from a 'FilePath',
-- -- either 'hashedFile' or 'chunkedFile' can be used, with the latter ensuring
-- -- the contents of the file is enumerated exactly once, during send:
-- body <- AWS.chunkedFile AWS.defaultChunkSize "local\/path\/to\/object-payload"
--
-- -- We now run the 'AWS' computation with the overriden logger, performing the
-- ' PutObject ' request .
-- AWS.runResourceT $
AWS.send env ( S3.newPutObject " bucket - name " " object - key " body )
-- @
-- $discovery
-- AuthN/AuthZ information is handled similarly to other AWS SDKs. You can read
some of the options available < -New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs here > .
--
-- Authentication methods which return short-lived credentials (e.g., when running on
-- an EC2 instance) fork a background thread which transparently handles the expiry
and subsequent refresh of IAM profile information . See
-- 'Amazonka.Auth.Background.fetchAuthInBackground' for more information.
--
-- /See:/ "Amazonka.Auth", if you want to commit to specific authentication methods.
--
/See:/ ' Amazonka . ' if you want to build your own credential chain .
-- $sending
-- To send a request you need to create a value of the desired operation type using
-- the relevant constructor, as well as any further modifications of default/optional
-- parameters using the appropriate lenses. This value can then be sent using 'send'
-- or 'paginate' and the library will take care of serialisation/authentication and
-- so forth.
--
-- The default 'Service' configuration for a request contains retry configuration that is used to
-- determine if a request can safely be retried and what kind of back off/on strategy
-- should be used. (Usually exponential.)
-- Typically services define retry strategies that handle throttling, general server
-- errors and transport errors. Streaming requests are never retried.
-- $pagination
-- Some AWS operations return results that are incomplete and require subsequent
-- requests in order to obtain the entire result set. The process of sending
-- subsequent requests to continue where a previous request left off is called
pagination . For example , the ' ListObjects ' operation of Amazon S3 returns up to
1000 objects at a time , and you must send subsequent requests with the
appropriate in order to retrieve the next page of results .
--
Operations that have an ' AWSPager ' instance can transparently perform subsequent
-- requests, correctly setting Markers and other request facets to iterate through
-- the entire result set of a truncated API operation. Operations which support
-- this have an additional note in the documentation.
--
-- Many operations have the ability to filter results on the server side. See the
-- individual operation parameters for details.
-- $waiters
-- Waiters poll by repeatedly sending a request until some remote success condition
-- configured by the 'Wait' specification is fulfilled. The 'Wait' specification
-- determines how many attempts should be made, in addition to delay and retry strategies.
-- Error conditions that are not handled by the 'Wait' configuration will be thrown,
or the first successful response that fulfills the success condition will be
-- returned.
--
-- 'Wait' specifications can be found under the @Amazonka.{ServiceName}.Waiters@
-- namespace for services which support 'await'.
-- $service
-- When a request is sent, various values such as the endpoint,
-- retry strategy, timeout and error handlers are taken from the associated 'Service'
-- for a request. For example, 'DynamoDB' will use the 'Amazonka.DynamoDB.defaultService'
-- configuration when sending 'PutItem', 'Query' and all other operations.
--
-- You can modify a specific 'Service''s default configuration by using
-- 'configure'. To modify all configurations simultaneously, see 'override'.
--
-- An example of how you might alter default configuration using these mechanisms
is demonstrated below . Firstly , the default ' dynamoDB ' service is configured to
use non - SSL localhost as the endpoint :
--
--
-- > import qualified Amazonka as AWS
-- > import qualified Amazonka.DynamoDB as DynamoDB
-- >
> let dynamo : :
> dynamo = AWS.setEndpoint False " localhost " 8000 DynamoDB.defaultService
--
-- The updated configuration is then passed to the 'Env' during setup:
--
-- > env <- AWS.configure dynamo <$> AWS.newEnv AWS.discover
-- >
-- > AWS.runResourceT $ do
-- > -- This S3 operation will communicate with remote AWS APIs.
-- > x <- AWS.send env newListBuckets
-- >
-- > -- DynamoDB operations will communicate with localhost:8000.
-- > y <- AWS.send env Dynamo.newListTables
-- >
-- > -- Any operations for services other than DynamoDB, are not affected.
-- > ...
--
-- You can also scope the service configuration modifications to specific actions:
--
-- > env <- AWS.newEnv AWS.discover
-- >
-- > AWS.runResourceT $ do
-- > -- Service operations here will communicate with AWS, even remote DynamoDB.
-- > x <- AWS.send env Dynamo.newListTables
-- >
-- > -- Here DynamoDB operations will communicate with localhost:8000.
-- > y <- AWS.send (AWS.configure dynamo env) Dynamo.newListTables
--
-- Functions such as 'within', 'once', and 'globalTimeout' can also be
-- used to modify service configuration for all (or specific)
-- requests.
-- $streaming
Streaming comes in two flavours . ' HashedBody ' represents a request
that requires a precomputed ' SHA256 ' hash , or a ' ChunkedBody ' type for those services
-- that can perform incremental signing and do not require the entire payload to
-- be hashed (such as S3). The type signatures for request smart constructors
-- advertise which respective body type is required, denoting the underlying signing
-- capabilities.
--
-- 'ToHashedBody' and 'ToBody' typeclass instances are available to construct the
-- streaming bodies, automatically calculating any hash or size as needed for types
such as ' Text ' , ' ByteString ' , or Aeson 's ' Value ' type . To read files and other
-- 'IO' primitives, functions such as 'hashedFile', 'chunkedFile', or 'hashedBody'
-- should be used.
--
For responses that contain streaming bodies ( such as ' GetObject ' ) , you can use
-- 'sinkBody' to connect the response body to a
< conduit>-compatible sink .
-- $presigning
Presigning requires the ' Service ' signer to be an instance of ' AWSPresigner ' .
-- Not all signing algorithms support this.
-- $metadata
Metadata can be retrieved from the underlying host assuming that you 're running
-- the code on an EC2 instance or have a compatible @instance-data@ endpoint available.
-- $async
-- Requests can be sent asynchronously, but due to guarantees about resource closure
require the use of " UnliftIO.Async " .
--
The following example demonstrates retrieving two objects from S3 concurrently :
--
-- @
{ - # LANGUAGE OverloadedStrings # - }
-- import qualified Amazonka as AWS
-- import qualified Amazonka.S3 as S3
import qualified UnliftIO.Async as Async
--
-- let requestA = S3.newGetObject "bucket" "prefix/object-a"
-- let requestB = S3.newGetObject "bucket" "prefix/object-b"
--
-- runResourceT $
-- Async.'UnliftIO.Async.withAsync' (send env requestA) $ \\asyncA ->
-- Async.'UnliftIO.Async.withAsync' (send env requestB) $ \\asyncB -> do
-- Async.'UnliftIO.Async.waitBoth' asyncA asyncB
-- @
--
-- If you are running many async requests in parallel, using
' Control . . Trans . Cont . ContT ' can hide the giant callback pyramid :
--
-- @
runResourceT . ' Control . . Trans . Cont.evalContT ' $ do
-- asyncA <- ContT $ Async.'UnliftIO.Async.withAsync' (send env requestA)
-- asyncB <- ContT $ Async.'UnliftIO.Async.withAsync' (send env requestB)
Async . 'UnliftIO.Async.waitBoth ' asyncA asyncB
-- @
-- $errors
-- Errors are either returned or thrown by the library using 'IO'. Sub-errors of
-- the canonical 'Error' type can be caught using 'trying' or 'catching' and the
-- appropriate 'AsError' 'Prism' when using the non-'Either' send variants:
--
-- @
-- trying '_Error' (send $ newListObjects "bucket-name") :: Either 'Error' ListObjectsResponse
trying ' _ TransportError ' ( send $ newListObjects " bucket - name " ) : : Either ' HttpException ' ListObjectsResponse
-- trying '_SerializeError' (send $ newListObjects "bucket-name") :: Either 'SerializeError' ListObjectsResponse
trying ' _ ServiceError ' ( send $ newListObjects " bucket - name " ) : : Either ' ServiceError ' ListObjectsResponse
-- @
--
Many of the individual @amazonka-*@ libraries export compatible ' Control . Lens . 's for
-- matching service specific error codes and messages in the style above.
-- See the @Error Matchers@ heading in each respective library for details.
-- $logging
-- The exposed logging interface is a primitive 'Logger' function which gets
-- threaded through service calls and serialisation routines. This allows the
-- library to output useful information and diagnostics.
--
-- The 'newLogger' function can be used to construct a simple logger which writes
-- output to a 'Handle', but in most production code you should probably consider
-- using a more robust logging library such as
-- < tinylog> or
-- <-logger fast-logger>.
-- | Presign an URL that is valid from the specified time until the
number of seconds expiry has elapsed .
presignURL ::
( MonadIO m,
AWSRequest a
) =>
Env ->
-- | Signing time.
UTCTime ->
-- | Expiry time.
Seconds ->
-- | Request to presign.
a ->
m ByteString
presignURL env time expires =
fmap clientRequestURL
. presign env time expires
-- | Presign an HTTP request that is valid from the specified time until the
number of seconds expiry has elapsed .
presign ::
( MonadIO m,
AWSRequest a
) =>
Env ->
-- | Signing time.
UTCTime ->
-- | Expiry time.
Seconds ->
-- | Request to presign.
a ->
m ClientRequest
presign env time expires rq = withAuth (runIdentity $ Env.auth env) $ \ae ->
pure $! Presign.presignWith
(Env.overrides env)
ae
(Env.region env)
time
expires
rq
-- | Retrieve the specified 'Dynamic' data.
dynamic :: MonadIO m => Env -> EC2.Dynamic -> m ByteString
dynamic env = EC2.dynamic (Env.manager env)
-- | Retrieve the specified 'Metadata'.
metadata :: MonadIO m => Env -> EC2.Metadata -> m ByteString
metadata env = EC2.metadata (Env.manager env)
-- | Retrieve the user data. Returns 'Nothing' if no user data is assigned
-- to the instance.
userdata :: MonadIO m => Env -> m (Maybe ByteString)
userdata = EC2.userdata . Env.manager
| null | https://raw.githubusercontent.com/brendanhay/amazonka/7b8c332d91a13d47cb6478529264b8cb6d0dd5a3/lib/amazonka/src/Amazonka.hs | haskell | |
Module : Amazonka
Stability : provisional
This module provides simple 'Env' and 'IO'-based operations which
* Usage
$usage
* Authentication and Environment
** Service Configuration
$service
** Running AWS Actions
$discovery
** Supported Regions
** Service Endpoints
* Sending Requests
$sending
** Pagination
$pagination
** Waiters
$waiters
** Unsigned
** Streaming
$streaming
*** Hashed Request Bodies
*** Chunked Request Bodies
*** Response Bodies
*** File Size and MD5/SHA256
* Presigning Requests
$presigning
* EC2 Instance Metadata
$metadata
* Running Asynchronous Actions
$async
* Handling Errors
$errors
** Building Error Prisms
* Logging
$logging
** Constructing a Logger
* Re-exported Types
$usage
The key functions dealing with the request/response lifecycle are:
* 'send', 'sendEither'
* 'paginate', 'paginateEither'
* 'await', 'awaitEither'
satisfy. To utilise these, you will need to specify what 'Region' you wish to
'Credentials' can be supplied in a number of ways. Either via explicit keys,
via session profiles, or have Amazonka retrieve the credentials from an
As a basic example, you might wish to store an object in an S3 bucket using
@
import qualified Amazonka as AWS
import qualified Amazonka.S3 as S3
example = do
-- A new 'Logger' to replace the default noop logger is created, with the logger
-- set to print debug information and errors to stdout:
logger <- AWS.newLogger AWS.Debug IO.stdout
-- To specify configuration preferences, 'newEnv' is used to create a new
-- configuration environment. The argument to 'newEnv' is used to specify the
mechanism for supplying or retrieving AuthN / AuthZ information .
-- In this case 'discover' will cause the library to try a number of options such
as default environment variables , or an instance 's IAM Profile and identity document :
discoveredEnv <- AWS.newEnv AWS.discover
let env =
discoveredEnv
{ AWS.logger = logger
}
-- The payload (and hash) for the S3 object is retrieved from a 'FilePath',
-- either 'hashedFile' or 'chunkedFile' can be used, with the latter ensuring
-- the contents of the file is enumerated exactly once, during send:
body <- AWS.chunkedFile AWS.defaultChunkSize "local\/path\/to\/object-payload"
-- We now run the 'AWS' computation with the overriden logger, performing the
' PutObject ' request .
AWS.runResourceT $
@
$discovery
AuthN/AuthZ information is handled similarly to other AWS SDKs. You can read
Authentication methods which return short-lived credentials (e.g., when running on
an EC2 instance) fork a background thread which transparently handles the expiry
'Amazonka.Auth.Background.fetchAuthInBackground' for more information.
/See:/ "Amazonka.Auth", if you want to commit to specific authentication methods.
$sending
To send a request you need to create a value of the desired operation type using
the relevant constructor, as well as any further modifications of default/optional
parameters using the appropriate lenses. This value can then be sent using 'send'
or 'paginate' and the library will take care of serialisation/authentication and
so forth.
The default 'Service' configuration for a request contains retry configuration that is used to
determine if a request can safely be retried and what kind of back off/on strategy
should be used. (Usually exponential.)
Typically services define retry strategies that handle throttling, general server
errors and transport errors. Streaming requests are never retried.
$pagination
Some AWS operations return results that are incomplete and require subsequent
requests in order to obtain the entire result set. The process of sending
subsequent requests to continue where a previous request left off is called
requests, correctly setting Markers and other request facets to iterate through
the entire result set of a truncated API operation. Operations which support
this have an additional note in the documentation.
Many operations have the ability to filter results on the server side. See the
individual operation parameters for details.
$waiters
Waiters poll by repeatedly sending a request until some remote success condition
configured by the 'Wait' specification is fulfilled. The 'Wait' specification
determines how many attempts should be made, in addition to delay and retry strategies.
Error conditions that are not handled by the 'Wait' configuration will be thrown,
returned.
'Wait' specifications can be found under the @Amazonka.{ServiceName}.Waiters@
namespace for services which support 'await'.
$service
When a request is sent, various values such as the endpoint,
retry strategy, timeout and error handlers are taken from the associated 'Service'
for a request. For example, 'DynamoDB' will use the 'Amazonka.DynamoDB.defaultService'
configuration when sending 'PutItem', 'Query' and all other operations.
You can modify a specific 'Service''s default configuration by using
'configure'. To modify all configurations simultaneously, see 'override'.
An example of how you might alter default configuration using these mechanisms
> import qualified Amazonka as AWS
> import qualified Amazonka.DynamoDB as DynamoDB
>
The updated configuration is then passed to the 'Env' during setup:
> env <- AWS.configure dynamo <$> AWS.newEnv AWS.discover
>
> AWS.runResourceT $ do
> -- This S3 operation will communicate with remote AWS APIs.
> x <- AWS.send env newListBuckets
>
> -- DynamoDB operations will communicate with localhost:8000.
> y <- AWS.send env Dynamo.newListTables
>
> -- Any operations for services other than DynamoDB, are not affected.
> ...
You can also scope the service configuration modifications to specific actions:
> env <- AWS.newEnv AWS.discover
>
> AWS.runResourceT $ do
> -- Service operations here will communicate with AWS, even remote DynamoDB.
> x <- AWS.send env Dynamo.newListTables
>
> -- Here DynamoDB operations will communicate with localhost:8000.
> y <- AWS.send (AWS.configure dynamo env) Dynamo.newListTables
Functions such as 'within', 'once', and 'globalTimeout' can also be
used to modify service configuration for all (or specific)
requests.
$streaming
that can perform incremental signing and do not require the entire payload to
be hashed (such as S3). The type signatures for request smart constructors
advertise which respective body type is required, denoting the underlying signing
capabilities.
'ToHashedBody' and 'ToBody' typeclass instances are available to construct the
streaming bodies, automatically calculating any hash or size as needed for types
'IO' primitives, functions such as 'hashedFile', 'chunkedFile', or 'hashedBody'
should be used.
'sinkBody' to connect the response body to a
$presigning
Not all signing algorithms support this.
$metadata
the code on an EC2 instance or have a compatible @instance-data@ endpoint available.
$async
Requests can be sent asynchronously, but due to guarantees about resource closure
@
import qualified Amazonka as AWS
import qualified Amazonka.S3 as S3
let requestA = S3.newGetObject "bucket" "prefix/object-a"
let requestB = S3.newGetObject "bucket" "prefix/object-b"
runResourceT $
Async.'UnliftIO.Async.withAsync' (send env requestA) $ \\asyncA ->
Async.'UnliftIO.Async.withAsync' (send env requestB) $ \\asyncB -> do
Async.'UnliftIO.Async.waitBoth' asyncA asyncB
@
If you are running many async requests in parallel, using
@
asyncA <- ContT $ Async.'UnliftIO.Async.withAsync' (send env requestA)
asyncB <- ContT $ Async.'UnliftIO.Async.withAsync' (send env requestB)
@
$errors
Errors are either returned or thrown by the library using 'IO'. Sub-errors of
the canonical 'Error' type can be caught using 'trying' or 'catching' and the
appropriate 'AsError' 'Prism' when using the non-'Either' send variants:
@
trying '_Error' (send $ newListObjects "bucket-name") :: Either 'Error' ListObjectsResponse
trying '_SerializeError' (send $ newListObjects "bucket-name") :: Either 'SerializeError' ListObjectsResponse
@
matching service specific error codes and messages in the style above.
See the @Error Matchers@ heading in each respective library for details.
$logging
The exposed logging interface is a primitive 'Logger' function which gets
threaded through service calls and serialisation routines. This allows the
library to output useful information and diagnostics.
The 'newLogger' function can be used to construct a simple logger which writes
output to a 'Handle', but in most production code you should probably consider
using a more robust logging library such as
< tinylog> or
<-logger fast-logger>.
| Presign an URL that is valid from the specified time until the
| Signing time.
| Expiry time.
| Request to presign.
| Presign an HTTP request that is valid from the specified time until the
| Signing time.
| Expiry time.
| Request to presign.
| Retrieve the specified 'Dynamic' data.
| Retrieve the specified 'Metadata'.
| Retrieve the user data. Returns 'Nothing' if no user data is assigned
to the instance. | # OPTIONS_GHC -fno - warn - duplicate - exports #
Copyright : ( c ) 2013 - 2021
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
can be performed against remote Amazon Web Services APIs , for use with the types
supplied by the various @amazonka-*@ libraries .
module Amazonka
Env.Env' (..),
Env.Env,
Env.EnvNoAuth,
Env.newEnv,
Env.newEnvFromManager,
Env.newEnvNoAuth,
Env.newEnvNoAuthFromManager,
Env.authMaybe,
Env.overrideService,
Env.configureService,
Env.globalTimeout,
Env.once,
runResourceT,
* * Credential Discovery
AccessKey (..),
SecretKey (..),
SessionToken (..),
discover,
Region (..),
Endpoint (..),
Endpoint.setEndpoint,
send,
sendEither,
paginate,
paginateEither,
await,
awaitEither,
sendUnsigned,
sendUnsignedEither,
ToBody (..),
RequestBody (..),
ResponseBody (..),
ToHashedBody (..),
HashedBody (..),
Body.hashedFile,
Body.hashedFileRange,
Body.hashedBody,
ChunkedBody (..),
ChunkSize (..),
defaultChunkSize,
Body.chunkedFile,
Body.chunkedFileRange,
Body.unsafeChunkedBody,
Body.sinkBody,
Body.getFileSize,
Crypto.sinkMD5,
Crypto.sinkSHA256,
presignURL,
presign,
EC2.Dynamic (..),
dynamic,
EC2.Metadata (..),
metadata,
userdata,
AsError (..),
AsAuthError (..),
Lens.trying,
Lens.catching,
Error._MatchServiceError,
Error.hasService,
Error.hasStatus,
Error.hasCode,
LogLevel (..),
Logger,
newLogger,
module Amazonka.Core,
)
where
import Amazonka.Auth
import Amazonka.Core hiding (presign)
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Crypto as Crypto
import qualified Amazonka.Data.Body as Body
import qualified Amazonka.EC2.Metadata as EC2
import qualified Amazonka.Endpoint as Endpoint
import qualified Amazonka.Env as Env
import qualified Amazonka.Error as Error
import Amazonka.Logger
import Amazonka.Prelude
import qualified Amazonka.Presign as Presign
import Amazonka.Request (clientRequestURL)
import Amazonka.Send
( await,
awaitEither,
paginate,
paginateEither,
send,
sendEither,
sendUnsigned,
sendUnsignedEither,
)
import Control.Monad.Trans.Resource (runResourceT)
These functions have constraints that types from the @amazonka-*@ libraries
operate in and your Amazon credentials for AuthN / AuthZ purposes .
underlying IAM Role / Profile .
< -s3 amazonka - s3 > :
{ - # LANGUAGE OverloadedStrings # - }
import qualified System . IO as IO
example : : IO
, AWS.region = AWS.Frankfurt
AWS.send env ( S3.newPutObject " bucket - name " " object - key " body )
some of the options available < -New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs here > .
and subsequent refresh of IAM profile information . See
/See:/ ' Amazonka . ' if you want to build your own credential chain .
pagination . For example , the ' ListObjects ' operation of Amazon S3 returns up to
1000 objects at a time , and you must send subsequent requests with the
appropriate in order to retrieve the next page of results .
Operations that have an ' AWSPager ' instance can transparently perform subsequent
or the first successful response that fulfills the success condition will be
is demonstrated below . Firstly , the default ' dynamoDB ' service is configured to
use non - SSL localhost as the endpoint :
> let dynamo : :
> dynamo = AWS.setEndpoint False " localhost " 8000 DynamoDB.defaultService
Streaming comes in two flavours . ' HashedBody ' represents a request
that requires a precomputed ' SHA256 ' hash , or a ' ChunkedBody ' type for those services
such as ' Text ' , ' ByteString ' , or Aeson 's ' Value ' type . To read files and other
For responses that contain streaming bodies ( such as ' GetObject ' ) , you can use
< conduit>-compatible sink .
Presigning requires the ' Service ' signer to be an instance of ' AWSPresigner ' .
Metadata can be retrieved from the underlying host assuming that you 're running
require the use of " UnliftIO.Async " .
The following example demonstrates retrieving two objects from S3 concurrently :
{ - # LANGUAGE OverloadedStrings # - }
import qualified UnliftIO.Async as Async
' Control . . Trans . Cont . ContT ' can hide the giant callback pyramid :
runResourceT . ' Control . . Trans . Cont.evalContT ' $ do
Async . 'UnliftIO.Async.waitBoth ' asyncA asyncB
trying ' _ TransportError ' ( send $ newListObjects " bucket - name " ) : : Either ' HttpException ' ListObjectsResponse
trying ' _ ServiceError ' ( send $ newListObjects " bucket - name " ) : : Either ' ServiceError ' ListObjectsResponse
Many of the individual @amazonka-*@ libraries export compatible ' Control . Lens . 's for
number of seconds expiry has elapsed .
presignURL ::
( MonadIO m,
AWSRequest a
) =>
Env ->
UTCTime ->
Seconds ->
a ->
m ByteString
presignURL env time expires =
fmap clientRequestURL
. presign env time expires
number of seconds expiry has elapsed .
presign ::
( MonadIO m,
AWSRequest a
) =>
Env ->
UTCTime ->
Seconds ->
a ->
m ClientRequest
presign env time expires rq = withAuth (runIdentity $ Env.auth env) $ \ae ->
pure $! Presign.presignWith
(Env.overrides env)
ae
(Env.region env)
time
expires
rq
dynamic :: MonadIO m => Env -> EC2.Dynamic -> m ByteString
dynamic env = EC2.dynamic (Env.manager env)
metadata :: MonadIO m => Env -> EC2.Metadata -> m ByteString
metadata env = EC2.metadata (Env.manager env)
userdata :: MonadIO m => Env -> m (Maybe ByteString)
userdata = EC2.userdata . Env.manager
|
356423c2aa9c12e393f12feb139dcf0393f5ce47d7c258eac8abaef505be3949 | TerrorJack/ghc-alter | Utils.hs | # LANGUAGE Trustworthy #
# LANGUAGE NoImplicitPrelude #
-----------------------------------------------------------------------------
-- This is a non-exposed internal module.
--
-- This code contains utility function and data structures that are used
-- to improve the efficiency of several instances in the Data.* namespace.
-----------------------------------------------------------------------------
module Data.Functor.Utils where
import Data.Coerce (Coercible, coerce)
import GHC.Base ( Applicative(..), Functor(..), Maybe(..), Monoid(..), Ord(..)
, ($), otherwise )
We do n't expose and because , as pointed out to me ,
there are two reasonable ways to define them . One way is to use Maybe , as we
-- do here; the other way is to impose a Bounded constraint on the Monoid
-- instance. We may eventually want to add both versions, but we don't want to
trample on anyone 's toes by imposing = .
newtype Max a = Max {getMax :: Maybe a}
newtype Min a = Min {getMin :: Maybe a}
| @since 4.8.0.0
instance Ord a => Monoid (Max a) where
mempty = Max Nothing
# INLINE mappend #
m `mappend` Max Nothing = m
Max Nothing `mappend` n = n
(Max m@(Just x)) `mappend` (Max n@(Just y))
| x >= y = Max m
| otherwise = Max n
| @since 4.8.0.0
instance Ord a => Monoid (Min a) where
mempty = Min Nothing
# INLINE mappend #
m `mappend` Min Nothing = m
Min Nothing `mappend` n = n
(Min m@(Just x)) `mappend` (Min n@(Just y))
| x <= y = Min m
| otherwise = Min n
-- left-to-right state transformer
newtype StateL s a = StateL { runStateL :: s -> (s, a) }
| @since 4.0
instance Functor (StateL s) where
fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v)
| @since 4.0
instance Applicative (StateL s) where
pure x = StateL (\ s -> (s, x))
StateL kf <*> StateL kv = StateL $ \ s ->
let (s', f) = kf s
(s'', v) = kv s'
in (s'', f v)
liftA2 f (StateL kx) (StateL ky) = StateL $ \s ->
let (s', x) = kx s
(s'', y) = ky s'
in (s'', f x y)
-- right-to-left state transformer
newtype StateR s a = StateR { runStateR :: s -> (s, a) }
| @since 4.0
instance Functor (StateR s) where
fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v)
| @since 4.0
instance Applicative (StateR s) where
pure x = StateR (\ s -> (s, x))
StateR kf <*> StateR kv = StateR $ \ s ->
let (s', v) = kv s
(s'', f) = kf s'
in (s'', f v)
liftA2 f (StateR kx) (StateR ky) = StateR $ \ s ->
let (s', y) = ky s
(s'', x) = kx s'
in (s'', f x y)
-- See Note [Function coercion]
(#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c)
(#.) _f = coerce
# INLINE ( # . ) #
Note [ Function coercion ]
~~~~~~~~~~~~~~~~~~~~~~~
Several functions here use ( # . ) instead of ( . ) to avoid potential efficiency
problems relating to # 7542 . The problem , in a nutshell :
If N is a newtype constructor , then N x will always have the same
representation as x ( something similar applies for a newtype deconstructor ) .
However , if f is a function ,
N . f = \x - > N ( f x )
This looks almost the same as f , but the eta expansion lifts it -- the lhs could
be _ | _ , but the rhs never is . This can lead to very inefficient code . Thus we
steal a technique from and and adapt it to the current
( rather clean ) setting . Instead of using N . f , we use N # . f , which is
just
coerce f ` asTypeOf ` ( N . f )
That is , we just * pretend * that f has the right type , and thanks to the safety
of coerce , the type checker guarantees that nothing really goes wrong . We still
have to be a bit careful , though : remember that # . completely ignores the
* value * of its left operand .
Note [Function coercion]
~~~~~~~~~~~~~~~~~~~~~~~
Several functions here use (#.) instead of (.) to avoid potential efficiency
problems relating to #7542. The problem, in a nutshell:
If N is a newtype constructor, then N x will always have the same
representation as x (something similar applies for a newtype deconstructor).
However, if f is a function,
N . f = \x -> N (f x)
This looks almost the same as f, but the eta expansion lifts it--the lhs could
be _|_, but the rhs never is. This can lead to very inefficient code. Thus we
steal a technique from Shachaf and Edward Kmett and adapt it to the current
(rather clean) setting. Instead of using N . f, we use N #. f, which is
just
coerce f `asTypeOf` (N . f)
That is, we just *pretend* that f has the right type, and thanks to the safety
of coerce, the type checker guarantees that nothing really goes wrong. We still
have to be a bit careful, though: remember that #. completely ignores the
*value* of its left operand.
-}
| null | https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/base/Data/Functor/Utils.hs | haskell | ---------------------------------------------------------------------------
This is a non-exposed internal module.
This code contains utility function and data structures that are used
to improve the efficiency of several instances in the Data.* namespace.
---------------------------------------------------------------------------
do here; the other way is to impose a Bounded constraint on the Monoid
instance. We may eventually want to add both versions, but we don't want to
left-to-right state transformer
right-to-left state transformer
See Note [Function coercion]
the lhs could
the lhs could | # LANGUAGE Trustworthy #
# LANGUAGE NoImplicitPrelude #
module Data.Functor.Utils where
import Data.Coerce (Coercible, coerce)
import GHC.Base ( Applicative(..), Functor(..), Maybe(..), Monoid(..), Ord(..)
, ($), otherwise )
We do n't expose and because , as pointed out to me ,
there are two reasonable ways to define them . One way is to use Maybe , as we
trample on anyone 's toes by imposing = .
newtype Max a = Max {getMax :: Maybe a}
newtype Min a = Min {getMin :: Maybe a}
| @since 4.8.0.0
instance Ord a => Monoid (Max a) where
mempty = Max Nothing
# INLINE mappend #
m `mappend` Max Nothing = m
Max Nothing `mappend` n = n
(Max m@(Just x)) `mappend` (Max n@(Just y))
| x >= y = Max m
| otherwise = Max n
| @since 4.8.0.0
instance Ord a => Monoid (Min a) where
mempty = Min Nothing
# INLINE mappend #
m `mappend` Min Nothing = m
Min Nothing `mappend` n = n
(Min m@(Just x)) `mappend` (Min n@(Just y))
| x <= y = Min m
| otherwise = Min n
newtype StateL s a = StateL { runStateL :: s -> (s, a) }
| @since 4.0
instance Functor (StateL s) where
fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v)
| @since 4.0
instance Applicative (StateL s) where
pure x = StateL (\ s -> (s, x))
StateL kf <*> StateL kv = StateL $ \ s ->
let (s', f) = kf s
(s'', v) = kv s'
in (s'', f v)
liftA2 f (StateL kx) (StateL ky) = StateL $ \s ->
let (s', x) = kx s
(s'', y) = ky s'
in (s'', f x y)
newtype StateR s a = StateR { runStateR :: s -> (s, a) }
| @since 4.0
instance Functor (StateR s) where
fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v)
| @since 4.0
instance Applicative (StateR s) where
pure x = StateR (\ s -> (s, x))
StateR kf <*> StateR kv = StateR $ \ s ->
let (s', v) = kv s
(s'', f) = kf s'
in (s'', f v)
liftA2 f (StateR kx) (StateR ky) = StateR $ \ s ->
let (s', y) = ky s
(s'', x) = kx s'
in (s'', f x y)
(#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c)
(#.) _f = coerce
# INLINE ( # . ) #
Note [ Function coercion ]
~~~~~~~~~~~~~~~~~~~~~~~
Several functions here use ( # . ) instead of ( . ) to avoid potential efficiency
problems relating to # 7542 . The problem , in a nutshell :
If N is a newtype constructor , then N x will always have the same
representation as x ( something similar applies for a newtype deconstructor ) .
However , if f is a function ,
N . f = \x - > N ( f x )
be _ | _ , but the rhs never is . This can lead to very inefficient code . Thus we
steal a technique from and and adapt it to the current
( rather clean ) setting . Instead of using N . f , we use N # . f , which is
just
coerce f ` asTypeOf ` ( N . f )
That is , we just * pretend * that f has the right type , and thanks to the safety
of coerce , the type checker guarantees that nothing really goes wrong . We still
have to be a bit careful , though : remember that # . completely ignores the
* value * of its left operand .
Note [Function coercion]
~~~~~~~~~~~~~~~~~~~~~~~
Several functions here use (#.) instead of (.) to avoid potential efficiency
problems relating to #7542. The problem, in a nutshell:
If N is a newtype constructor, then N x will always have the same
representation as x (something similar applies for a newtype deconstructor).
However, if f is a function,
N . f = \x -> N (f x)
be _|_, but the rhs never is. This can lead to very inefficient code. Thus we
steal a technique from Shachaf and Edward Kmett and adapt it to the current
(rather clean) setting. Instead of using N . f, we use N #. f, which is
just
coerce f `asTypeOf` (N . f)
That is, we just *pretend* that f has the right type, and thanks to the safety
of coerce, the type checker guarantees that nothing really goes wrong. We still
have to be a bit careful, though: remember that #. completely ignores the
*value* of its left operand.
-}
|
fb0052e82a31049f92339441a11ce53194721f612266307b532051e851c605c5 | ocaml/oasis2debian | myocamlbuild.ml | (******************************************************************************)
(* oasis2debian: create and maintain a debian/ directory using _oasis *)
(* *)
Copyright ( C ) 2010 , OCamlCore SARL ,
(* *)
(* This library is free software; you can redistribute it and/or modify it *)
(* under the terms of the GNU Lesser General Public License as published by *)
the Free Software Foundation ; either version 2.1 of the License , or ( at
(* your option) any later version, with the OCaml static compilation *)
(* exception. *)
(* *)
(* This library is distributed in the hope that it will be useful, but *)
(* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *)
(* or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more *)
(* details. *)
(* *)
You should have received a copy of the GNU Lesser General Public License
along with this library ; if not , write to the Free Software Foundation ,
Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
(******************************************************************************)
OASIS_START
OASIS_STOP
let =
( * TODO : we should really auto load the env +
let camlmix =
(* TODO: we should really auto load the env + Hashtbl *)
let env =
BaseEnvLight.load ()
in
try
BaseEnvLight.var_get "camlmix" env
with Not_found ->
failwith (Printf.sprintf "camlmix not defined")
;;
rule "camlmix: mlx -> ml"
~prod:"%.ml"
~dep:"%.mlx"
(fun env _build ->
Cmd(S[A camlmix;
A"-c";
A"-co"; P(env "%.ml");
A"-fun";
P(env "%.mlx")]))
;;
*)
Ocamlbuild_plugin.dispatch dispatch_default;;
| null | https://raw.githubusercontent.com/ocaml/oasis2debian/41d268cada4afdac8c906ac99277d7c685bc15ae/myocamlbuild.ml | ocaml | ****************************************************************************
oasis2debian: create and maintain a debian/ directory using _oasis
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
your option) any later version, with the OCaml static compilation
exception.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more
details.
****************************************************************************
TODO: we should really auto load the env + Hashtbl | Copyright ( C ) 2010 , OCamlCore SARL ,
the Free Software Foundation ; either version 2.1 of the License , or ( at
You should have received a copy of the GNU Lesser General Public License
along with this library ; if not , write to the Free Software Foundation ,
Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
OASIS_START
OASIS_STOP
let =
( * TODO : we should really auto load the env +
let camlmix =
let env =
BaseEnvLight.load ()
in
try
BaseEnvLight.var_get "camlmix" env
with Not_found ->
failwith (Printf.sprintf "camlmix not defined")
;;
rule "camlmix: mlx -> ml"
~prod:"%.ml"
~dep:"%.mlx"
(fun env _build ->
Cmd(S[A camlmix;
A"-c";
A"-co"; P(env "%.ml");
A"-fun";
P(env "%.mlx")]))
;;
*)
Ocamlbuild_plugin.dispatch dispatch_default;;
|
411a951def766f1b05b15cdb622aa0c69f75b28e697aedabcd82acbdb7931d53 | cbaggers/cepl | docs-image-formats.lisp | (in-package :cepl.image-formats)
(docs:define-docs
(defun image-formatp
"
This function returns t if the value provided is a keyword that can be found in
*image-formats*
")
(defun valid-image-format-for-buffer-backed-texturep
"
This function returns t if the value provided is a keyword that can be found in
*valid-image-formats-for-buffer-backed-texture*
")
(defun color-renderable-formatp
"
This function returns t if the value provided is a keyword that can be found in
*color-renderable-formats*
")
(defun depth-formatp
"
This function returns t if the value provided is a keyword that can be found in
*depth-formats*
")
(defun stencil-formatp
"
This function returns t if the value provided is a keyword that can be found in
*stencil-formats*
")
(defun depth-stencil-formatp
"
This function returns t if the value provided is a keyword that can be found in
*depth-stencil-formats*
")
(defvar *unsigned-normalized-integer-formats*
"
A list of all of OpenGL's unsigned normalized integer formats
")
(defvar *signed-normalized-integer-formats*
"
A list of all of OpenGL's signed normalized integer formats
")
(defvar *signed-integral-formats*
"
A list of all of OpenGL's signed integral formats
")
(defvar *unsigned-integral-formats*
"
A list of all of OpenGL's unsigned integral formats
")
(defvar *floating-point-formats*
"
A list of all of OpenGL's floating point formats
")
(defvar *regular-color-formats*
"
A list of all of OpenGL's regular color formats
")
(defvar *special-color-formats*
"
A list of all of OpenGL's special color formats
")
(defvar *srgb-color-formats*
"
A list of all of OpenGL's srgb color formats
")
(defvar *red/green-compressed-formats*
"
A list of all of OpenGL's red/green compressed formats
")
(defvar *bptc-compressed-formats*
"
A list of all of OpenGL's bptc compressed formats
")
(defvar *s3tc/dxt-compessed-formats*
"
A list of all of OpenGL's s3tc/dxt compessed formats
")
(defvar *depth-formats*
"
A list of all of OpenGL's depth formats
")
(defvar *stencil-formats*
"
A list of all of OpenGL's stencil formats
")
(defvar *depth-stencil-formats*
"
A list of all of OpenGL's depth stencil formats
")
(defvar *color-renderable-formats*
"
A list of all of OpenGL's color renderable formats
")
(defvar *valid-image-formats-for-buffer-backed-texture*
"
A list of all of OpenGL's valid image formats for buffer backed texture
")
(defvar *image-formats*
"
A list of all of OpenGL's image formats
"))
| null | https://raw.githubusercontent.com/cbaggers/cepl/d1a10b6c8f4cedc07493bf06aef3a56c7b6f8d5b/core/types/docs-image-formats.lisp | lisp | (in-package :cepl.image-formats)
(docs:define-docs
(defun image-formatp
"
This function returns t if the value provided is a keyword that can be found in
*image-formats*
")
(defun valid-image-format-for-buffer-backed-texturep
"
This function returns t if the value provided is a keyword that can be found in
*valid-image-formats-for-buffer-backed-texture*
")
(defun color-renderable-formatp
"
This function returns t if the value provided is a keyword that can be found in
*color-renderable-formats*
")
(defun depth-formatp
"
This function returns t if the value provided is a keyword that can be found in
*depth-formats*
")
(defun stencil-formatp
"
This function returns t if the value provided is a keyword that can be found in
*stencil-formats*
")
(defun depth-stencil-formatp
"
This function returns t if the value provided is a keyword that can be found in
*depth-stencil-formats*
")
(defvar *unsigned-normalized-integer-formats*
"
A list of all of OpenGL's unsigned normalized integer formats
")
(defvar *signed-normalized-integer-formats*
"
A list of all of OpenGL's signed normalized integer formats
")
(defvar *signed-integral-formats*
"
A list of all of OpenGL's signed integral formats
")
(defvar *unsigned-integral-formats*
"
A list of all of OpenGL's unsigned integral formats
")
(defvar *floating-point-formats*
"
A list of all of OpenGL's floating point formats
")
(defvar *regular-color-formats*
"
A list of all of OpenGL's regular color formats
")
(defvar *special-color-formats*
"
A list of all of OpenGL's special color formats
")
(defvar *srgb-color-formats*
"
A list of all of OpenGL's srgb color formats
")
(defvar *red/green-compressed-formats*
"
A list of all of OpenGL's red/green compressed formats
")
(defvar *bptc-compressed-formats*
"
A list of all of OpenGL's bptc compressed formats
")
(defvar *s3tc/dxt-compessed-formats*
"
A list of all of OpenGL's s3tc/dxt compessed formats
")
(defvar *depth-formats*
"
A list of all of OpenGL's depth formats
")
(defvar *stencil-formats*
"
A list of all of OpenGL's stencil formats
")
(defvar *depth-stencil-formats*
"
A list of all of OpenGL's depth stencil formats
")
(defvar *color-renderable-formats*
"
A list of all of OpenGL's color renderable formats
")
(defvar *valid-image-formats-for-buffer-backed-texture*
"
A list of all of OpenGL's valid image formats for buffer backed texture
")
(defvar *image-formats*
"
A list of all of OpenGL's image formats
"))
|
|
5a2a873393ac47c9632f17bcc199d964eba0083144a37cafac946d163435a9d0 | google/haskell-trainings | Solution.hs | Copyright 2021 Google LLC
--
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.
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - type - defaults #
module Solution where
import Internal (codelab)
import Prelude hiding (map, filter, foldr, foldl)
CODELAB 04 : Abstractions
--
-- Have you noticed that we keep using the same pattern? If the list is
-- empty we return a specific value. If it is not, we call a function to
-- combine the element with the result of the recursive calls.
--
This is : if there is a pattern , it can ( must ) be abstracted !
-- Fortunately, some useful functions are here for us.
--
-- To understand the difference between foldr and foldl, remember that the
-- last letter indicates if the "reduction" function is left associative or
-- right associative: foldr goes from right to left, foldl goes from left
-- to right.
--
-- foldl :: (a -> x -> a) -> a -> [x] -> a
-- foldr :: (x -> a -> a) -> a -> [x] -> a
foldl ( - ) 0 [ 1,2,3,4 ] = = ( ( ( 0 - 1 ) - 2 ) - 3 ) - 4 = = -10
foldr ( - ) 0 [ 1,2,3,4 ] = = 1 - ( 2 - ( 3 - ( 4 - 0 ) ) ) = = -2
-- You probably remember this one? Nothing extraordinary here.
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (a:as) = f a : map f as
-- Same thing here for filter, except that we use it to introduce a new
-- syntax: those | are called "guards". They let you specify different
implementations of your function depending on some Boolean
-- value. "otherwise" is not a keyword but simply a constant whose value is
-- True! Try to evaluate "otherwise" in GHCI.
--
-- Simple example of guard usage:
-- abs :: Int -> Int
-- abs x
-- | x < 0 = -x
-- | otherwise = x
filter :: (a -> Bool) -> [a] -> [a]
filter _ [] = []
filter f (x:xs)
| f x = x : filter f xs
| otherwise = filter f xs
-- foldl
foldl ( - ) 0 [ 1,2,3,4 ] = = ( ( ( 0 - 1 ) - 2 ) - 3 ) - 4 = = -10
foldl :: (a -> x -> a) -> a -> [x] -> a
foldl _ a [] = a
foldl f a (x:xs) = foldl f (f a x) xs
-- foldr
foldr ( - ) 0 [ 1,2,3,4 ] = = 1 - ( 2 - ( 3 - ( 4 - 0 ) ) ) = = -2
foldr :: (x -> a -> a) -> a -> [x] -> a
foldr _ a [] = a
foldr f a (x:xs) = f x (foldr f a xs)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
-- BONUS STAGE!
--
For fun , you can try reimplementing the functions in previous codelab with
-- foldr or foldl! For length, remember that the syntax for a lambda function
is ( \arg1 - > value ) .
--
-- You can replace your previous implementation if you want. Otherwise, you can
add new functions ( such as andF , orF ) , and test them by loading your file in
-- GHCI.
--
To go a bit further , you can also try QuickCheck :
--
-- > import Test.QuickCheck
> quickCheck $ \anyList - > and anyList = = andF anyList
--
QuickCheck automatically generates tests based on the types expected
-- (here, list of boolean values).
--
-- It is also worth noting that there is a special syntax for list
comprehension in Haskell , which is at a first glance quite similar to
the syntax of Python 's list comprehension
--
-- Python: [transform(value) for value in container if test(value)]
: [ transform value | value < - container , test value ]
--
-- This allows you to succinctly write your map / filters.
| null | https://raw.githubusercontent.com/google/haskell-trainings/214013fc324fd6c8f63b874a58ead0c1d3e6788c/haskell_101/codelab/04_abstractions/src/Solution.hs | haskell |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Have you noticed that we keep using the same pattern? If the list is
empty we return a specific value. If it is not, we call a function to
combine the element with the result of the recursive calls.
Fortunately, some useful functions are here for us.
To understand the difference between foldr and foldl, remember that the
last letter indicates if the "reduction" function is left associative or
right associative: foldr goes from right to left, foldl goes from left
to right.
foldl :: (a -> x -> a) -> a -> [x] -> a
foldr :: (x -> a -> a) -> a -> [x] -> a
You probably remember this one? Nothing extraordinary here.
Same thing here for filter, except that we use it to introduce a new
syntax: those | are called "guards". They let you specify different
value. "otherwise" is not a keyword but simply a constant whose value is
True! Try to evaluate "otherwise" in GHCI.
Simple example of guard usage:
abs :: Int -> Int
abs x
| x < 0 = -x
| otherwise = x
foldl
foldr
BONUS STAGE!
foldr or foldl! For length, remember that the syntax for a lambda function
You can replace your previous implementation if you want. Otherwise, you can
GHCI.
> import Test.QuickCheck
(here, list of boolean values).
It is also worth noting that there is a special syntax for list
Python: [transform(value) for value in container if test(value)]
This allows you to succinctly write your map / filters. | Copyright 2021 Google LLC
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - type - defaults #
module Solution where
import Internal (codelab)
import Prelude hiding (map, filter, foldr, foldl)
CODELAB 04 : Abstractions
This is : if there is a pattern , it can ( must ) be abstracted !
foldl ( - ) 0 [ 1,2,3,4 ] = = ( ( ( 0 - 1 ) - 2 ) - 3 ) - 4 = = -10
foldr ( - ) 0 [ 1,2,3,4 ] = = 1 - ( 2 - ( 3 - ( 4 - 0 ) ) ) = = -2
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (a:as) = f a : map f as
implementations of your function depending on some Boolean
filter :: (a -> Bool) -> [a] -> [a]
filter _ [] = []
filter f (x:xs)
| f x = x : filter f xs
| otherwise = filter f xs
foldl ( - ) 0 [ 1,2,3,4 ] = = ( ( ( 0 - 1 ) - 2 ) - 3 ) - 4 = = -10
foldl :: (a -> x -> a) -> a -> [x] -> a
foldl _ a [] = a
foldl f a (x:xs) = foldl f (f a x) xs
foldr ( - ) 0 [ 1,2,3,4 ] = = 1 - ( 2 - ( 3 - ( 4 - 0 ) ) ) = = -2
foldr :: (x -> a -> a) -> a -> [x] -> a
foldr _ a [] = a
foldr f a (x:xs) = f x (foldr f a xs)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
For fun , you can try reimplementing the functions in previous codelab with
is ( \arg1 - > value ) .
add new functions ( such as andF , orF ) , and test them by loading your file in
To go a bit further , you can also try QuickCheck :
> quickCheck $ \anyList - > and anyList = = andF anyList
QuickCheck automatically generates tests based on the types expected
comprehension in Haskell , which is at a first glance quite similar to
the syntax of Python 's list comprehension
: [ transform value | value < - container , test value ]
|
9c5396b1e4a6105316b54ebf01052ac3055f139866178eacf158794ed8c158b3 | quephird/fun-with-quil | cityscape.clj | (ns fun-with-quil.sketches.cityscape
(:require [quil.core :as q :include-macros true]
[quil.middleware :as m])
(:import [processing.core PGraphics]))
(defn make-windows [n]
(into [] (repeatedly n (fn [] (rand-int 3)))))
(defn- make-skyscraper []
(let [storeys (+ 10 (rand-int 20))
windows-per-floor (+ 4 (rand-int 4))
windows (make-windows (* storeys windows-per-floor))]
{:brick-color (rand-int 50)
:storeys storeys
:windows-per-floor windows-per-floor
:windows windows
:lights-on-top (rand-int 3)
:light-color ([[200 0 0] [200 200 0] [0 200 0] [200 0 200]](rand-int 4))})
)
; Give x,y coords for each skyscraper; there should be gaps between buildings
(defn- make-skyscrapers [n]
(into [] (for [i (range n)] [i (make-skyscraper)])))
(defn setup []
(q/smooth)
(q/no-stroke)
(q/background 0)
(q/no-loop))
(defn stars [sky-w sky-h]
(let [star-color [255 240 210]]
(apply q/stroke star-color)
(q/stroke-weight 4)
(dotimes [i 5]
(let [star-x (q/random sky-w)
star-y (q/random (* 0.7 sky-h))]
(q/point star-x star-y)))))
(defn moon [sky-w sky-h]
(let [moon-x (q/random sky-w)
moon-y (q/random (* 0.5 sky-h))
moon-d 100
moon-color [255 240 210]
shadow-color [140 120 100]]
(q/no-stroke)
(apply q/fill moon-color)
(q/ellipse moon-x moon-y 100 100)
(q/push-matrix)
(q/translate moon-x moon-y)
(q/rotate (q/radians -20))
(apply q/fill shadow-color)
(q/arc 0 0 100 100 (q/radians 100) (q/radians 260))
(q/arc (* -0.2 moon-d) 0 moon-d moon-d (q/radians -80) (q/radians 80))
(q/pop-matrix)))
(defn sunset [sky-w sky-h]
(let [top-color [0 0 127]
bottom-color [127 80 0]]
(q/no-stroke)
(q/begin-shape :quads)
(apply q/fill top-color)
(q/vertex 0 0)
(q/vertex sky-w 0)
(apply q/fill bottom-color)
(q/vertex sky-w sky-h)
(q/vertex 0 sky-h)
(q/end-shape))
; Maybe simulate clouds?
)
; Render lights
; Rippling effect?
; Combine draw-skyscraper and draw-reflection somehow
(defn- draw-skyscraper [brick-color storeys windows-per-floor windows]
(q/no-stroke)
(q/fill brick-color)
(q/rect 0 0 (* windows-per-floor 10) (* storeys -10))
(q/push-matrix)
(q/fill 255 255 200)
(dotimes [s storeys]
(q/push-matrix)
(dotimes [w windows-per-floor]
(if (zero? (windows (+ w (* s windows-per-floor))))
(q/rect 0 0 5 -5))
(q/translate 10 0))
(q/pop-matrix)
(q/translate 0 -10))
(q/pop-matrix)
)
(defn- draw-skyscrapers [skyscrapers]
(q/push-matrix)
(doseq [[_ {:keys [brick-color storeys windows-per-floor windows]}] skyscrapers]
(draw-skyscraper brick-color storeys windows-per-floor windows)
(q/translate (* windows-per-floor 10) 0)
)
(q/pop-matrix))
(defn- draw-reflections [skyscrapers w h]
(let [pg (q/create-graphics w h)
img (q/create-image w h :rgb)]
(.beginDraw pg)
(.pushMatrix pg)
(doseq [[i {:keys [brick-color storeys windows-per-floor windows]}] skyscrapers]
(let [muted-brick-color (int (* 0.2 brick-color))
muted-window-color (map #(* % 0.2) [255 255 200])]
(.noStroke pg)
(.fill pg brick-color)
(.rect pg 0 0 (* windows-per-floor 10) (* storeys 10))
(.pushMatrix pg)
; (.fill pg 255 255 200)
(.fill pg 50 50 40)
(dotimes [s storeys]
(.pushMatrix pg)
(dotimes [w windows-per-floor]
(if (zero? (windows (+ w (* s windows-per-floor))))
(.rect pg 0 0 5 5))
(.translate pg 10 0))
(.popMatrix pg)
(.translate pg 0 10))
(.popMatrix pg)
)
(.translate pg (* windows-per-floor 10) 0)
)
(.popMatrix pg)
(.loadPixels pg)
(let [pg-pixels (.pixels pg)
img-pixels (.pixels pg)
max-i (dec (count pg-pixels))
a 25
p 50]
(dotimes [i 700000] ; This is to avoid an IndexOutOfBoundsException
(let [x (mod i w)
y (quot i w)
source-i (+ x (* y w) (rand-int 10) (* a (q/sin (* q/TWO-PI (/ y (+ p (rand-int 5)))))))]
(aset img-pixels i (aget pg-pixels source-i))
)
)
(set! (.pixels img) img-pixels)
)
(q/image img 0 0)))
(defn- water [w h]
(let [water-color [255 255 255]]
( let [ water - color [ 0 25 30 ] ]
(q/no-stroke)
(apply q/fill water-color)
(q/rect 0 0 w h))
)
; Blinking windows?
(defn draw []
(let [w (q/width)
h (q/height)
sky-h (* h 0.6)
water-h (- h sky-h)
skyscrapers (make-skyscrapers 40)]
(q/translate 0 0)
(sunset w sky-h)
(moon w sky-h)
(stars w sky-h)
(q/translate 0 sky-h)
(water w water-h)
(draw-skyscrapers skyscrapers)
(draw-reflections skyscrapers w water-h)
(q/save "cityscape.png")
))
(q/defsketch cityscape
:title "cityscape"
:setup setup
:renderer :p3d
:draw draw
:size [1920 1080])
| null | https://raw.githubusercontent.com/quephird/fun-with-quil/3b3a6885771f5a1a4cffeb8379f05a28048a1616/src/fun_with_quil/sketches/cityscape.clj | clojure | Give x,y coords for each skyscraper; there should be gaps between buildings
Maybe simulate clouds?
Render lights
Rippling effect?
Combine draw-skyscraper and draw-reflection somehow
(.fill pg 255 255 200)
This is to avoid an IndexOutOfBoundsException
Blinking windows? | (ns fun-with-quil.sketches.cityscape
(:require [quil.core :as q :include-macros true]
[quil.middleware :as m])
(:import [processing.core PGraphics]))
(defn make-windows [n]
(into [] (repeatedly n (fn [] (rand-int 3)))))
(defn- make-skyscraper []
(let [storeys (+ 10 (rand-int 20))
windows-per-floor (+ 4 (rand-int 4))
windows (make-windows (* storeys windows-per-floor))]
{:brick-color (rand-int 50)
:storeys storeys
:windows-per-floor windows-per-floor
:windows windows
:lights-on-top (rand-int 3)
:light-color ([[200 0 0] [200 200 0] [0 200 0] [200 0 200]](rand-int 4))})
)
(defn- make-skyscrapers [n]
(into [] (for [i (range n)] [i (make-skyscraper)])))
(defn setup []
(q/smooth)
(q/no-stroke)
(q/background 0)
(q/no-loop))
(defn stars [sky-w sky-h]
(let [star-color [255 240 210]]
(apply q/stroke star-color)
(q/stroke-weight 4)
(dotimes [i 5]
(let [star-x (q/random sky-w)
star-y (q/random (* 0.7 sky-h))]
(q/point star-x star-y)))))
(defn moon [sky-w sky-h]
(let [moon-x (q/random sky-w)
moon-y (q/random (* 0.5 sky-h))
moon-d 100
moon-color [255 240 210]
shadow-color [140 120 100]]
(q/no-stroke)
(apply q/fill moon-color)
(q/ellipse moon-x moon-y 100 100)
(q/push-matrix)
(q/translate moon-x moon-y)
(q/rotate (q/radians -20))
(apply q/fill shadow-color)
(q/arc 0 0 100 100 (q/radians 100) (q/radians 260))
(q/arc (* -0.2 moon-d) 0 moon-d moon-d (q/radians -80) (q/radians 80))
(q/pop-matrix)))
(defn sunset [sky-w sky-h]
(let [top-color [0 0 127]
bottom-color [127 80 0]]
(q/no-stroke)
(q/begin-shape :quads)
(apply q/fill top-color)
(q/vertex 0 0)
(q/vertex sky-w 0)
(apply q/fill bottom-color)
(q/vertex sky-w sky-h)
(q/vertex 0 sky-h)
(q/end-shape))
)
(defn- draw-skyscraper [brick-color storeys windows-per-floor windows]
(q/no-stroke)
(q/fill brick-color)
(q/rect 0 0 (* windows-per-floor 10) (* storeys -10))
(q/push-matrix)
(q/fill 255 255 200)
(dotimes [s storeys]
(q/push-matrix)
(dotimes [w windows-per-floor]
(if (zero? (windows (+ w (* s windows-per-floor))))
(q/rect 0 0 5 -5))
(q/translate 10 0))
(q/pop-matrix)
(q/translate 0 -10))
(q/pop-matrix)
)
(defn- draw-skyscrapers [skyscrapers]
(q/push-matrix)
(doseq [[_ {:keys [brick-color storeys windows-per-floor windows]}] skyscrapers]
(draw-skyscraper brick-color storeys windows-per-floor windows)
(q/translate (* windows-per-floor 10) 0)
)
(q/pop-matrix))
(defn- draw-reflections [skyscrapers w h]
(let [pg (q/create-graphics w h)
img (q/create-image w h :rgb)]
(.beginDraw pg)
(.pushMatrix pg)
(doseq [[i {:keys [brick-color storeys windows-per-floor windows]}] skyscrapers]
(let [muted-brick-color (int (* 0.2 brick-color))
muted-window-color (map #(* % 0.2) [255 255 200])]
(.noStroke pg)
(.fill pg brick-color)
(.rect pg 0 0 (* windows-per-floor 10) (* storeys 10))
(.pushMatrix pg)
(.fill pg 50 50 40)
(dotimes [s storeys]
(.pushMatrix pg)
(dotimes [w windows-per-floor]
(if (zero? (windows (+ w (* s windows-per-floor))))
(.rect pg 0 0 5 5))
(.translate pg 10 0))
(.popMatrix pg)
(.translate pg 0 10))
(.popMatrix pg)
)
(.translate pg (* windows-per-floor 10) 0)
)
(.popMatrix pg)
(.loadPixels pg)
(let [pg-pixels (.pixels pg)
img-pixels (.pixels pg)
max-i (dec (count pg-pixels))
a 25
p 50]
(let [x (mod i w)
y (quot i w)
source-i (+ x (* y w) (rand-int 10) (* a (q/sin (* q/TWO-PI (/ y (+ p (rand-int 5)))))))]
(aset img-pixels i (aget pg-pixels source-i))
)
)
(set! (.pixels img) img-pixels)
)
(q/image img 0 0)))
(defn- water [w h]
(let [water-color [255 255 255]]
( let [ water - color [ 0 25 30 ] ]
(q/no-stroke)
(apply q/fill water-color)
(q/rect 0 0 w h))
)
(defn draw []
(let [w (q/width)
h (q/height)
sky-h (* h 0.6)
water-h (- h sky-h)
skyscrapers (make-skyscrapers 40)]
(q/translate 0 0)
(sunset w sky-h)
(moon w sky-h)
(stars w sky-h)
(q/translate 0 sky-h)
(water w water-h)
(draw-skyscrapers skyscrapers)
(draw-reflections skyscrapers w water-h)
(q/save "cityscape.png")
))
(q/defsketch cityscape
:title "cityscape"
:setup setup
:renderer :p3d
:draw draw
:size [1920 1080])
|
651aad97dd7e0b7576a0cc08635b3cd314124d4457e1a70c9b7b6661191f0854 | RichiH/git-annex | Alert.hs | git - annex assistant alerts
-
- Copyright 2012 - 2014 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2012-2014 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
# LANGUAGE OverloadedStrings , CPP , BangPatterns #
module Assistant.Alert where
import Annex.Common
import Assistant.Types.Alert
import Assistant.Alert.Utility
import qualified Remote
import Utility.Tense
import Types.Transfer
import Types.Distribution
import Git.Types (RemoteName)
import Data.String
import qualified Data.Text as T
import qualified Control.Exception as E
#ifdef WITH_WEBAPP
import Assistant.DaemonStatus
import Assistant.WebApp.Types
import Assistant.WebApp (renderUrl)
#endif
import Assistant.Monad
import Assistant.Types.UrlRenderer
Makes a button for an alert that opens a Route .
-
- If autoclose is set , the button will close the alert it 's
- attached to when clicked .
-
- If autoclose is set, the button will close the alert it's
- attached to when clicked. -}
#ifdef WITH_WEBAPP
mkAlertButton :: Bool -> T.Text -> UrlRenderer -> Route WebApp -> Assistant AlertButton
mkAlertButton autoclose label urlrenderer route = do
close <- asIO1 removeAlert
url <- liftIO $ renderUrl urlrenderer route []
return $ AlertButton
{ buttonLabel = label
, buttonUrl = url
, buttonAction = if autoclose then Just close else Nothing
, buttonPrimary = True
}
#endif
renderData :: Alert -> TenseText
renderData = tenseWords . alertData
baseActivityAlert :: Alert
baseActivityAlert = Alert
{ alertClass = Activity
, alertHeader = Nothing
, alertMessageRender = renderData
, alertData = []
, alertCounter = 0
, alertBlockDisplay = False
, alertClosable = False
, alertPriority = Medium
, alertIcon = Just ActivityIcon
, alertCombiner = Nothing
, alertName = Nothing
, alertButtons = []
}
warningAlert :: String -> String -> Alert
warningAlert name msg = Alert
{ alertClass = Warning
, alertHeader = Just $ tenseWords ["warning"]
, alertMessageRender = renderData
, alertData = [UnTensed $ T.pack msg]
, alertCounter = 0
, alertBlockDisplay = True
, alertClosable = True
, alertPriority = High
, alertIcon = Just ErrorIcon
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertName = Just $ WarningAlert name
, alertButtons = []
}
errorAlert :: String -> [AlertButton] -> Alert
errorAlert msg buttons = Alert
{ alertClass = Error
, alertHeader = Nothing
, alertMessageRender = renderData
, alertData = [UnTensed $ T.pack msg]
, alertCounter = 0
, alertBlockDisplay = True
, alertClosable = True
, alertPriority = Pinned
, alertIcon = Just ErrorIcon
, alertCombiner = Nothing
, alertName = Nothing
, alertButtons = buttons
}
activityAlert :: Maybe TenseText -> [TenseChunk] -> Alert
activityAlert header dat = baseActivityAlert
{ alertHeader = header
, alertData = dat
}
startupScanAlert :: Alert
startupScanAlert = activityAlert Nothing
[Tensed "Performing" "Performed", "startup scan"]
{- Displayed when a shutdown is occurring, so will be seen after shutdown
- has happened. -}
shutdownAlert :: Alert
shutdownAlert = warningAlert "shutdown" "git-annex has been shut down"
commitAlert :: Alert
commitAlert = activityAlert Nothing
[Tensed "Committing" "Committed", "changes to git"]
showRemotes :: [RemoteName] -> TenseChunk
showRemotes = UnTensed . T.intercalate ", " . map T.pack
syncAlert :: [Remote] -> Alert
syncAlert = syncAlert' . map Remote.name
syncAlert' :: [RemoteName] -> Alert
syncAlert' rs = baseActivityAlert
{ alertName = Just SyncAlert
, alertHeader = Just $ tenseWords
[Tensed "Syncing" "Synced", "with", showRemotes rs]
, alertPriority = Low
, alertIcon = Just SyncIcon
}
syncResultAlert :: [Remote] -> [Remote] -> Alert
syncResultAlert succeeded failed = syncResultAlert'
(map Remote.name succeeded)
(map Remote.name failed)
syncResultAlert' :: [RemoteName] -> [RemoteName] -> Alert
syncResultAlert' succeeded failed = makeAlertFiller (not $ null succeeded) $
baseActivityAlert
{ alertName = Just SyncAlert
, alertHeader = Just $ tenseWords msg
}
where
msg
| null succeeded = ["Failed to sync with", showRemotes failed]
| null failed = ["Synced with", showRemotes succeeded]
| otherwise =
[ "Synced with", showRemotes succeeded
, "but not with", showRemotes failed
]
sanityCheckAlert :: Alert
sanityCheckAlert = activityAlert
(Just $ tenseWords [Tensed "Running" "Ran", "daily sanity check"])
["to make sure everything is ok."]
sanityCheckFixAlert :: String -> Alert
sanityCheckFixAlert msg = Alert
{ alertClass = Warning
, alertHeader = Just $ tenseWords ["Fixed a problem"]
, alertMessageRender = render
, alertData = [UnTensed $ T.pack msg]
, alertCounter = 0
, alertBlockDisplay = True
, alertPriority = High
, alertClosable = True
, alertIcon = Just ErrorIcon
, alertName = Just SanityCheckFixAlert
, alertCombiner = Just $ dataCombiner (++)
, alertButtons = []
}
where
render alert = tenseWords $ alerthead : alertData alert ++ [alertfoot]
alerthead = "The daily sanity check found and fixed a problem:"
alertfoot = "If these problems persist, consider filing a bug report."
fsckingAlert :: AlertButton -> Maybe Remote -> Alert
fsckingAlert button mr = baseActivityAlert
{ alertData = case mr of
Nothing -> [ UnTensed $ T.pack $ "Consistency check in progress" ]
Just r -> [ UnTensed $ T.pack $ "Consistency check of " ++ Remote.name r ++ " in progress"]
, alertButtons = [button]
}
showFscking :: UrlRenderer -> Maybe Remote -> IO (Either E.SomeException a) -> Assistant a
showFscking urlrenderer mr a = do
#ifdef WITH_WEBAPP
button <- mkAlertButton False (T.pack "Configure") urlrenderer ConfigFsckR
r <- alertDuring (fsckingAlert button mr) $
liftIO a
#else
r <- liftIO a
#endif
either (liftIO . E.throwIO) return r
notFsckedNudge :: UrlRenderer -> Maybe Remote -> Assistant ()
#ifdef WITH_WEBAPP
notFsckedNudge urlrenderer mr = do
button <- mkAlertButton True (T.pack "Configure") urlrenderer ConfigFsckR
void $ addAlert (notFsckedAlert mr button)
#else
notFsckedNudge _ _ = noop
#endif
notFsckedAlert :: Maybe Remote -> AlertButton -> Alert
notFsckedAlert mr button = Alert
{ alertHeader = Just $ fromString $ concat
[ "You should enable consistency checking to protect your data"
, maybe "" (\r -> " in " ++ Remote.name r) mr
, "."
]
, alertIcon = Just InfoIcon
, alertPriority = High
, alertButtons = [button]
, alertClosable = True
, alertClass = Message
, alertMessageRender = renderData
, alertCounter = 0
, alertBlockDisplay = True
, alertName = Just NotFsckedAlert
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertData = []
}
baseUpgradeAlert :: [AlertButton] -> TenseText -> Alert
baseUpgradeAlert buttons message = Alert
{ alertHeader = Just message
, alertIcon = Just UpgradeIcon
, alertPriority = High
, alertButtons = buttons
, alertClosable = True
, alertClass = Message
, alertMessageRender = renderData
, alertCounter = 0
, alertBlockDisplay = True
, alertName = Just UpgradeAlert
, alertCombiner = Just $ fullCombiner $ \new _old -> new
, alertData = []
}
canUpgradeAlert :: AlertPriority -> GitAnnexVersion -> AlertButton -> Alert
canUpgradeAlert priority version button =
(baseUpgradeAlert [button] $ fromString msg)
{ alertPriority = priority
, alertData = [fromString $ " (version " ++ version ++ ")"]
}
where
msg = if priority >= High
then "An important upgrade of git-annex is available!"
else "An upgrade of git-annex is available."
upgradeReadyAlert :: AlertButton -> Alert
upgradeReadyAlert button = baseUpgradeAlert [button] $
fromString "A new version of git-annex has been installed."
upgradingAlert :: Alert
upgradingAlert = activityAlert Nothing [ fromString "Upgrading git-annex" ]
upgradeFinishedAlert :: Maybe AlertButton -> GitAnnexVersion -> Alert
upgradeFinishedAlert button version =
baseUpgradeAlert (maybeToList button) $ fromString $
"Finished upgrading git-annex to version " ++ version
upgradeFailedAlert :: String -> Alert
upgradeFailedAlert msg = (errorAlert msg [])
{ alertHeader = Just $ fromString "Upgrade failed." }
unusedFilesAlert :: [AlertButton] -> String -> Alert
unusedFilesAlert buttons message = Alert
{ alertHeader = Just $ fromString $ unwords
[ "Old and deleted files are piling up --"
, message
]
, alertIcon = Just InfoIcon
, alertPriority = High
, alertButtons = buttons
, alertClosable = True
, alertClass = Message
, alertMessageRender = renderData
, alertCounter = 0
, alertBlockDisplay = True
, alertName = Just UnusedFilesAlert
, alertCombiner = Just $ fullCombiner $ \new _old -> new
, alertData = []
}
brokenRepositoryAlert :: [AlertButton] -> Alert
brokenRepositoryAlert = errorAlert "Serious problems have been detected with your repository. This needs your immediate attention!"
repairingAlert :: String -> Alert
repairingAlert repodesc = activityAlert Nothing
[ Tensed "Attempting to repair" "Repaired"
, UnTensed $ T.pack repodesc
]
pairingAlert :: AlertButton -> Alert
pairingAlert button = baseActivityAlert
{ alertData = [ UnTensed "Pairing in progress" ]
, alertPriority = High
, alertButtons = [button]
}
pairRequestReceivedAlert :: String -> AlertButton -> Alert
pairRequestReceivedAlert who button = Alert
{ alertClass = Message
, alertHeader = Nothing
, alertMessageRender = renderData
, alertData = [UnTensed $ T.pack $ who ++ " is sending a pair request."]
, alertCounter = 0
, alertBlockDisplay = False
, alertPriority = High
, alertClosable = True
, alertIcon = Just InfoIcon
, alertName = Just $ PairAlert who
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertButtons = [button]
}
pairRequestAcknowledgedAlert :: String -> Maybe AlertButton -> Alert
pairRequestAcknowledgedAlert who button = baseActivityAlert
{ alertData = ["Pairing with", UnTensed (T.pack who), Tensed "in progress" "complete"]
, alertPriority = High
, alertName = Just $ PairAlert who
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertButtons = maybeToList button
}
connectionNeededAlert :: AlertButton -> Alert
connectionNeededAlert button = Alert
{ alertHeader = Just "Share with friends, and keep your devices in sync across the cloud."
, alertIcon = Just ConnectionIcon
, alertPriority = High
, alertButtons = [button]
, alertClosable = True
, alertClass = Message
, alertMessageRender = renderData
, alertCounter = 0
, alertBlockDisplay = True
, alertName = Just ConnectionNeededAlert
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertData = []
}
cloudRepoNeededAlert :: Maybe String -> AlertButton -> Alert
cloudRepoNeededAlert friendname button = Alert
{ alertHeader = Just $ fromString $ unwords
[ "Unable to download files from"
, (fromMaybe "your other devices" friendname) ++ "."
]
, alertIcon = Just ErrorIcon
, alertPriority = High
, alertButtons = [button]
, alertClosable = True
, alertClass = Message
, alertMessageRender = renderData
, alertCounter = 0
, alertBlockDisplay = True
, alertName = Just $ CloudRepoNeededAlert
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertData = []
}
remoteRemovalAlert :: String -> AlertButton -> Alert
remoteRemovalAlert desc button = Alert
{ alertHeader = Just $ fromString $
"The repository \"" ++ desc ++
"\" has been emptied, and can now be removed."
, alertIcon = Just InfoIcon
, alertPriority = High
, alertButtons = [button]
, alertClosable = True
, alertClass = Message
, alertMessageRender = renderData
, alertCounter = 0
, alertBlockDisplay = True
, alertName = Just $ RemoteRemovalAlert desc
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertData = []
}
{- Show a message that relates to a list of files.
-
- The most recent several files are shown, and a count of any others. -}
fileAlert :: TenseChunk -> [FilePath] -> Alert
fileAlert msg files = (activityAlert Nothing shortfiles)
{ alertName = Just $ FileAlert msg
, alertMessageRender = renderer
, alertCounter = counter
, alertCombiner = Just $ fullCombiner combiner
}
where
maxfilesshown = 10
(!somefiles, !counter) = splitcounter (dedupadjacent files)
!shortfiles = map (fromString . shortFile . takeFileName) somefiles
renderer alert = tenseWords $ msg : alertData alert ++ showcounter
where
showcounter = case alertCounter alert of
0 -> []
_ -> [fromString $ "and " ++ show (alertCounter alert) ++ " other files"]
dedupadjacent (x:y:rest)
| x == y = dedupadjacent (y:rest)
| otherwise = x : dedupadjacent (y:rest)
dedupadjacent (x:[]) = [x]
dedupadjacent [] = []
Note that this ensures the counter is never 1 ; no need to say
- " 1 file " when the filename could be shown .
- "1 file" when the filename could be shown. -}
splitcounter l
| length l <= maxfilesshown = (l, 0)
| otherwise =
let (keep, rest) = splitAt (maxfilesshown - 1) l
in (keep, length rest)
combiner new old =
let (!fs, n) = splitcounter $
dedupadjacent $ alertData new ++ alertData old
!cnt = n + alertCounter new + alertCounter old
in old
{ alertData = fs
, alertCounter = cnt
}
addFileAlert :: [FilePath] -> Alert
addFileAlert = fileAlert (Tensed "Adding" "Added")
{- This is only used as a success alert after a transfer, not during it. -}
transferFileAlert :: Direction -> Bool -> FilePath -> Alert
transferFileAlert direction True file
| direction == Upload = fileAlert "Uploaded" [file]
| otherwise = fileAlert "Downloaded" [file]
transferFileAlert direction False file
| direction == Upload = fileAlert "Upload failed" [file]
| otherwise = fileAlert "Download failed" [file]
dataCombiner :: ([TenseChunk] -> [TenseChunk] -> [TenseChunk]) -> AlertCombiner
dataCombiner combiner = fullCombiner $
\new old -> old { alertData = alertData new `combiner` alertData old }
fullCombiner :: (Alert -> Alert -> Alert) -> AlertCombiner
fullCombiner combiner new old
| alertClass new /= alertClass old = Nothing
| alertName new == alertName old =
Just $! new `combiner` old
| otherwise = Nothing
shortFile :: FilePath -> String
shortFile f
| len < maxlen = f
| otherwise = take half f ++ ".." ++ drop (len - half) f
where
len = length f
maxlen = 20
half = (maxlen - 2) `div` 2
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Assistant/Alert.hs | haskell | Displayed when a shutdown is occurring, so will be seen after shutdown
- has happened.
Show a message that relates to a list of files.
-
- The most recent several files are shown, and a count of any others.
This is only used as a success alert after a transfer, not during it. | git - annex assistant alerts
-
- Copyright 2012 - 2014 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2012-2014 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
# LANGUAGE OverloadedStrings , CPP , BangPatterns #
module Assistant.Alert where
import Annex.Common
import Assistant.Types.Alert
import Assistant.Alert.Utility
import qualified Remote
import Utility.Tense
import Types.Transfer
import Types.Distribution
import Git.Types (RemoteName)
import Data.String
import qualified Data.Text as T
import qualified Control.Exception as E
#ifdef WITH_WEBAPP
import Assistant.DaemonStatus
import Assistant.WebApp.Types
import Assistant.WebApp (renderUrl)
#endif
import Assistant.Monad
import Assistant.Types.UrlRenderer
Makes a button for an alert that opens a Route .
-
- If autoclose is set , the button will close the alert it 's
- attached to when clicked .
-
- If autoclose is set, the button will close the alert it's
- attached to when clicked. -}
#ifdef WITH_WEBAPP
mkAlertButton :: Bool -> T.Text -> UrlRenderer -> Route WebApp -> Assistant AlertButton
mkAlertButton autoclose label urlrenderer route = do
close <- asIO1 removeAlert
url <- liftIO $ renderUrl urlrenderer route []
return $ AlertButton
{ buttonLabel = label
, buttonUrl = url
, buttonAction = if autoclose then Just close else Nothing
, buttonPrimary = True
}
#endif
renderData :: Alert -> TenseText
renderData = tenseWords . alertData
baseActivityAlert :: Alert
baseActivityAlert = Alert
{ alertClass = Activity
, alertHeader = Nothing
, alertMessageRender = renderData
, alertData = []
, alertCounter = 0
, alertBlockDisplay = False
, alertClosable = False
, alertPriority = Medium
, alertIcon = Just ActivityIcon
, alertCombiner = Nothing
, alertName = Nothing
, alertButtons = []
}
warningAlert :: String -> String -> Alert
warningAlert name msg = Alert
{ alertClass = Warning
, alertHeader = Just $ tenseWords ["warning"]
, alertMessageRender = renderData
, alertData = [UnTensed $ T.pack msg]
, alertCounter = 0
, alertBlockDisplay = True
, alertClosable = True
, alertPriority = High
, alertIcon = Just ErrorIcon
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertName = Just $ WarningAlert name
, alertButtons = []
}
errorAlert :: String -> [AlertButton] -> Alert
errorAlert msg buttons = Alert
{ alertClass = Error
, alertHeader = Nothing
, alertMessageRender = renderData
, alertData = [UnTensed $ T.pack msg]
, alertCounter = 0
, alertBlockDisplay = True
, alertClosable = True
, alertPriority = Pinned
, alertIcon = Just ErrorIcon
, alertCombiner = Nothing
, alertName = Nothing
, alertButtons = buttons
}
activityAlert :: Maybe TenseText -> [TenseChunk] -> Alert
activityAlert header dat = baseActivityAlert
{ alertHeader = header
, alertData = dat
}
startupScanAlert :: Alert
startupScanAlert = activityAlert Nothing
[Tensed "Performing" "Performed", "startup scan"]
shutdownAlert :: Alert
shutdownAlert = warningAlert "shutdown" "git-annex has been shut down"
commitAlert :: Alert
commitAlert = activityAlert Nothing
[Tensed "Committing" "Committed", "changes to git"]
showRemotes :: [RemoteName] -> TenseChunk
showRemotes = UnTensed . T.intercalate ", " . map T.pack
syncAlert :: [Remote] -> Alert
syncAlert = syncAlert' . map Remote.name
syncAlert' :: [RemoteName] -> Alert
syncAlert' rs = baseActivityAlert
{ alertName = Just SyncAlert
, alertHeader = Just $ tenseWords
[Tensed "Syncing" "Synced", "with", showRemotes rs]
, alertPriority = Low
, alertIcon = Just SyncIcon
}
syncResultAlert :: [Remote] -> [Remote] -> Alert
syncResultAlert succeeded failed = syncResultAlert'
(map Remote.name succeeded)
(map Remote.name failed)
syncResultAlert' :: [RemoteName] -> [RemoteName] -> Alert
syncResultAlert' succeeded failed = makeAlertFiller (not $ null succeeded) $
baseActivityAlert
{ alertName = Just SyncAlert
, alertHeader = Just $ tenseWords msg
}
where
msg
| null succeeded = ["Failed to sync with", showRemotes failed]
| null failed = ["Synced with", showRemotes succeeded]
| otherwise =
[ "Synced with", showRemotes succeeded
, "but not with", showRemotes failed
]
sanityCheckAlert :: Alert
sanityCheckAlert = activityAlert
(Just $ tenseWords [Tensed "Running" "Ran", "daily sanity check"])
["to make sure everything is ok."]
sanityCheckFixAlert :: String -> Alert
sanityCheckFixAlert msg = Alert
{ alertClass = Warning
, alertHeader = Just $ tenseWords ["Fixed a problem"]
, alertMessageRender = render
, alertData = [UnTensed $ T.pack msg]
, alertCounter = 0
, alertBlockDisplay = True
, alertPriority = High
, alertClosable = True
, alertIcon = Just ErrorIcon
, alertName = Just SanityCheckFixAlert
, alertCombiner = Just $ dataCombiner (++)
, alertButtons = []
}
where
render alert = tenseWords $ alerthead : alertData alert ++ [alertfoot]
alerthead = "The daily sanity check found and fixed a problem:"
alertfoot = "If these problems persist, consider filing a bug report."
fsckingAlert :: AlertButton -> Maybe Remote -> Alert
fsckingAlert button mr = baseActivityAlert
{ alertData = case mr of
Nothing -> [ UnTensed $ T.pack $ "Consistency check in progress" ]
Just r -> [ UnTensed $ T.pack $ "Consistency check of " ++ Remote.name r ++ " in progress"]
, alertButtons = [button]
}
showFscking :: UrlRenderer -> Maybe Remote -> IO (Either E.SomeException a) -> Assistant a
showFscking urlrenderer mr a = do
#ifdef WITH_WEBAPP
button <- mkAlertButton False (T.pack "Configure") urlrenderer ConfigFsckR
r <- alertDuring (fsckingAlert button mr) $
liftIO a
#else
r <- liftIO a
#endif
either (liftIO . E.throwIO) return r
notFsckedNudge :: UrlRenderer -> Maybe Remote -> Assistant ()
#ifdef WITH_WEBAPP
notFsckedNudge urlrenderer mr = do
button <- mkAlertButton True (T.pack "Configure") urlrenderer ConfigFsckR
void $ addAlert (notFsckedAlert mr button)
#else
notFsckedNudge _ _ = noop
#endif
notFsckedAlert :: Maybe Remote -> AlertButton -> Alert
notFsckedAlert mr button = Alert
{ alertHeader = Just $ fromString $ concat
[ "You should enable consistency checking to protect your data"
, maybe "" (\r -> " in " ++ Remote.name r) mr
, "."
]
, alertIcon = Just InfoIcon
, alertPriority = High
, alertButtons = [button]
, alertClosable = True
, alertClass = Message
, alertMessageRender = renderData
, alertCounter = 0
, alertBlockDisplay = True
, alertName = Just NotFsckedAlert
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertData = []
}
baseUpgradeAlert :: [AlertButton] -> TenseText -> Alert
baseUpgradeAlert buttons message = Alert
{ alertHeader = Just message
, alertIcon = Just UpgradeIcon
, alertPriority = High
, alertButtons = buttons
, alertClosable = True
, alertClass = Message
, alertMessageRender = renderData
, alertCounter = 0
, alertBlockDisplay = True
, alertName = Just UpgradeAlert
, alertCombiner = Just $ fullCombiner $ \new _old -> new
, alertData = []
}
canUpgradeAlert :: AlertPriority -> GitAnnexVersion -> AlertButton -> Alert
canUpgradeAlert priority version button =
(baseUpgradeAlert [button] $ fromString msg)
{ alertPriority = priority
, alertData = [fromString $ " (version " ++ version ++ ")"]
}
where
msg = if priority >= High
then "An important upgrade of git-annex is available!"
else "An upgrade of git-annex is available."
upgradeReadyAlert :: AlertButton -> Alert
upgradeReadyAlert button = baseUpgradeAlert [button] $
fromString "A new version of git-annex has been installed."
upgradingAlert :: Alert
upgradingAlert = activityAlert Nothing [ fromString "Upgrading git-annex" ]
upgradeFinishedAlert :: Maybe AlertButton -> GitAnnexVersion -> Alert
upgradeFinishedAlert button version =
baseUpgradeAlert (maybeToList button) $ fromString $
"Finished upgrading git-annex to version " ++ version
upgradeFailedAlert :: String -> Alert
upgradeFailedAlert msg = (errorAlert msg [])
{ alertHeader = Just $ fromString "Upgrade failed." }
unusedFilesAlert :: [AlertButton] -> String -> Alert
unusedFilesAlert buttons message = Alert
{ alertHeader = Just $ fromString $ unwords
[ "Old and deleted files are piling up --"
, message
]
, alertIcon = Just InfoIcon
, alertPriority = High
, alertButtons = buttons
, alertClosable = True
, alertClass = Message
, alertMessageRender = renderData
, alertCounter = 0
, alertBlockDisplay = True
, alertName = Just UnusedFilesAlert
, alertCombiner = Just $ fullCombiner $ \new _old -> new
, alertData = []
}
brokenRepositoryAlert :: [AlertButton] -> Alert
brokenRepositoryAlert = errorAlert "Serious problems have been detected with your repository. This needs your immediate attention!"
repairingAlert :: String -> Alert
repairingAlert repodesc = activityAlert Nothing
[ Tensed "Attempting to repair" "Repaired"
, UnTensed $ T.pack repodesc
]
pairingAlert :: AlertButton -> Alert
pairingAlert button = baseActivityAlert
{ alertData = [ UnTensed "Pairing in progress" ]
, alertPriority = High
, alertButtons = [button]
}
pairRequestReceivedAlert :: String -> AlertButton -> Alert
pairRequestReceivedAlert who button = Alert
{ alertClass = Message
, alertHeader = Nothing
, alertMessageRender = renderData
, alertData = [UnTensed $ T.pack $ who ++ " is sending a pair request."]
, alertCounter = 0
, alertBlockDisplay = False
, alertPriority = High
, alertClosable = True
, alertIcon = Just InfoIcon
, alertName = Just $ PairAlert who
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertButtons = [button]
}
pairRequestAcknowledgedAlert :: String -> Maybe AlertButton -> Alert
pairRequestAcknowledgedAlert who button = baseActivityAlert
{ alertData = ["Pairing with", UnTensed (T.pack who), Tensed "in progress" "complete"]
, alertPriority = High
, alertName = Just $ PairAlert who
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertButtons = maybeToList button
}
connectionNeededAlert :: AlertButton -> Alert
connectionNeededAlert button = Alert
{ alertHeader = Just "Share with friends, and keep your devices in sync across the cloud."
, alertIcon = Just ConnectionIcon
, alertPriority = High
, alertButtons = [button]
, alertClosable = True
, alertClass = Message
, alertMessageRender = renderData
, alertCounter = 0
, alertBlockDisplay = True
, alertName = Just ConnectionNeededAlert
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertData = []
}
cloudRepoNeededAlert :: Maybe String -> AlertButton -> Alert
cloudRepoNeededAlert friendname button = Alert
{ alertHeader = Just $ fromString $ unwords
[ "Unable to download files from"
, (fromMaybe "your other devices" friendname) ++ "."
]
, alertIcon = Just ErrorIcon
, alertPriority = High
, alertButtons = [button]
, alertClosable = True
, alertClass = Message
, alertMessageRender = renderData
, alertCounter = 0
, alertBlockDisplay = True
, alertName = Just $ CloudRepoNeededAlert
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertData = []
}
remoteRemovalAlert :: String -> AlertButton -> Alert
remoteRemovalAlert desc button = Alert
{ alertHeader = Just $ fromString $
"The repository \"" ++ desc ++
"\" has been emptied, and can now be removed."
, alertIcon = Just InfoIcon
, alertPriority = High
, alertButtons = [button]
, alertClosable = True
, alertClass = Message
, alertMessageRender = renderData
, alertCounter = 0
, alertBlockDisplay = True
, alertName = Just $ RemoteRemovalAlert desc
, alertCombiner = Just $ dataCombiner $ \_old new -> new
, alertData = []
}
fileAlert :: TenseChunk -> [FilePath] -> Alert
fileAlert msg files = (activityAlert Nothing shortfiles)
{ alertName = Just $ FileAlert msg
, alertMessageRender = renderer
, alertCounter = counter
, alertCombiner = Just $ fullCombiner combiner
}
where
maxfilesshown = 10
(!somefiles, !counter) = splitcounter (dedupadjacent files)
!shortfiles = map (fromString . shortFile . takeFileName) somefiles
renderer alert = tenseWords $ msg : alertData alert ++ showcounter
where
showcounter = case alertCounter alert of
0 -> []
_ -> [fromString $ "and " ++ show (alertCounter alert) ++ " other files"]
dedupadjacent (x:y:rest)
| x == y = dedupadjacent (y:rest)
| otherwise = x : dedupadjacent (y:rest)
dedupadjacent (x:[]) = [x]
dedupadjacent [] = []
Note that this ensures the counter is never 1 ; no need to say
- " 1 file " when the filename could be shown .
- "1 file" when the filename could be shown. -}
splitcounter l
| length l <= maxfilesshown = (l, 0)
| otherwise =
let (keep, rest) = splitAt (maxfilesshown - 1) l
in (keep, length rest)
combiner new old =
let (!fs, n) = splitcounter $
dedupadjacent $ alertData new ++ alertData old
!cnt = n + alertCounter new + alertCounter old
in old
{ alertData = fs
, alertCounter = cnt
}
addFileAlert :: [FilePath] -> Alert
addFileAlert = fileAlert (Tensed "Adding" "Added")
transferFileAlert :: Direction -> Bool -> FilePath -> Alert
transferFileAlert direction True file
| direction == Upload = fileAlert "Uploaded" [file]
| otherwise = fileAlert "Downloaded" [file]
transferFileAlert direction False file
| direction == Upload = fileAlert "Upload failed" [file]
| otherwise = fileAlert "Download failed" [file]
dataCombiner :: ([TenseChunk] -> [TenseChunk] -> [TenseChunk]) -> AlertCombiner
dataCombiner combiner = fullCombiner $
\new old -> old { alertData = alertData new `combiner` alertData old }
fullCombiner :: (Alert -> Alert -> Alert) -> AlertCombiner
fullCombiner combiner new old
| alertClass new /= alertClass old = Nothing
| alertName new == alertName old =
Just $! new `combiner` old
| otherwise = Nothing
shortFile :: FilePath -> String
shortFile f
| len < maxlen = f
| otherwise = take half f ++ ".." ++ drop (len - half) f
where
len = length f
maxlen = 20
half = (maxlen - 2) `div` 2
|
59189bcbc057410ad2e68c64c599c9e50577bec9a06a3482b5be7d87d1c5aca4 | egonSchiele/salty | KeywordParser.hs | module Parser.KeywordParser where
import Types
import Utils
import Text.Parsec
import Text.ParserCombinators.Parsec.Char
import Text.Parsec.Combinator
saltySpace = debug "saltySpace" >> do
space
return SaltySpace
maybeToSpace Nothing = ""
maybeToSpace (Just _) = " "
saltyKeyword followupParser = debug "saltyKeyword" >> do
kw <- (saltyKeywordPreceding followupParser) <||> saltyKeywordSimple
return $ Keyword kw
saltyKeywordSimple = debug "saltyKeywordSimple" >> do
sp <- optionMaybe space
kw <- string "undefined"
<||> string "break"
return $ KwSimple ((maybeToSpace sp) ++ kw)
saltyKeywordPreceding followupParser = debug "saltyKeywordPreceding" >> do
sp <- optionMaybe space
kw <- string "const"
<||> string "var"
<||> string "let"
<||> string "throw"
<||> string "require_once"
<||> string "require"
<||> string "public"
<||> string "private"
<||> string "protected"
<||> string "static"
<||> string "export"
<||> string "default"
<||> string "namespace"
<||> string "echo"
<||> string "import *"
<||> string "import"
<||> string "as"
<||> string "use"
<||> string "from"
<||> string "2from"
space
indentDebugger
salty <- followupParser
unindentDebugger
return $ KwPreceding ((maybeToSpace sp) ++ kw) salty
| null | https://raw.githubusercontent.com/egonSchiele/salty/7cb31f35ef0c9d63777d7499174884d7a4054dbb/src/Parser/KeywordParser.hs | haskell | module Parser.KeywordParser where
import Types
import Utils
import Text.Parsec
import Text.ParserCombinators.Parsec.Char
import Text.Parsec.Combinator
saltySpace = debug "saltySpace" >> do
space
return SaltySpace
maybeToSpace Nothing = ""
maybeToSpace (Just _) = " "
saltyKeyword followupParser = debug "saltyKeyword" >> do
kw <- (saltyKeywordPreceding followupParser) <||> saltyKeywordSimple
return $ Keyword kw
saltyKeywordSimple = debug "saltyKeywordSimple" >> do
sp <- optionMaybe space
kw <- string "undefined"
<||> string "break"
return $ KwSimple ((maybeToSpace sp) ++ kw)
saltyKeywordPreceding followupParser = debug "saltyKeywordPreceding" >> do
sp <- optionMaybe space
kw <- string "const"
<||> string "var"
<||> string "let"
<||> string "throw"
<||> string "require_once"
<||> string "require"
<||> string "public"
<||> string "private"
<||> string "protected"
<||> string "static"
<||> string "export"
<||> string "default"
<||> string "namespace"
<||> string "echo"
<||> string "import *"
<||> string "import"
<||> string "as"
<||> string "use"
<||> string "from"
<||> string "2from"
space
indentDebugger
salty <- followupParser
unindentDebugger
return $ KwPreceding ((maybeToSpace sp) ++ kw) salty
|
|
20ec943510da0831ce6f6393348b4f48c1d61603c08994246b754dafef48da88 | ygrek/mldonkey | commonSearch.ml | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey 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 mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey 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 mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Int64ops
open BasicSocket
open Printf2
open CommonGlobals
open CommonNetwork
open CommonResult
open Options
open CommonTypes
open CommonComplexOptions
let search_num = ref 0
let searches_by_num = Hashtbl.create 1027
let new_search user s =
incr search_num;
let time = last_time () in
CommonResult.dummy_result.result_time <- time;
let s = {
search_time = time;
search_num = !search_num;
search_type = s.GuiTypes.search_type;
search_max_hits = s.GuiTypes.search_max_hits;
search_query = s.GuiTypes.search_query;
search_nresults = 0;
search_results = Intmap.empty;
search_waiting = 0;
search_string = CommonIndexing.string_of_query s.GuiTypes.search_query;
search_closed = false;
op_search_new_result_handlers = [];
op_search_end_reply_handlers = [];
search_network = s.GuiTypes.search_network;
} in
Hashtbl.add searches_by_num !search_num s;
user.ui_user_searches <- s :: user.ui_user_searches ;
s
let search_find num = Hashtbl.find searches_by_num num
let search_add_result_in s r =
try
let (c,_) = Intmap.find r.stored_result_num s.search_results in
incr c;
let ri = IndexedResults.get_result r in
if ri.result_modified then
List.iter (fun f -> f r) s.op_search_new_result_handlers
with _ ->
s.search_results <- Intmap.add r.stored_result_num (ref 1, r)
s.search_results;
s.search_nresults <- s.search_nresults + 1;
List.iter (fun f -> f r) s.op_search_new_result_handlers
let search_end_reply s =
s.search_waiting <- s.search_waiting - 1;
List.iter (fun f -> f ()) s.op_search_end_reply_handlers
let search_nresults s =
s.search_nresults
(* should call a handler to send the result to the GUI ... *)
let search_of_args args =
let net = ref 0 in
let rec iter args q =
match args with
[] -> q
| "-minsize" :: minsize :: args ->
let minsize = Int64.of_string minsize in
iter args ((QHasMinVal(Field_Size, minsize)) :: q)
| "-maxsize" :: maxsize :: args ->
let maxsize = Int64.of_string maxsize in
iter args ((QHasMaxVal(Field_Size, maxsize)) :: q)
| "-avail" :: avail :: args ->
let avail = Int64.of_string avail in
iter args ((QHasMinVal(Field_Availability, avail)) :: q)
| "-uid" :: uid :: args ->
iter args ((QHasField(Field_Uid, uid)) :: q)
| "-media" :: filetype :: args ->
iter args ((QHasField(Field_Type, filetype)) :: q)
| "-Video" :: args ->
iter args ((QHasField(Field_Type, "Video")) :: q)
| "-Audio" :: filetype :: args ->
iter args ((QHasField(Field_Type, "Audio")) :: q)
| "-format" :: format :: args ->
iter args ((QHasField(Field_Format, format)) :: q)
| "-artist" :: format :: args ->
iter args ((QHasField(Field_Artist, format)) :: q)
| "-title" :: format :: args ->
iter args ((QHasField(Field_Title, format)) :: q)
| "-album" :: format :: args ->
iter args ((QHasField(Field_Album, format)) :: q)
| "-field" :: field :: format :: args ->
iter args ((QHasField(Field_KNOWN field, format)) :: q)
| "-network" :: name :: args ->
net := (network_find_by_name name).network_num;
iter args q
| "-not" :: name :: args ->
iter args ((QAndNot (QHasWord name, QHasWord name)) :: q)
| "-and" :: name :: args ->
iter args ((QAnd (QHasWord name, QHasWord name)) :: q)
| "-or" :: name :: args ->
iter args ((QOr (QHasWord name, QHasWord name)) :: q)
| s :: args ->
if s.[0] = '-' then
let args =
try
(String2.split_simplify (List.assoc s !!special_queries) ' ')@args
with Not_found ->
failwith (Printf.sprintf "No specialized search '%s'"
s)
in
iter args q
else
iter args ((QHasWord(s)) :: q)
in
let q = iter args [] in
(match (List.rev q) with
[] -> failwith "Void query"
| q1 :: tail ->
List.fold_left (fun q1 q2 ->
match q2 with
QAndNot (QHasWord x, _) ->
QAndNot (q1, QHasWord x)
| QAnd (QHasWord x, _) ->
QAnd (q1, QHasWord x)
| QOr (QHasWord x, _) ->
QOr (q1, QHasWord x)
| _ ->
QAnd (q1,q2)
) q1 tail), !net
type englob_op = IN_NOOP | IN_AND | IN_OR
let can_search = ref false
let custom_query buf query =
can_search :=
networks_iter_all_until_true (fun net ->
try
network_is_enabled net && List.mem NetworkHasSearch net.network_flags
with _ -> false
);
if !can_search then begin
try
let q = List.assoc query (CommonComplexOptions.customized_queries()) in
Printf.bprintf buf "
<center>
<h2 class=\"header2\"> %s </h2>
</center>
<form action=\"submit\">
<input type=hidden name=custom value=\"%s\">
<input type=submit value=Search>" query query;
let rec iter q in_op =
match q with
| Q_COMBO _ -> assert false
| Q_AND list ->
if in_op <> IN_AND then begin
Buffer.add_string buf "<table border=1>";
Buffer.add_string buf "<tr>";
Buffer.add_string buf "<td>";
Buffer.add_string buf "AND";
Buffer.add_string buf "</td>";
Buffer.add_string buf "<td>";
Buffer.add_string buf "<table border=1>";
List.iter (fun q ->
Buffer.add_string buf "<tr><td>";
iter q IN_AND;
Buffer.add_string buf "</td></tr>";
) list;
Buffer.add_string buf "</table>";
Buffer.add_string buf "</td>";
Buffer.add_string buf "</tr>";
Buffer.add_string buf "</table>";
end else begin
Buffer.add_string buf "<table border=0>";
List.iter (fun q ->
Buffer.add_string buf "<tr><td>";
iter q IN_AND;
Buffer.add_string buf "</td></tr>";
) list;
Buffer.add_string buf "</table>";
end
| Q_OR list ->
if in_op <> IN_OR then begin
Buffer.add_string buf "<table border=1>";
Buffer.add_string buf "<tr>";
Buffer.add_string buf "<td>";
Buffer.add_string buf "OR";
Buffer.add_string buf "</td>";
Buffer.add_string buf "<td>";
Buffer.add_string buf "<table border=1>";
List.iter (fun q ->
Buffer.add_string buf "<tr><td>";
iter q IN_OR;
Buffer.add_string buf "</td></tr>";
) list;
Buffer.add_string buf "</table>";
Buffer.add_string buf "</td>";
Buffer.add_string buf "</tr>";
Buffer.add_string buf "</table>";
end else begin
Buffer.add_string buf "<table border=0>";
List.iter (fun q ->
Buffer.add_string buf "<tr><td>";
iter q IN_OR;
Buffer.add_string buf "</td></tr>";
) list;
Buffer.add_string buf "</table>";
end
| Q_ANDNOT (q1,q2) ->
Buffer.add_string buf "<table border=1>";
Buffer.add_string buf "<tr>";
Buffer.add_string buf "<td>";
iter q1 IN_AND;
Buffer.add_string buf "</td>";
Buffer.add_string buf "</tr>";
Buffer.add_string buf "<tr>";
Buffer.add_string buf "<table border=1>";
Buffer.add_string buf "<tr>";
Buffer.add_string buf "<td>";
Buffer.add_string buf "AND NOT";
Buffer.add_string buf "</td>";
Buffer.add_string buf "<td>";
iter q2 IN_AND;
Buffer.add_string buf "</td>";
Buffer.add_string buf "</tr>";
Buffer.add_string buf "</table>";
Buffer.add_string buf "</tr>";
| Q_KEYWORDS (label, default) ->
Printf.bprintf buf "
<table border=0>
<td class=\"txt\" width=100 align=right>%s</td><td><input type=text name=keywords size=40 value=\"%s\"></td>
</table>" label default
| Q_MINSIZE (label, default) ->
Printf.bprintf buf "
<table border=0>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=minsize size=40 value=\"%s\">
</td>
<td>
<select name=minsize_unit>
<option value=1048576> MBytes </option>
<option value=1024> kBytes </option>
<option value=1> Bytes </option>
</select>
</td>
</table>
" label (if default = "" then "" else
try
let size = Int64.of_string default in
let size = size // 1048576L in
Int64.to_string size
with _ -> "")
| Q_MAXSIZE (label, default) ->
Printf.bprintf buf "
<table border=0>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=maxsize size=40 value=\"%s\">
</td>
<td>
<select name=maxsize_unit>
<option value=1048576> MBytes </option>
<option value=1024> kBytes </option>
<option value=1> Bytes </option>
</select>
</td>
</table>
" label (if default = "" then "" else
try
let size = Int64.of_string default in
let size = size // 1048576L in
Int64.to_string size
with _ -> "")
| Q_MP3_BITRATE (label, default) ->
Printf.bprintf buf "
<table border=0>
<tr>
<td class=\"txt\" width=100 align=right>
%s
</td>
<td>
<select name=bitrate>
<option value=\"%s\"> --- </option>
<option value=64> 64 </option>
<option value=96> 96 </option>
<option value=128> 128 </option>
<option value=160> 160 </option>
<option value=192> 192 </option>
</select>
</td>
</tr>
</table>
" label default
| Q_MP3_ALBUM (label, default) ->
Printf.bprintf buf "
<table border=0>
<tr>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=album size=40 value=\"%s\">
</td>
</tr>
</table>
" label default
| Q_MP3_TITLE (label, default) ->
Printf.bprintf buf "
<table border=0>
<tr>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=title size=40 value=\"%s\">
</td>
</tr>
</table>
" label default
| Q_MP3_ARTIST (label, default) ->
Printf.bprintf buf "
<table border=0>
<tr>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=artist size=40 value=\"%s\">
</td>
</tr>
</table>
" label default
| Q_MEDIA (label, default) ->
Printf.bprintf buf "
<table border=0>
<tr>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=media size=40 value=\"%s\">
</td>
<td>
<select name=media_propose>
<option value=\"\"> --- </option>
<option value=Audio> Audio </option>
<option value=Video> Video </option>
<option value=Pro> Program </option>
<option value=Doc> Document </option>
<option value=Image> Image </option>
<option value=Col> Collection </option>
</select>
</td>
</tr>
</table>
" label default
| Q_FORMAT (label, default) ->
Printf.bprintf buf "
<table border=0>
<tr>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=format size=40 value=\"%s\">
</td>
<td>
<select name=format_propose>
<option value=\"\"> --- </option>
<option value=avi> avi </option>
<option value=mp3> mp3 </option>
<option value=zip> zip </option>
<option value=gif> gif </option>
</select>
</td>
</tr>
</table>
" label default
| Q_MODULE (label, q) ->
Printf.bprintf buf "<table border=0> <tr><td> <h3 class=\"header3\"> %s </h3> </td></tr>" label;
Printf.bprintf buf "<tr><td>";
iter q in_op;
Printf.bprintf buf "</td></tr>";
Printf.bprintf buf "</table>";
| Q_HIDDEN list ->
List.iter iter_hidden list
and iter_hidden q =
match q with
| Q_COMBO _ -> assert false
| Q_AND list | Q_OR list | Q_HIDDEN list ->
List.iter iter_hidden list
| Q_ANDNOT (q1,q2) ->
iter_hidden q1;
iter_hidden q2;
| Q_KEYWORDS (label, default) ->
Printf.bprintf buf
"<input type=hidden name=keywords value=\"%s\">"
default
| Q_MINSIZE (label, default) ->
Printf.bprintf buf
"<input type=hidden name=minsize value=\"%s\">
<input type=hidden name=minsize_unit value=\"1\">" default
| Q_MAXSIZE (label, default) ->
Printf.bprintf buf
"<input type=hidden name=maxsize value=\"%s\">
<input type=hidden name=maxsize_unit value=\"1\">" default
| Q_MP3_BITRATE (label, default) ->
Printf.bprintf buf
"<input type=hidden name=bitrate value=\"%s\">"
default
| Q_MP3_ALBUM (label, default) ->
Printf.bprintf buf
"<input type=album name=bitrate value=\"%s\">"
default
| Q_MP3_TITLE (label, default) ->
Printf.bprintf buf
"<input type=hidden name=title value=\"%s\">"
default
| Q_MP3_ARTIST (label, default) ->
Printf.bprintf buf
"<input type=hidden name=artist value=\"%s\">"
default
| Q_MEDIA (label, default) ->
Printf.bprintf buf
"<input type=hidden name=media value=\"%s\">
<input type=hidden name=media_propose value=\"\">"
default
| Q_FORMAT (label, default) ->
Printf.bprintf buf
"<input type=hidden name=format value=\"%s\">
<input type=hidden name=format_propose value=\"\">"
default
| Q_MODULE (label, q) ->
iter_hidden q
in
iter q IN_AND;
Printf.bprintf buf "</td></tr>";
Printf.bprintf buf "</table>";
Printf.bprintf buf "<table border=0> <tr><td> <h3 class=\"header3\"> Misc </h3> </td></tr>";
Printf.bprintf buf "<tr><td>";
Printf.bprintf buf "
<table border=0>
<td class=\"txt\" width=100 align=right>Network</td><td>
<select name=network>
<option value=\"\"> --- </option>
";
networks_iter_all (fun net ->
let name = net.network_name in
try
if network_is_enabled net &&
List.mem NetworkHasSearch net.network_flags then
Printf.bprintf buf
"<option value=\"%s\"> %s </option>" name name
with _ -> ()
);
Printf.bprintf buf "
</select></td></table>" ;
Buffer.add_string buf "</form>"
with Not_found ->
Printf.bprintf buf "No custom search %s" query
end
else
begin
html_mods_table_header buf " searchTable " " search " [ ] ;
html_mods_td buf [
( " " , " srh " , " No searchable networks enabled " ) ; ] ;
html_mods_td buf [
("", "srh", "No searchable networks enabled"); ];
*)
Buffer.add_string buf "<div class=\"results\">
<table id=\"memstatsTable\" name=\"searchTable\" class=\"search\" cellspacing=0 cellpadding=0>
<tr><td class=\"srh\" >No searchable networks enabled</td>";
Buffer.add_string buf "</tr></table></div>\n"
end
Printf.bprintf buf "
< h3 > No searchable networks enabled < /h3 >
"
<h3> No searchable networks enabled </h3>
"
*)
let complex_search buf =
can_search :=
networks_iter_all_until_true (fun net ->
try network_is_enabled net && List.mem NetworkHasSearch net.network_flags
with _ -> false
);
Buffer.add_string buf "<div class=\"results\">
<table id=\"memstatsTable\" name=\"searchTable\" class=\"search\" cellspacing=0 cellpadding=0>
<tr><td class=\"srh\" >";
Buffer.add_string buf
"
<center>
<h2> Complex Search </h2>
</center>
</td>
";
if !can_search then begin
Buffer.add_string buf
"
<td>
<form action=\"submit\">
<table border=0>
<tr>
<td width=\"1%\"><input type=text name=query size=40 value=\"\"></td>
<td align=left><input type=submit value=Search></td>
</tr>
</table>
<h3> Simple Options </h3>
<table border=0>
<tr>
<td> Min size </td>
<td>
<input type=text name=minsize size=40 value=\"\">
</td>
<td>
<select name=minsize_unit>
<option value=1048576> MBytes </option>
<option value=1024> kBytes </option>
<option value=1> Bytes </option>
</select>
</td>
</tr>
<tr>
<td> Max size </td>
<td>
<input type=text name=maxsize size=40 value=\"\">
</td>
<td>
<select name=maxsize_unit>
<option value=1048576> Mbytes </option>
<option value=1024> kBytes </option>
<option value=1> Bytes </option>
</select>
</td>
</tr>
<tr>
<td> Media </td>
<td>
<input type=text name=media size=40 value=\"\">
</td>
<td>
<select name=media_propose>
<option value=\"\"> --- </option>
<option value=Audio> Audio </option>
<option value=Video> Video </option>
<option value=Pro> Program </option>
<option value=Doc> Document </option>
<option value=Image> Image </option>
<option value=Col> Collection </option>
</select>
</td>
</tr>
<tr>
<td> Format </td>
<td>
<input type=text name=format size=40 value=\"\">
</td>
<td>
<select name=format_propose>
<option value=\"\"> --- </option>
<option value=avi> avi </option>
<option value=mp3> mp3 </option>
<option value=zip> zip </option>
</select>
</td>
</tr>
</table>
<h3> Mp3 options </h3>
<table border=0>
<tr>
<td> Album </td>
<td>
<input type=text name=album size=40 value=\"\">
</td>
</tr>
<tr>
<td class=\"txt\"> Artist </td>
<td>
<input type=text name=artist size=40 value=\"\">
</td>
</tr>
<tr>
<td> Title </td>
<td>
<input type=text name=title size=40 value=\"\">
</td>
</tr>
<tr>
<td>
Min bitrate
</td>
<td>
<select name=bitrate>
<option value=\"\"> --- </option>
<option value=64> 64 </option>
<option value=96> 96 </option>
<option value=128> 128 </option>
<option value=160> 160 </option>
<option value=192> 192 </option>
</select>
</td>
</tr>
</table>
<h3> Boolean options </h3>
<table border=0>
<tr>
<td> And </td>
<td>
<input type=text name=and size=40 value=\"\">
</td>
</tr>
<tr>
<td> Or </td>
<td>
<input type=text name=or size=40 value=\"\">
</td>
</tr>
<tr>
<td> Not </td>
<td>
<input type=text name=not size=40 value=\"\">
</td>
</tr>
";
Printf.bprintf buf "
<tr>
<td> Network </td>
<td>
<select name=network>
<option value=\"\"> --- </option>
";
networks_iter_all (fun net ->
let name = net.network_name in
try
if network_is_enabled net &&
List.mem NetworkHasSearch net.network_flags then
Printf.bprintf buf
"<option value=\"%s\"> %s </option>" name name
with _ -> ()
);
Printf.bprintf buf "
</select></td></tr></table></form></td>";
end;
if not !can_search then begin
html_mods_table_header buf " searchTable " " search " [ ] ;
html_mods_td buf [
( " " , " srh " , " No searchable networks enabled " ) ; ] ;
html_mods_td buf [
("", "srh", "No searchable networks enabled"); ];
*)
Printf.bprintf buf "<td><div class=\"results\">
<table id=\"memstatsTable\" name=\"searchTable\" class=\"search\" cellspacing=0 cellpadding=0>
<tr><td class=\"srh\" >No searchable networks enabled</td>";
Buffer.add_string buf "</tr></table></div></td>\n"
end;
Printf.bprintf buf "
< h3 > No searchable networks enabled < /h3 >
" ;
Printf.bprintf buf "
<h3> No searchable networks enabled </h3>
";
*)
Buffer.add_string buf
"
</table>
</div>
"
let search_forget user s =
networks_iter (fun n -> network_forget_search n s);
Hashtbl.remove searches_by_num s.search_num;
user.ui_user_searches <- List2.removeq s user.ui_user_searches
let search_close s =
networks_iter (fun n -> network_close_search n s)
let search_media_list =
[ "Program", "Pro";
"Documentation", "Doc";
"Collection", "Col";
]
* Transforme une query_entry en provenance
en query . Les conversions pour Media sont faites
au vol , pour donkey .
en query. Les conversions pour Media sont faites
au vol, pour donkey.*)
let or_comb q1 q2 = QOr (q1,q2)
let and_comb q1 q2 = QAnd (q1,q2)
let andnot q1 q2 = QAndNot (q1,q2)
let rec mftp_query_of_query_entry qe =
match qe with
Q_AND ([]) -> QNone
| Q_AND [_] -> lprintf_nl "Q_AND [_]"; QNone
| Q_COMBO _ -> assert false
| Q_AND (h :: q) ->
List.fold_left
(fun acc -> fun q -> QAnd (acc, mftp_query_of_query_entry q))
(mftp_query_of_query_entry h)
q
| Q_OR [_] -> lprintf_nl "Q_OR [_]"; QNone
| Q_OR ([]) -> QNone
| Q_OR (h :: q) ->
List.fold_left
(fun acc -> fun q -> QOr (acc, mftp_query_of_query_entry q))
(mftp_query_of_query_entry h)
q
| Q_ANDNOT (q1,q2) ->
QAndNot
(mftp_query_of_query_entry q1,
mftp_query_of_query_entry q2)
| Q_MODULE (_, q) ->
mftp_query_of_query_entry q
| Q_KEYWORDS (_,s) ->
(
try want_and_not andnot (fun w -> QHasWord w) QNone s
with Not_found -> QNone
)
| Q_MINSIZE (_,s) ->
(
try QHasMinVal (Field_Size, Int64.of_string s)
with _ -> QNone
)
| Q_MAXSIZE (_,s) ->
(
try QHasMaxVal (Field_Size, Int64.of_string s)
with _ -> QNone
)
| Q_FORMAT (_,s) ->
(
try
want_comb_not andnot or_comb (fun w -> QHasField(Field_Format, w)) QNone s
with Not_found ->
QNone
)
| Q_MEDIA (_,s) ->
(
try QHasField(Field_Type, List.assoc s search_media_list)
with Not_found ->
match String2.split_simplify s ' ' with
[] -> QNone
| _ -> QHasField (Field_Type, s)
)
| Q_MP3_ARTIST (_,s) ->
(
try
want_comb_not andnot and_comb
(fun w -> QHasField(Field_Artist, w)) QNone s
with Not_found ->
QNone
)
| Q_MP3_TITLE (_,s) ->
(
try
want_comb_not andnot and_comb
(fun w -> QHasField(Field_Title, w)) QNone s
with Not_found ->
QNone
)
| Q_MP3_ALBUM (_,s) ->
(
try
want_comb_not andnot and_comb
(fun w -> QHasField(Field_Album, w)) QNone s
with Not_found ->
QNone
)
| Q_MP3_BITRATE (_,s) ->
begin
try
let bitrate = Int64.of_string s
in
QHasMinVal(Field_KNOWN "bitrate", bitrate)
with _ -> QNone
end
| Q_HIDDEN [q] ->
mftp_query_of_query_entry q
| Q_HIDDEN l ->
mftp_query_of_query_entry (Q_AND l)
(*********************************************************************
SEARCH FILTERING
*********************************************************************)
module Search = struct
let add_search_result s r =
search_add_result_in s (find_result r.result_num)
end
module Filter = IndexedResults.MakeIndex(Search)
module Local = IndexedResults.MakeIndex(Search)
let clean_local_search = ref 0
let local_search s =
add_timer 330. (fun _ ->
if !clean_local_search < last_time () then begin
Local.clear ();
clean_local_search := 0
end
);
if !clean_local_search = 0 then begin
Local.clear ();
results_iter (fun _ r -> Local.add r)
end;
clean_local_search := last_time () + 300;
Local.find s
let result_format_of_name name =
match String.lowercase (Filename2.last_extension name ) with
".mpeg" -> "mpg"
| ".jpeg" -> "jpg"
| "" -> ""
| s ->
let n = String.sub s 1 (String.length s - 1) in
n
let result_media_of_name name =
match String.lowercase (Filename2.last_extension name ) with
".mpg" | ".mpeg" | ".avi" | ".ogm" | ".divx" | ".mov" -> "Video"
| ".mp3" | ".wav" | ".ogg" -> "Audio"
| ".txt" | ".doc" -> "Doc"
| ".exe" -> "Pro"
| ".jpg" | ".jpeg" | ".tiff" | ".png" | ".gif" -> "Image"
| _ -> ""
let _ =
Heap.add_memstat "CommonSearch" (fun level buf ->
let mem = Filter.stats () in
Printf.bprintf buf " Filtering index memory: %d\n" mem;
let mem = Local.stats () in
Printf.bprintf buf " Local index memory: %d\n" mem;
let counter = ref 0 in
let items = ref 0 in
Hashtbl.iter (fun _ s ->
incr counter;
items := !items + Intmap.length s.search_results
) searches_by_num;
Printf.bprintf buf " Memorized searches: %d\n" !counter;
Printf.bprintf buf " Memorized items: %d\n" !items;
)
| null | https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/daemon/common/commonSearch.ml | ocaml | should call a handler to send the result to the GUI ...
********************************************************************
SEARCH FILTERING
******************************************************************** | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey 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 mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey 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 mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Int64ops
open BasicSocket
open Printf2
open CommonGlobals
open CommonNetwork
open CommonResult
open Options
open CommonTypes
open CommonComplexOptions
let search_num = ref 0
let searches_by_num = Hashtbl.create 1027
let new_search user s =
incr search_num;
let time = last_time () in
CommonResult.dummy_result.result_time <- time;
let s = {
search_time = time;
search_num = !search_num;
search_type = s.GuiTypes.search_type;
search_max_hits = s.GuiTypes.search_max_hits;
search_query = s.GuiTypes.search_query;
search_nresults = 0;
search_results = Intmap.empty;
search_waiting = 0;
search_string = CommonIndexing.string_of_query s.GuiTypes.search_query;
search_closed = false;
op_search_new_result_handlers = [];
op_search_end_reply_handlers = [];
search_network = s.GuiTypes.search_network;
} in
Hashtbl.add searches_by_num !search_num s;
user.ui_user_searches <- s :: user.ui_user_searches ;
s
let search_find num = Hashtbl.find searches_by_num num
let search_add_result_in s r =
try
let (c,_) = Intmap.find r.stored_result_num s.search_results in
incr c;
let ri = IndexedResults.get_result r in
if ri.result_modified then
List.iter (fun f -> f r) s.op_search_new_result_handlers
with _ ->
s.search_results <- Intmap.add r.stored_result_num (ref 1, r)
s.search_results;
s.search_nresults <- s.search_nresults + 1;
List.iter (fun f -> f r) s.op_search_new_result_handlers
let search_end_reply s =
s.search_waiting <- s.search_waiting - 1;
List.iter (fun f -> f ()) s.op_search_end_reply_handlers
let search_nresults s =
s.search_nresults
let search_of_args args =
let net = ref 0 in
let rec iter args q =
match args with
[] -> q
| "-minsize" :: minsize :: args ->
let minsize = Int64.of_string minsize in
iter args ((QHasMinVal(Field_Size, minsize)) :: q)
| "-maxsize" :: maxsize :: args ->
let maxsize = Int64.of_string maxsize in
iter args ((QHasMaxVal(Field_Size, maxsize)) :: q)
| "-avail" :: avail :: args ->
let avail = Int64.of_string avail in
iter args ((QHasMinVal(Field_Availability, avail)) :: q)
| "-uid" :: uid :: args ->
iter args ((QHasField(Field_Uid, uid)) :: q)
| "-media" :: filetype :: args ->
iter args ((QHasField(Field_Type, filetype)) :: q)
| "-Video" :: args ->
iter args ((QHasField(Field_Type, "Video")) :: q)
| "-Audio" :: filetype :: args ->
iter args ((QHasField(Field_Type, "Audio")) :: q)
| "-format" :: format :: args ->
iter args ((QHasField(Field_Format, format)) :: q)
| "-artist" :: format :: args ->
iter args ((QHasField(Field_Artist, format)) :: q)
| "-title" :: format :: args ->
iter args ((QHasField(Field_Title, format)) :: q)
| "-album" :: format :: args ->
iter args ((QHasField(Field_Album, format)) :: q)
| "-field" :: field :: format :: args ->
iter args ((QHasField(Field_KNOWN field, format)) :: q)
| "-network" :: name :: args ->
net := (network_find_by_name name).network_num;
iter args q
| "-not" :: name :: args ->
iter args ((QAndNot (QHasWord name, QHasWord name)) :: q)
| "-and" :: name :: args ->
iter args ((QAnd (QHasWord name, QHasWord name)) :: q)
| "-or" :: name :: args ->
iter args ((QOr (QHasWord name, QHasWord name)) :: q)
| s :: args ->
if s.[0] = '-' then
let args =
try
(String2.split_simplify (List.assoc s !!special_queries) ' ')@args
with Not_found ->
failwith (Printf.sprintf "No specialized search '%s'"
s)
in
iter args q
else
iter args ((QHasWord(s)) :: q)
in
let q = iter args [] in
(match (List.rev q) with
[] -> failwith "Void query"
| q1 :: tail ->
List.fold_left (fun q1 q2 ->
match q2 with
QAndNot (QHasWord x, _) ->
QAndNot (q1, QHasWord x)
| QAnd (QHasWord x, _) ->
QAnd (q1, QHasWord x)
| QOr (QHasWord x, _) ->
QOr (q1, QHasWord x)
| _ ->
QAnd (q1,q2)
) q1 tail), !net
type englob_op = IN_NOOP | IN_AND | IN_OR
let can_search = ref false
let custom_query buf query =
can_search :=
networks_iter_all_until_true (fun net ->
try
network_is_enabled net && List.mem NetworkHasSearch net.network_flags
with _ -> false
);
if !can_search then begin
try
let q = List.assoc query (CommonComplexOptions.customized_queries()) in
Printf.bprintf buf "
<center>
<h2 class=\"header2\"> %s </h2>
</center>
<form action=\"submit\">
<input type=hidden name=custom value=\"%s\">
<input type=submit value=Search>" query query;
let rec iter q in_op =
match q with
| Q_COMBO _ -> assert false
| Q_AND list ->
if in_op <> IN_AND then begin
Buffer.add_string buf "<table border=1>";
Buffer.add_string buf "<tr>";
Buffer.add_string buf "<td>";
Buffer.add_string buf "AND";
Buffer.add_string buf "</td>";
Buffer.add_string buf "<td>";
Buffer.add_string buf "<table border=1>";
List.iter (fun q ->
Buffer.add_string buf "<tr><td>";
iter q IN_AND;
Buffer.add_string buf "</td></tr>";
) list;
Buffer.add_string buf "</table>";
Buffer.add_string buf "</td>";
Buffer.add_string buf "</tr>";
Buffer.add_string buf "</table>";
end else begin
Buffer.add_string buf "<table border=0>";
List.iter (fun q ->
Buffer.add_string buf "<tr><td>";
iter q IN_AND;
Buffer.add_string buf "</td></tr>";
) list;
Buffer.add_string buf "</table>";
end
| Q_OR list ->
if in_op <> IN_OR then begin
Buffer.add_string buf "<table border=1>";
Buffer.add_string buf "<tr>";
Buffer.add_string buf "<td>";
Buffer.add_string buf "OR";
Buffer.add_string buf "</td>";
Buffer.add_string buf "<td>";
Buffer.add_string buf "<table border=1>";
List.iter (fun q ->
Buffer.add_string buf "<tr><td>";
iter q IN_OR;
Buffer.add_string buf "</td></tr>";
) list;
Buffer.add_string buf "</table>";
Buffer.add_string buf "</td>";
Buffer.add_string buf "</tr>";
Buffer.add_string buf "</table>";
end else begin
Buffer.add_string buf "<table border=0>";
List.iter (fun q ->
Buffer.add_string buf "<tr><td>";
iter q IN_OR;
Buffer.add_string buf "</td></tr>";
) list;
Buffer.add_string buf "</table>";
end
| Q_ANDNOT (q1,q2) ->
Buffer.add_string buf "<table border=1>";
Buffer.add_string buf "<tr>";
Buffer.add_string buf "<td>";
iter q1 IN_AND;
Buffer.add_string buf "</td>";
Buffer.add_string buf "</tr>";
Buffer.add_string buf "<tr>";
Buffer.add_string buf "<table border=1>";
Buffer.add_string buf "<tr>";
Buffer.add_string buf "<td>";
Buffer.add_string buf "AND NOT";
Buffer.add_string buf "</td>";
Buffer.add_string buf "<td>";
iter q2 IN_AND;
Buffer.add_string buf "</td>";
Buffer.add_string buf "</tr>";
Buffer.add_string buf "</table>";
Buffer.add_string buf "</tr>";
| Q_KEYWORDS (label, default) ->
Printf.bprintf buf "
<table border=0>
<td class=\"txt\" width=100 align=right>%s</td><td><input type=text name=keywords size=40 value=\"%s\"></td>
</table>" label default
| Q_MINSIZE (label, default) ->
Printf.bprintf buf "
<table border=0>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=minsize size=40 value=\"%s\">
</td>
<td>
<select name=minsize_unit>
<option value=1048576> MBytes </option>
<option value=1024> kBytes </option>
<option value=1> Bytes </option>
</select>
</td>
</table>
" label (if default = "" then "" else
try
let size = Int64.of_string default in
let size = size // 1048576L in
Int64.to_string size
with _ -> "")
| Q_MAXSIZE (label, default) ->
Printf.bprintf buf "
<table border=0>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=maxsize size=40 value=\"%s\">
</td>
<td>
<select name=maxsize_unit>
<option value=1048576> MBytes </option>
<option value=1024> kBytes </option>
<option value=1> Bytes </option>
</select>
</td>
</table>
" label (if default = "" then "" else
try
let size = Int64.of_string default in
let size = size // 1048576L in
Int64.to_string size
with _ -> "")
| Q_MP3_BITRATE (label, default) ->
Printf.bprintf buf "
<table border=0>
<tr>
<td class=\"txt\" width=100 align=right>
%s
</td>
<td>
<select name=bitrate>
<option value=\"%s\"> --- </option>
<option value=64> 64 </option>
<option value=96> 96 </option>
<option value=128> 128 </option>
<option value=160> 160 </option>
<option value=192> 192 </option>
</select>
</td>
</tr>
</table>
" label default
| Q_MP3_ALBUM (label, default) ->
Printf.bprintf buf "
<table border=0>
<tr>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=album size=40 value=\"%s\">
</td>
</tr>
</table>
" label default
| Q_MP3_TITLE (label, default) ->
Printf.bprintf buf "
<table border=0>
<tr>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=title size=40 value=\"%s\">
</td>
</tr>
</table>
" label default
| Q_MP3_ARTIST (label, default) ->
Printf.bprintf buf "
<table border=0>
<tr>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=artist size=40 value=\"%s\">
</td>
</tr>
</table>
" label default
| Q_MEDIA (label, default) ->
Printf.bprintf buf "
<table border=0>
<tr>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=media size=40 value=\"%s\">
</td>
<td>
<select name=media_propose>
<option value=\"\"> --- </option>
<option value=Audio> Audio </option>
<option value=Video> Video </option>
<option value=Pro> Program </option>
<option value=Doc> Document </option>
<option value=Image> Image </option>
<option value=Col> Collection </option>
</select>
</td>
</tr>
</table>
" label default
| Q_FORMAT (label, default) ->
Printf.bprintf buf "
<table border=0>
<tr>
<td class=\"txt\" width=100 align=right> %s </td>
<td>
<input type=text name=format size=40 value=\"%s\">
</td>
<td>
<select name=format_propose>
<option value=\"\"> --- </option>
<option value=avi> avi </option>
<option value=mp3> mp3 </option>
<option value=zip> zip </option>
<option value=gif> gif </option>
</select>
</td>
</tr>
</table>
" label default
| Q_MODULE (label, q) ->
Printf.bprintf buf "<table border=0> <tr><td> <h3 class=\"header3\"> %s </h3> </td></tr>" label;
Printf.bprintf buf "<tr><td>";
iter q in_op;
Printf.bprintf buf "</td></tr>";
Printf.bprintf buf "</table>";
| Q_HIDDEN list ->
List.iter iter_hidden list
and iter_hidden q =
match q with
| Q_COMBO _ -> assert false
| Q_AND list | Q_OR list | Q_HIDDEN list ->
List.iter iter_hidden list
| Q_ANDNOT (q1,q2) ->
iter_hidden q1;
iter_hidden q2;
| Q_KEYWORDS (label, default) ->
Printf.bprintf buf
"<input type=hidden name=keywords value=\"%s\">"
default
| Q_MINSIZE (label, default) ->
Printf.bprintf buf
"<input type=hidden name=minsize value=\"%s\">
<input type=hidden name=minsize_unit value=\"1\">" default
| Q_MAXSIZE (label, default) ->
Printf.bprintf buf
"<input type=hidden name=maxsize value=\"%s\">
<input type=hidden name=maxsize_unit value=\"1\">" default
| Q_MP3_BITRATE (label, default) ->
Printf.bprintf buf
"<input type=hidden name=bitrate value=\"%s\">"
default
| Q_MP3_ALBUM (label, default) ->
Printf.bprintf buf
"<input type=album name=bitrate value=\"%s\">"
default
| Q_MP3_TITLE (label, default) ->
Printf.bprintf buf
"<input type=hidden name=title value=\"%s\">"
default
| Q_MP3_ARTIST (label, default) ->
Printf.bprintf buf
"<input type=hidden name=artist value=\"%s\">"
default
| Q_MEDIA (label, default) ->
Printf.bprintf buf
"<input type=hidden name=media value=\"%s\">
<input type=hidden name=media_propose value=\"\">"
default
| Q_FORMAT (label, default) ->
Printf.bprintf buf
"<input type=hidden name=format value=\"%s\">
<input type=hidden name=format_propose value=\"\">"
default
| Q_MODULE (label, q) ->
iter_hidden q
in
iter q IN_AND;
Printf.bprintf buf "</td></tr>";
Printf.bprintf buf "</table>";
Printf.bprintf buf "<table border=0> <tr><td> <h3 class=\"header3\"> Misc </h3> </td></tr>";
Printf.bprintf buf "<tr><td>";
Printf.bprintf buf "
<table border=0>
<td class=\"txt\" width=100 align=right>Network</td><td>
<select name=network>
<option value=\"\"> --- </option>
";
networks_iter_all (fun net ->
let name = net.network_name in
try
if network_is_enabled net &&
List.mem NetworkHasSearch net.network_flags then
Printf.bprintf buf
"<option value=\"%s\"> %s </option>" name name
with _ -> ()
);
Printf.bprintf buf "
</select></td></table>" ;
Buffer.add_string buf "</form>"
with Not_found ->
Printf.bprintf buf "No custom search %s" query
end
else
begin
html_mods_table_header buf " searchTable " " search " [ ] ;
html_mods_td buf [
( " " , " srh " , " No searchable networks enabled " ) ; ] ;
html_mods_td buf [
("", "srh", "No searchable networks enabled"); ];
*)
Buffer.add_string buf "<div class=\"results\">
<table id=\"memstatsTable\" name=\"searchTable\" class=\"search\" cellspacing=0 cellpadding=0>
<tr><td class=\"srh\" >No searchable networks enabled</td>";
Buffer.add_string buf "</tr></table></div>\n"
end
Printf.bprintf buf "
< h3 > No searchable networks enabled < /h3 >
"
<h3> No searchable networks enabled </h3>
"
*)
let complex_search buf =
can_search :=
networks_iter_all_until_true (fun net ->
try network_is_enabled net && List.mem NetworkHasSearch net.network_flags
with _ -> false
);
Buffer.add_string buf "<div class=\"results\">
<table id=\"memstatsTable\" name=\"searchTable\" class=\"search\" cellspacing=0 cellpadding=0>
<tr><td class=\"srh\" >";
Buffer.add_string buf
"
<center>
<h2> Complex Search </h2>
</center>
</td>
";
if !can_search then begin
Buffer.add_string buf
"
<td>
<form action=\"submit\">
<table border=0>
<tr>
<td width=\"1%\"><input type=text name=query size=40 value=\"\"></td>
<td align=left><input type=submit value=Search></td>
</tr>
</table>
<h3> Simple Options </h3>
<table border=0>
<tr>
<td> Min size </td>
<td>
<input type=text name=minsize size=40 value=\"\">
</td>
<td>
<select name=minsize_unit>
<option value=1048576> MBytes </option>
<option value=1024> kBytes </option>
<option value=1> Bytes </option>
</select>
</td>
</tr>
<tr>
<td> Max size </td>
<td>
<input type=text name=maxsize size=40 value=\"\">
</td>
<td>
<select name=maxsize_unit>
<option value=1048576> Mbytes </option>
<option value=1024> kBytes </option>
<option value=1> Bytes </option>
</select>
</td>
</tr>
<tr>
<td> Media </td>
<td>
<input type=text name=media size=40 value=\"\">
</td>
<td>
<select name=media_propose>
<option value=\"\"> --- </option>
<option value=Audio> Audio </option>
<option value=Video> Video </option>
<option value=Pro> Program </option>
<option value=Doc> Document </option>
<option value=Image> Image </option>
<option value=Col> Collection </option>
</select>
</td>
</tr>
<tr>
<td> Format </td>
<td>
<input type=text name=format size=40 value=\"\">
</td>
<td>
<select name=format_propose>
<option value=\"\"> --- </option>
<option value=avi> avi </option>
<option value=mp3> mp3 </option>
<option value=zip> zip </option>
</select>
</td>
</tr>
</table>
<h3> Mp3 options </h3>
<table border=0>
<tr>
<td> Album </td>
<td>
<input type=text name=album size=40 value=\"\">
</td>
</tr>
<tr>
<td class=\"txt\"> Artist </td>
<td>
<input type=text name=artist size=40 value=\"\">
</td>
</tr>
<tr>
<td> Title </td>
<td>
<input type=text name=title size=40 value=\"\">
</td>
</tr>
<tr>
<td>
Min bitrate
</td>
<td>
<select name=bitrate>
<option value=\"\"> --- </option>
<option value=64> 64 </option>
<option value=96> 96 </option>
<option value=128> 128 </option>
<option value=160> 160 </option>
<option value=192> 192 </option>
</select>
</td>
</tr>
</table>
<h3> Boolean options </h3>
<table border=0>
<tr>
<td> And </td>
<td>
<input type=text name=and size=40 value=\"\">
</td>
</tr>
<tr>
<td> Or </td>
<td>
<input type=text name=or size=40 value=\"\">
</td>
</tr>
<tr>
<td> Not </td>
<td>
<input type=text name=not size=40 value=\"\">
</td>
</tr>
";
Printf.bprintf buf "
<tr>
<td> Network </td>
<td>
<select name=network>
<option value=\"\"> --- </option>
";
networks_iter_all (fun net ->
let name = net.network_name in
try
if network_is_enabled net &&
List.mem NetworkHasSearch net.network_flags then
Printf.bprintf buf
"<option value=\"%s\"> %s </option>" name name
with _ -> ()
);
Printf.bprintf buf "
</select></td></tr></table></form></td>";
end;
if not !can_search then begin
html_mods_table_header buf " searchTable " " search " [ ] ;
html_mods_td buf [
( " " , " srh " , " No searchable networks enabled " ) ; ] ;
html_mods_td buf [
("", "srh", "No searchable networks enabled"); ];
*)
Printf.bprintf buf "<td><div class=\"results\">
<table id=\"memstatsTable\" name=\"searchTable\" class=\"search\" cellspacing=0 cellpadding=0>
<tr><td class=\"srh\" >No searchable networks enabled</td>";
Buffer.add_string buf "</tr></table></div></td>\n"
end;
Printf.bprintf buf "
< h3 > No searchable networks enabled < /h3 >
" ;
Printf.bprintf buf "
<h3> No searchable networks enabled </h3>
";
*)
Buffer.add_string buf
"
</table>
</div>
"
let search_forget user s =
networks_iter (fun n -> network_forget_search n s);
Hashtbl.remove searches_by_num s.search_num;
user.ui_user_searches <- List2.removeq s user.ui_user_searches
let search_close s =
networks_iter (fun n -> network_close_search n s)
let search_media_list =
[ "Program", "Pro";
"Documentation", "Doc";
"Collection", "Col";
]
* Transforme une query_entry en provenance
en query . Les conversions pour Media sont faites
au vol , pour donkey .
en query. Les conversions pour Media sont faites
au vol, pour donkey.*)
let or_comb q1 q2 = QOr (q1,q2)
let and_comb q1 q2 = QAnd (q1,q2)
let andnot q1 q2 = QAndNot (q1,q2)
let rec mftp_query_of_query_entry qe =
match qe with
Q_AND ([]) -> QNone
| Q_AND [_] -> lprintf_nl "Q_AND [_]"; QNone
| Q_COMBO _ -> assert false
| Q_AND (h :: q) ->
List.fold_left
(fun acc -> fun q -> QAnd (acc, mftp_query_of_query_entry q))
(mftp_query_of_query_entry h)
q
| Q_OR [_] -> lprintf_nl "Q_OR [_]"; QNone
| Q_OR ([]) -> QNone
| Q_OR (h :: q) ->
List.fold_left
(fun acc -> fun q -> QOr (acc, mftp_query_of_query_entry q))
(mftp_query_of_query_entry h)
q
| Q_ANDNOT (q1,q2) ->
QAndNot
(mftp_query_of_query_entry q1,
mftp_query_of_query_entry q2)
| Q_MODULE (_, q) ->
mftp_query_of_query_entry q
| Q_KEYWORDS (_,s) ->
(
try want_and_not andnot (fun w -> QHasWord w) QNone s
with Not_found -> QNone
)
| Q_MINSIZE (_,s) ->
(
try QHasMinVal (Field_Size, Int64.of_string s)
with _ -> QNone
)
| Q_MAXSIZE (_,s) ->
(
try QHasMaxVal (Field_Size, Int64.of_string s)
with _ -> QNone
)
| Q_FORMAT (_,s) ->
(
try
want_comb_not andnot or_comb (fun w -> QHasField(Field_Format, w)) QNone s
with Not_found ->
QNone
)
| Q_MEDIA (_,s) ->
(
try QHasField(Field_Type, List.assoc s search_media_list)
with Not_found ->
match String2.split_simplify s ' ' with
[] -> QNone
| _ -> QHasField (Field_Type, s)
)
| Q_MP3_ARTIST (_,s) ->
(
try
want_comb_not andnot and_comb
(fun w -> QHasField(Field_Artist, w)) QNone s
with Not_found ->
QNone
)
| Q_MP3_TITLE (_,s) ->
(
try
want_comb_not andnot and_comb
(fun w -> QHasField(Field_Title, w)) QNone s
with Not_found ->
QNone
)
| Q_MP3_ALBUM (_,s) ->
(
try
want_comb_not andnot and_comb
(fun w -> QHasField(Field_Album, w)) QNone s
with Not_found ->
QNone
)
| Q_MP3_BITRATE (_,s) ->
begin
try
let bitrate = Int64.of_string s
in
QHasMinVal(Field_KNOWN "bitrate", bitrate)
with _ -> QNone
end
| Q_HIDDEN [q] ->
mftp_query_of_query_entry q
| Q_HIDDEN l ->
mftp_query_of_query_entry (Q_AND l)
module Search = struct
let add_search_result s r =
search_add_result_in s (find_result r.result_num)
end
module Filter = IndexedResults.MakeIndex(Search)
module Local = IndexedResults.MakeIndex(Search)
let clean_local_search = ref 0
let local_search s =
add_timer 330. (fun _ ->
if !clean_local_search < last_time () then begin
Local.clear ();
clean_local_search := 0
end
);
if !clean_local_search = 0 then begin
Local.clear ();
results_iter (fun _ r -> Local.add r)
end;
clean_local_search := last_time () + 300;
Local.find s
let result_format_of_name name =
match String.lowercase (Filename2.last_extension name ) with
".mpeg" -> "mpg"
| ".jpeg" -> "jpg"
| "" -> ""
| s ->
let n = String.sub s 1 (String.length s - 1) in
n
let result_media_of_name name =
match String.lowercase (Filename2.last_extension name ) with
".mpg" | ".mpeg" | ".avi" | ".ogm" | ".divx" | ".mov" -> "Video"
| ".mp3" | ".wav" | ".ogg" -> "Audio"
| ".txt" | ".doc" -> "Doc"
| ".exe" -> "Pro"
| ".jpg" | ".jpeg" | ".tiff" | ".png" | ".gif" -> "Image"
| _ -> ""
let _ =
Heap.add_memstat "CommonSearch" (fun level buf ->
let mem = Filter.stats () in
Printf.bprintf buf " Filtering index memory: %d\n" mem;
let mem = Local.stats () in
Printf.bprintf buf " Local index memory: %d\n" mem;
let counter = ref 0 in
let items = ref 0 in
Hashtbl.iter (fun _ s ->
incr counter;
items := !items + Intmap.length s.search_results
) searches_by_num;
Printf.bprintf buf " Memorized searches: %d\n" !counter;
Printf.bprintf buf " Memorized items: %d\n" !items;
)
|
5989e7b85c6a33db2c2e69853c0e821bce8f3ad4bd14ea4fe05600e43af9a852 | Denommus/LuaOCaml | ast.ml | type unop =
UMinus
| Not
| Octo
[@@deriving show]
type binop =
And
| Or
| Plus
| Minus
| Times
| Div
| Mod
| Exp
| DoubleDot
| Lt
| Lte
| Gt
| Gte
| Eq
| Diff
[@@deriving show]
type funcname = FuncName of var * bool
and var = Name of string
| NestedVar of exp * exp
and exp =
Nil
| False
| True
| Number of float
| String of string
| Tripledot
| FunctionDef of funcbody
| Binop of binop * exp * exp
| Unop of unop * exp
| Var of var
| ExpNested of exp * string
| FuncallPref of functioncall
| Table of field list
and functioncall =
Funcall of exp * exp list
and stat =
EmptyStat
| Assign of (var * exp) list
| FuncallStat of functioncall
| Label of string
| Break
| Goto of string
| BlockStat of block
| WhileStat of exp * block
| RepeatStat of exp * block
| IfStat of exp * block * (exp * block) list * block option
| ForStat of string * exp * exp * exp option * block
| ForInStat of string list * exp list * block
| LocalAssign of var list * exp list option
and field =
AssignField of exp * exp
| NameField of string * exp
| ExpField of exp
bool : vararg
and funcbody = FuncBody of (string list * bool) * block
and retstat = Retstat of exp list
and block = Block of stat list * retstat option
[@@deriving show]
| null | https://raw.githubusercontent.com/Denommus/LuaOCaml/b562a6fd79cf2497f53aafd4f9a4e63370854dd9/library/ast.ml | ocaml | type unop =
UMinus
| Not
| Octo
[@@deriving show]
type binop =
And
| Or
| Plus
| Minus
| Times
| Div
| Mod
| Exp
| DoubleDot
| Lt
| Lte
| Gt
| Gte
| Eq
| Diff
[@@deriving show]
type funcname = FuncName of var * bool
and var = Name of string
| NestedVar of exp * exp
and exp =
Nil
| False
| True
| Number of float
| String of string
| Tripledot
| FunctionDef of funcbody
| Binop of binop * exp * exp
| Unop of unop * exp
| Var of var
| ExpNested of exp * string
| FuncallPref of functioncall
| Table of field list
and functioncall =
Funcall of exp * exp list
and stat =
EmptyStat
| Assign of (var * exp) list
| FuncallStat of functioncall
| Label of string
| Break
| Goto of string
| BlockStat of block
| WhileStat of exp * block
| RepeatStat of exp * block
| IfStat of exp * block * (exp * block) list * block option
| ForStat of string * exp * exp * exp option * block
| ForInStat of string list * exp list * block
| LocalAssign of var list * exp list option
and field =
AssignField of exp * exp
| NameField of string * exp
| ExpField of exp
bool : vararg
and funcbody = FuncBody of (string list * bool) * block
and retstat = Retstat of exp list
and block = Block of stat list * retstat option
[@@deriving show]
|
|
84e830bf2e883cb7220da70e5aff4ad0a0004afbf309fba37f57cb777dd0fca8 | tolysz/prepare-ghcjs | Functor.hs | # LANGUAGE Trustworthy #
# LANGUAGE NoImplicitPrelude #
-----------------------------------------------------------------------------
-- |
-- Module : Data.Functor
Copyright : ( c ) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
Functors : uniform action over a parameterized type , generalizing the
-- 'Data.List.map' function on lists.
module Data.Functor
(
Functor(fmap),
(<$),
($>),
(<$>),
void,
) where
import GHC.Base ( Functor(..), flip )
-- $setup
Allow the use of Prelude in doctests .
> > > import Prelude
infixl 4 <$>
-- | An infix synonym for 'fmap'.
--
-- The name of this operator is an allusion to '$'.
-- Note the similarities between their types:
--
-- > ($) :: (a -> b) -> a -> b
-- > (<$>) :: Functor f => (a -> b) -> f a -> f b
--
-- Whereas '$' is function application, '<$>' is function
-- application lifted over a 'Functor'.
--
-- ==== __Examples__
--
Convert from a @'Maybe ' ' Int'@ to a @'Maybe ' ' String'@ using ' show ' :
--
-- >>> show <$> Nothing
-- Nothing
> > > show < $ > Just 3
Just " 3 "
--
-- Convert from an @'Either' 'Int' 'Int'@ to an @'Either' 'Int'@
-- 'String' using 'show':
--
> > > show < $ > Left 17
-- Left 17
> > > show < $ > Right 17
Right " 17 "
--
-- Double each element of a list:
--
> > > ( * 2 ) < $ > [ 1,2,3 ]
[ 2,4,6 ]
--
Apply ' even ' to the second element of a pair :
--
> > > even < $ > ( 2,2 )
( 2,True )
--
(<$>) :: Functor f => (a -> b) -> f a -> f b
(<$>) = fmap
infixl 4 $>
-- | Flipped version of '<$'.
--
-- @since 4.7.0.0
--
-- ==== __Examples__
--
-- Replace the contents of a @'Maybe' 'Int'@ with a constant 'String':
--
-- >>> Nothing $> "foo"
-- Nothing
-- >>> Just 90210 $> "foo"
-- Just "foo"
--
-- Replace the contents of an @'Either' 'Int' 'Int'@ with a constant
-- 'String', resulting in an @'Either' 'Int' 'String'@:
--
-- >>> Left 8675309 $> "foo"
-- Left 8675309
-- >>> Right 8675309 $> "foo"
-- Right "foo"
--
-- Replace each element of a list with a constant 'String':
--
-- >>> [1,2,3] $> "foo"
-- ["foo","foo","foo"]
--
Replace the second element of a pair with a constant ' String ' :
--
-- >>> (1,2) $> "foo"
-- (1,"foo")
--
($>) :: Functor f => f a -> b -> f b
($>) = flip (<$)
-- | @'void' value@ discards or ignores the result of evaluation, such
-- as the return value of an 'System.IO.IO' action.
--
-- ==== __Examples__
--
-- Replace the contents of a @'Maybe' 'Int'@ with unit:
--
-- >>> void Nothing
-- Nothing
-- >>> void (Just 3)
-- Just ()
--
-- Replace the contents of an @'Either' 'Int' 'Int'@ with unit,
-- resulting in an @'Either' 'Int' '()'@:
--
-- >>> void (Left 8675309)
-- Left 8675309
-- >>> void (Right 8675309)
-- Right ()
--
-- Replace every element of a list with unit:
--
-- >>> void [1,2,3]
-- [(),(),()]
--
Replace the second element of a pair with unit :
--
-- >>> void (1,2)
( 1 , ( ) )
--
-- Discard the result of an 'System.IO.IO' action:
--
-- >>> mapM print [1,2]
1
2
-- [(),()]
-- >>> void $ mapM print [1,2]
1
2
--
void :: Functor f => f a -> f ()
void x = () <$ x
| null | https://raw.githubusercontent.com/tolysz/prepare-ghcjs/8499e14e27854a366e98f89fab0af355056cf055/spec-lts8/base/Data/Functor.hs | haskell | ---------------------------------------------------------------------------
|
Module : Data.Functor
License : BSD-style (see the file libraries/base/LICENSE)
Maintainer :
Stability : provisional
Portability : portable
'Data.List.map' function on lists.
$setup
| An infix synonym for 'fmap'.
The name of this operator is an allusion to '$'.
Note the similarities between their types:
> ($) :: (a -> b) -> a -> b
> (<$>) :: Functor f => (a -> b) -> f a -> f b
Whereas '$' is function application, '<$>' is function
application lifted over a 'Functor'.
==== __Examples__
>>> show <$> Nothing
Nothing
Convert from an @'Either' 'Int' 'Int'@ to an @'Either' 'Int'@
'String' using 'show':
Left 17
Double each element of a list:
| Flipped version of '<$'.
@since 4.7.0.0
==== __Examples__
Replace the contents of a @'Maybe' 'Int'@ with a constant 'String':
>>> Nothing $> "foo"
Nothing
>>> Just 90210 $> "foo"
Just "foo"
Replace the contents of an @'Either' 'Int' 'Int'@ with a constant
'String', resulting in an @'Either' 'Int' 'String'@:
>>> Left 8675309 $> "foo"
Left 8675309
>>> Right 8675309 $> "foo"
Right "foo"
Replace each element of a list with a constant 'String':
>>> [1,2,3] $> "foo"
["foo","foo","foo"]
>>> (1,2) $> "foo"
(1,"foo")
| @'void' value@ discards or ignores the result of evaluation, such
as the return value of an 'System.IO.IO' action.
==== __Examples__
Replace the contents of a @'Maybe' 'Int'@ with unit:
>>> void Nothing
Nothing
>>> void (Just 3)
Just ()
Replace the contents of an @'Either' 'Int' 'Int'@ with unit,
resulting in an @'Either' 'Int' '()'@:
>>> void (Left 8675309)
Left 8675309
>>> void (Right 8675309)
Right ()
Replace every element of a list with unit:
>>> void [1,2,3]
[(),(),()]
>>> void (1,2)
Discard the result of an 'System.IO.IO' action:
>>> mapM print [1,2]
[(),()]
>>> void $ mapM print [1,2]
| # LANGUAGE Trustworthy #
# LANGUAGE NoImplicitPrelude #
Copyright : ( c ) The University of Glasgow 2001
Functors : uniform action over a parameterized type , generalizing the
module Data.Functor
(
Functor(fmap),
(<$),
($>),
(<$>),
void,
) where
import GHC.Base ( Functor(..), flip )
Allow the use of Prelude in doctests .
> > > import Prelude
infixl 4 <$>
Convert from a @'Maybe ' ' Int'@ to a @'Maybe ' ' String'@ using ' show ' :
> > > show < $ > Just 3
Just " 3 "
> > > show < $ > Left 17
> > > show < $ > Right 17
Right " 17 "
> > > ( * 2 ) < $ > [ 1,2,3 ]
[ 2,4,6 ]
Apply ' even ' to the second element of a pair :
> > > even < $ > ( 2,2 )
( 2,True )
(<$>) :: Functor f => (a -> b) -> f a -> f b
(<$>) = fmap
infixl 4 $>
Replace the second element of a pair with a constant ' String ' :
($>) :: Functor f => f a -> b -> f b
($>) = flip (<$)
Replace the second element of a pair with unit :
( 1 , ( ) )
1
2
1
2
void :: Functor f => f a -> f ()
void x = () <$ x
|
d894a5cba8c4f9f86af1faea9e1b2ee6420ba50f76f75d191ba0210fd2964e6f | pfeodrippe/ummoi | example_bb.clj | #!/usr/bin/env bb
Cheers to
;; Taken and modified to add request body parsing from -common/blob/master/wee_httpd.bb
(ns wee-httpd)
(import (java.net ServerSocket))
(require '[clojure.string :as string]
'[clojure.java.io :as io]
'[cheshire.core :as json])
(defn create-worker-thread [client-socket request-handler]
(.start
(Thread.
(fn []
(with-open [out (io/writer (.getOutputStream client-socket))
in (io/reader (.getInputStream client-socket))]
(loop []
(let [[req-line & headers] (loop [headers []]
(let [line (.readLine in)]
(if (string/blank? line)
headers
(recur (conj headers line)))))]
(when-not (nil? req-line)
(let [headers-map (->> headers
(map #(update (string/split % #":" 2) 0 string/lower-case))
(into {}))
content-length (Integer/parseInt (string/trim (get headers-map "content-length")))
status 200
body (-> (loop [buf ""
count 1]
(let [c (.read in)]
(if (>= count content-length)
(str buf (char c))
(recur (str buf (char c)) (inc count)))))
json/parse-string
request-handler
json/generate-string)]
(.write out (format "HTTP/1.1 %s OK\r\nContent-Length: %s\r\n\r\n%s"
status
(count (.getBytes body))
body))
(.flush out)
(recur))))))))))
(defn start-web-server [request-handler]
(println "Server started \\o/")
(.start (Thread. #(with-open
[server-socket (new ServerSocket 4444)]
(while true
(let [client-socket (.accept server-socket)]
(create-worker-thread client-socket request-handler )))))))
(def vars-keys
[:c1 :c2 :account :sender :receiver :money :pc])
(defn handler
[{self "self" vars "vars"}]
(let [vars (zipmap vars-keys vars)
sender (get-in vars [:sender self])
receiver (get-in vars [:receiver self])
money (get-in vars [:money self])]
(-> (:account vars)
(update sender - money)
(update receiver + money))))
(wee-httpd/start-web-server handler)
;; Keep the shell script from returning. When evaling the whole buffer, comment this out.
(while true (Thread/sleep 1000))
| null | https://raw.githubusercontent.com/pfeodrippe/ummoi/46d11cdb684418fea089855abac3c32ffdd37c29/examples/example_bb.clj | clojure | Taken and modified to add request body parsing from -common/blob/master/wee_httpd.bb
Keep the shell script from returning. When evaling the whole buffer, comment this out. | #!/usr/bin/env bb
Cheers to
(ns wee-httpd)
(import (java.net ServerSocket))
(require '[clojure.string :as string]
'[clojure.java.io :as io]
'[cheshire.core :as json])
(defn create-worker-thread [client-socket request-handler]
(.start
(Thread.
(fn []
(with-open [out (io/writer (.getOutputStream client-socket))
in (io/reader (.getInputStream client-socket))]
(loop []
(let [[req-line & headers] (loop [headers []]
(let [line (.readLine in)]
(if (string/blank? line)
headers
(recur (conj headers line)))))]
(when-not (nil? req-line)
(let [headers-map (->> headers
(map #(update (string/split % #":" 2) 0 string/lower-case))
(into {}))
content-length (Integer/parseInt (string/trim (get headers-map "content-length")))
status 200
body (-> (loop [buf ""
count 1]
(let [c (.read in)]
(if (>= count content-length)
(str buf (char c))
(recur (str buf (char c)) (inc count)))))
json/parse-string
request-handler
json/generate-string)]
(.write out (format "HTTP/1.1 %s OK\r\nContent-Length: %s\r\n\r\n%s"
status
(count (.getBytes body))
body))
(.flush out)
(recur))))))))))
(defn start-web-server [request-handler]
(println "Server started \\o/")
(.start (Thread. #(with-open
[server-socket (new ServerSocket 4444)]
(while true
(let [client-socket (.accept server-socket)]
(create-worker-thread client-socket request-handler )))))))
(def vars-keys
[:c1 :c2 :account :sender :receiver :money :pc])
(defn handler
[{self "self" vars "vars"}]
(let [vars (zipmap vars-keys vars)
sender (get-in vars [:sender self])
receiver (get-in vars [:receiver self])
money (get-in vars [:money self])]
(-> (:account vars)
(update sender - money)
(update receiver + money))))
(wee-httpd/start-web-server handler)
(while true (Thread/sleep 1000))
|
a30453c6d87d145563d3045fd1c113eef314fdc71c15150cf8448d553897ed82 | bevuta/pepa | core.cljs | (ns ^:figwheel-always pepa.core
(:require pepa.style
pepa.navigation
[pepa.data :as data]
[pepa.preloader :as preloader]
[pepa.components.root :refer [root-component]]
[pepa.components.draggable :as draggable]
[om.core :as om :include-macros true]))
(enable-console-print!)
;;; Preload Images
(defonce preloaded-images (preloader/preload))
(om/root root-component
data/state
{:target (.getElementById js/window.document "app")
:shared (merge {}
(draggable/shared-data))})
| null | https://raw.githubusercontent.com/bevuta/pepa/0a9991de0fd1714515ca3def645aec30e21cd671/src-cljs/pepa/core.cljs | clojure | Preload Images | (ns ^:figwheel-always pepa.core
(:require pepa.style
pepa.navigation
[pepa.data :as data]
[pepa.preloader :as preloader]
[pepa.components.root :refer [root-component]]
[pepa.components.draggable :as draggable]
[om.core :as om :include-macros true]))
(enable-console-print!)
(defonce preloaded-images (preloader/preload))
(om/root root-component
data/state
{:target (.getElementById js/window.document "app")
:shared (merge {}
(draggable/shared-data))})
|
9cd4dbd1654133f02c3182e28fb8a0887ee5735f94002581370757580e66503a | Leberwurscht/Diaspora-User-Directory | dbMessages.ml | (************************************************************************)
This file is part of SKS . SKS is free software ; you can
redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation ; either
version 2 of the License , or ( at your option ) any later version .
This program is distributed in the hope that it will be useful , but
WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
General Public License for more details .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA
redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA *)
(***********************************************************************)
* Message types for communicating with com ports on dbserver and reconserver
open MoreLabels
open StdLabels
open Packet
open CMarshal
open Common
open Printf
module Unix=UnixLabels
module Set = PSet.Set
(***********************************)
type configvar = [ `int of int | `float of float | `string of string | `none ]
let marshal_config cout (s,cvar) =
marshal_string cout s;
match cvar with
| `int x -> cout#write_byte 0; cout#write_int x
| `float x -> cout#write_byte 1; cout#write_float x
| `string x -> cout#write_byte 2; marshal_string cout x
| `none -> cout #write_byte 3
let unmarshal_config cin =
let s = unmarshal_string cin in
let cvar =
match cin#read_byte with
| 0 -> `int cin#read_int
| 1 -> `float cin#read_float
| 2 -> `string (unmarshal_string cin)
| 3 -> `none
| _ -> failwith "Type failure unmarshalling config variable"
in
(s,cvar)
(***********************************)
(* Data Types ********************)
(***********************************)
type msg = | WordQuery of string list
| LogQuery of (int * timestamp) (* must make other changes.... *)
| HashRequest of string list
| LogResp of ( timestamp * event) list
| Keys of key list
| KeyStrings of string list
| Ack of int
| MissingKeys of (string list * Unix.sockaddr) (* DEPRECATED *)
| Synchronize
| RandomDrop of int
| ProtocolError
| DeleteKey of string
| Config of (string * configvar)
| Filters of string list
(**** data specific marshallers ****)
let marshal_timestamp cout timestamp = cout#write_float timestamp
let unmarshal_timestamp cin = cin#read_float
let marshal_logquery cout logquery =
let (count,timestamp) = logquery in
cout#write_int count;
marshal_timestamp cout timestamp
let unmarshal_logquery cin =
let count = cin#read_int in
let timestamp = unmarshal_timestamp cin in
(count,timestamp)
let marshal_event cout event = match event with
| Add hash -> cout#write_byte 0; marshal_string cout hash
| Delete hash -> cout#write_byte 1; marshal_string cout hash
let unmarshal_event cin =
match cin#read_byte with
0 -> Add (unmarshal_string cin)
| 1 -> Delete (unmarshal_string cin)
| _ -> failwith "Unexpected code for event"
let marshal_log_entry cout ( timestamp , event ) =
marshal_timestamp cout timestamp;
marshal_event cout event
let unmarshal_log_entry cin =
let timestamp = unmarshal_timestamp cin in
let event = unmarshal_event cin in
(timestamp,event)
let marshal_key cout key = marshal_string cout (Key.to_string key)
let unmarshal_key cin = Key.of_string (unmarshal_string cin)
let marshal_key_list l = marshal_list ~f:marshal_key l
let unmarshal_key_list l = unmarshal_list ~f:unmarshal_key l
let marshal_missingkeys cout (list,sockaddr) =
marshal_list ~f:marshal_string cout list;
marshal_sockaddr cout sockaddr
let unmarshal_missingkeys cin =
let list = unmarshal_list ~f:unmarshal_string cin in
let sockaddr = unmarshal_sockaddr cin in
(list,sockaddr)
(********************************************************)
let marshal_msg cout msg =
match msg with
| WordQuery x -> cout#write_byte 0; marshal_list ~f:marshal_string cout x
| LogQuery x -> cout#write_byte 1; marshal_logquery cout x
| LogResp x -> cout#write_byte 2; marshal_list ~f:marshal_log_entry cout x
| Keys x -> cout#write_byte 3; marshal_list ~f:marshal_key cout x
(* keystrings is just an alias for keys. They're sent over the wire
in the same form *)
| KeyStrings x -> cout#write_byte 3; marshal_list ~f:marshal_string cout x
| Ack x -> cout#write_byte 4; cout#write_int x
| MissingKeys x -> failwith "DO NOT USE MissingKeys"
cout#write_byte 5 ; marshal_missingkeys cout x
| Synchronize -> cout#write_byte 6
| RandomDrop x -> cout#write_byte 7; cout#write_int x
| ProtocolError -> cout#write_byte 8
| DeleteKey s -> cout#write_byte 9; marshal_string cout s
| HashRequest x -> cout#write_byte 10; marshal_list ~f:marshal_string cout x
| Config x -> cout#write_byte 11; marshal_config cout x
| Filters x -> cout#write_byte 12; marshal_list ~f:marshal_string cout x
let rec unmarshal_msg cin =
let rval =
match cin#read_byte with
| 0 -> WordQuery (unmarshal_list ~f:unmarshal_string cin)
| 1 -> LogQuery (unmarshal_logquery cin)
| 2 ->
LogResp (unmarshal_list ~f:unmarshal_log_entry cin)
| 3 -> Keys (unmarshal_list ~f:unmarshal_key cin)
| 4 -> Ack cin#read_int
| 5 -> MissingKeys (unmarshal_missingkeys cin)
| 6 -> Synchronize
| 7 -> RandomDrop cin#read_int
| 8 -> ProtocolError
| 9 -> DeleteKey (unmarshal_string cin)
| 10 -> HashRequest (unmarshal_list ~f:unmarshal_string cin)
| 11 -> Config (unmarshal_config cin)
| 12 -> Filters (unmarshal_list ~f:unmarshal_string cin)
| _ -> failwith "Unexpected message type"
in
rval
let sockaddr_to_string sockaddr = match sockaddr with
Unix.ADDR_UNIX s -> sprintf "<ADDR_UNIX %s>" s
| Unix.ADDR_INET (addr,p) -> sprintf "<ADDR_INET [%s]:%d>" (Unix.string_of_inet_addr addr) p
let msg_to_string msg =
match msg with
WordQuery words -> "WordQuery: " ^ (String.concat ", " words)
| LogQuery (count,timestamp) -> sprintf "LogQuery: (%d,%f)" count timestamp
| LogResp list ->
let length = List.length list in
sprintf "LogResp: %d events" length
| Keys keys ->
let length = List.length keys in
sprintf "Keys: %d keys" length
| KeyStrings keystrings ->
let length = List.length keystrings in
sprintf "KeyStrings: %d keystrings" length
| Ack i ->
sprintf "Ack: %d" i
| MissingKeys (keys,sockaddr) ->
if List.length keys > 20 then
sprintf "MissingKeys: %d keys from %s"
(List.length keys) (sockaddr_to_string sockaddr)
else
sprintf "MissingKeys from %s: [ %s ]"
(sockaddr_to_string sockaddr)
(String.concat ~sep:""
(List.map ~f:(sprintf "\n\t%s")
(List.map Utils.hexstring keys)))
| Synchronize -> sprintf "Synchronize"
| RandomDrop i ->
sprintf "RandomDrop: %d" i
| ProtocolError -> "ProtocolError"
| DeleteKey x -> sprintf "DeleteKey %s" (Utils.hexstring x)
| HashRequest x -> sprintf "HashRequest(%d)" (List.length x)
| Config (s,cvar) -> sprintf "Config(s," ^
(match cvar with
`int x -> sprintf "%d)" x
| `float x -> sprintf "%f)" x
| `string x -> sprintf "%s)" x
| `none -> "none)"
)
| Filters filters -> sprintf "Filters(%s)"
(String.concat ~sep:"," filters)
module M =
MsgContainer.Container(
struct
type msg_t = msg
let marshal = marshal_msg
let unmarshal = unmarshal_msg
let to_string = msg_to_string
let print = (fun s -> plerror 7 "%s" s)
end
)
include M
| null | https://raw.githubusercontent.com/Leberwurscht/Diaspora-User-Directory/1ca4a06a67d591760516edffddb0308b86b6314c/trie_manager/dbMessages.ml | ocaml | **********************************************************************
*********************************************************************
*********************************
*********************************
Data Types *******************
*********************************
must make other changes....
DEPRECATED
*** data specific marshallers ***
******************************************************
keystrings is just an alias for keys. They're sent over the wire
in the same form | This file is part of SKS . SKS is free software ; you can
redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation ; either
version 2 of the License , or ( at your option ) any later version .
This program is distributed in the hope that it will be useful , but
WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
General Public License for more details .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA
redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA *)
* Message types for communicating with com ports on dbserver and reconserver
open MoreLabels
open StdLabels
open Packet
open CMarshal
open Common
open Printf
module Unix=UnixLabels
module Set = PSet.Set
type configvar = [ `int of int | `float of float | `string of string | `none ]
let marshal_config cout (s,cvar) =
marshal_string cout s;
match cvar with
| `int x -> cout#write_byte 0; cout#write_int x
| `float x -> cout#write_byte 1; cout#write_float x
| `string x -> cout#write_byte 2; marshal_string cout x
| `none -> cout #write_byte 3
let unmarshal_config cin =
let s = unmarshal_string cin in
let cvar =
match cin#read_byte with
| 0 -> `int cin#read_int
| 1 -> `float cin#read_float
| 2 -> `string (unmarshal_string cin)
| 3 -> `none
| _ -> failwith "Type failure unmarshalling config variable"
in
(s,cvar)
type msg = | WordQuery of string list
| HashRequest of string list
| LogResp of ( timestamp * event) list
| Keys of key list
| KeyStrings of string list
| Ack of int
| Synchronize
| RandomDrop of int
| ProtocolError
| DeleteKey of string
| Config of (string * configvar)
| Filters of string list
let marshal_timestamp cout timestamp = cout#write_float timestamp
let unmarshal_timestamp cin = cin#read_float
let marshal_logquery cout logquery =
let (count,timestamp) = logquery in
cout#write_int count;
marshal_timestamp cout timestamp
let unmarshal_logquery cin =
let count = cin#read_int in
let timestamp = unmarshal_timestamp cin in
(count,timestamp)
let marshal_event cout event = match event with
| Add hash -> cout#write_byte 0; marshal_string cout hash
| Delete hash -> cout#write_byte 1; marshal_string cout hash
let unmarshal_event cin =
match cin#read_byte with
0 -> Add (unmarshal_string cin)
| 1 -> Delete (unmarshal_string cin)
| _ -> failwith "Unexpected code for event"
let marshal_log_entry cout ( timestamp , event ) =
marshal_timestamp cout timestamp;
marshal_event cout event
let unmarshal_log_entry cin =
let timestamp = unmarshal_timestamp cin in
let event = unmarshal_event cin in
(timestamp,event)
let marshal_key cout key = marshal_string cout (Key.to_string key)
let unmarshal_key cin = Key.of_string (unmarshal_string cin)
let marshal_key_list l = marshal_list ~f:marshal_key l
let unmarshal_key_list l = unmarshal_list ~f:unmarshal_key l
let marshal_missingkeys cout (list,sockaddr) =
marshal_list ~f:marshal_string cout list;
marshal_sockaddr cout sockaddr
let unmarshal_missingkeys cin =
let list = unmarshal_list ~f:unmarshal_string cin in
let sockaddr = unmarshal_sockaddr cin in
(list,sockaddr)
let marshal_msg cout msg =
match msg with
| WordQuery x -> cout#write_byte 0; marshal_list ~f:marshal_string cout x
| LogQuery x -> cout#write_byte 1; marshal_logquery cout x
| LogResp x -> cout#write_byte 2; marshal_list ~f:marshal_log_entry cout x
| Keys x -> cout#write_byte 3; marshal_list ~f:marshal_key cout x
| KeyStrings x -> cout#write_byte 3; marshal_list ~f:marshal_string cout x
| Ack x -> cout#write_byte 4; cout#write_int x
| MissingKeys x -> failwith "DO NOT USE MissingKeys"
cout#write_byte 5 ; marshal_missingkeys cout x
| Synchronize -> cout#write_byte 6
| RandomDrop x -> cout#write_byte 7; cout#write_int x
| ProtocolError -> cout#write_byte 8
| DeleteKey s -> cout#write_byte 9; marshal_string cout s
| HashRequest x -> cout#write_byte 10; marshal_list ~f:marshal_string cout x
| Config x -> cout#write_byte 11; marshal_config cout x
| Filters x -> cout#write_byte 12; marshal_list ~f:marshal_string cout x
let rec unmarshal_msg cin =
let rval =
match cin#read_byte with
| 0 -> WordQuery (unmarshal_list ~f:unmarshal_string cin)
| 1 -> LogQuery (unmarshal_logquery cin)
| 2 ->
LogResp (unmarshal_list ~f:unmarshal_log_entry cin)
| 3 -> Keys (unmarshal_list ~f:unmarshal_key cin)
| 4 -> Ack cin#read_int
| 5 -> MissingKeys (unmarshal_missingkeys cin)
| 6 -> Synchronize
| 7 -> RandomDrop cin#read_int
| 8 -> ProtocolError
| 9 -> DeleteKey (unmarshal_string cin)
| 10 -> HashRequest (unmarshal_list ~f:unmarshal_string cin)
| 11 -> Config (unmarshal_config cin)
| 12 -> Filters (unmarshal_list ~f:unmarshal_string cin)
| _ -> failwith "Unexpected message type"
in
rval
let sockaddr_to_string sockaddr = match sockaddr with
Unix.ADDR_UNIX s -> sprintf "<ADDR_UNIX %s>" s
| Unix.ADDR_INET (addr,p) -> sprintf "<ADDR_INET [%s]:%d>" (Unix.string_of_inet_addr addr) p
let msg_to_string msg =
match msg with
WordQuery words -> "WordQuery: " ^ (String.concat ", " words)
| LogQuery (count,timestamp) -> sprintf "LogQuery: (%d,%f)" count timestamp
| LogResp list ->
let length = List.length list in
sprintf "LogResp: %d events" length
| Keys keys ->
let length = List.length keys in
sprintf "Keys: %d keys" length
| KeyStrings keystrings ->
let length = List.length keystrings in
sprintf "KeyStrings: %d keystrings" length
| Ack i ->
sprintf "Ack: %d" i
| MissingKeys (keys,sockaddr) ->
if List.length keys > 20 then
sprintf "MissingKeys: %d keys from %s"
(List.length keys) (sockaddr_to_string sockaddr)
else
sprintf "MissingKeys from %s: [ %s ]"
(sockaddr_to_string sockaddr)
(String.concat ~sep:""
(List.map ~f:(sprintf "\n\t%s")
(List.map Utils.hexstring keys)))
| Synchronize -> sprintf "Synchronize"
| RandomDrop i ->
sprintf "RandomDrop: %d" i
| ProtocolError -> "ProtocolError"
| DeleteKey x -> sprintf "DeleteKey %s" (Utils.hexstring x)
| HashRequest x -> sprintf "HashRequest(%d)" (List.length x)
| Config (s,cvar) -> sprintf "Config(s," ^
(match cvar with
`int x -> sprintf "%d)" x
| `float x -> sprintf "%f)" x
| `string x -> sprintf "%s)" x
| `none -> "none)"
)
| Filters filters -> sprintf "Filters(%s)"
(String.concat ~sep:"," filters)
module M =
MsgContainer.Container(
struct
type msg_t = msg
let marshal = marshal_msg
let unmarshal = unmarshal_msg
let to_string = msg_to_string
let print = (fun s -> plerror 7 "%s" s)
end
)
include M
|
34fa6e36c1873bcfc5dca1d2560862ea249755a35bc612b0a1717981e6381667 | fortytools/holumbus | PortRegistryData.hs | -- ----------------------------------------------------------------------------
|
Module : Holumbus . Network . PortRegistry . PortRegistryData
Copyright : Copyright ( C ) 2008
License : MIT
Maintainer : ( )
Stability : experimental
Portability : portable
Version : 0.1
This module contains the main datatype for the PortRegistry .
Module : Holumbus.Network.PortRegistry.PortRegistryData
Copyright : Copyright (C) 2008 Stefan Schmidt
License : MIT
Maintainer : Stefan Schmidt ()
Stability : experimental
Portability: portable
Version : 0.1
This module contains the main datatype for the PortRegistry.
-}
-- ----------------------------------------------------------------------------
module Holumbus.Network.PortRegistry.PortRegistryData
# DEPRECATED " this module will be remove in the next release , please use the packages from Holumbus . Distribution . * " #
(
*
PortRegistryData
-- * Creation and Destruction
, newPortRegistryData
, closePortRegistryData
, getPortRegistryRequestPort
*
, setPortRegistry
)
where
import Control.Concurrent
import qualified Data.Map as Map
import Network
import System.Log.Logger
import Holumbus.Common.Threading
import Holumbus.Network.Port
import Holumbus.Network.Messages
import Holumbus.Network.PortRegistry
import Holumbus.Network.PortRegistry.Messages
localLogger :: String
localLogger = "Holumbus.Network.PortRegistry.PortRegistryData"
-- ----------------------------------------------------------------------------
-- ----------------------------------------------------------------------------
| The data needed by the PortRegistry
data PortRegistryData = PortRegistryData {
prd_ServerThreadId :: Thread -- ^ The thread-data of the message-dispatcher thread.
, prd_OwnStream :: PortRegistryRequestStream -- ^ The Stream for all incomming messages.
, prd_SocketMap :: MVar (Map.Map StreamName SocketId) -- ^ The map storing the port-data (the real registry).
}
-- ----------------------------------------------------------------------------
-- Creation and Destruction
-- ----------------------------------------------------------------------------
-- | Creates a new PortRegistry.
newPortRegistryData :: StreamName -> Maybe PortNumber -> IO PortRegistryData
newPortRegistryData sn pn
= do
st <- (newStream STLocal (Just sn) pn)::IO PortRegistryRequestStream
mMVar <- newMVar Map.empty
sMVar <- newThread
let prd = PortRegistryData sMVar st mMVar
startRequestDispatcher sMVar st (dispatch prd)
return prd
-- | Closes the PortRegistry with its streams and threads.
closePortRegistryData :: PortRegistryData -> IO ()
closePortRegistryData prd
= do
stopRequestDispatcher (prd_ServerThreadId prd)
closeStream (prd_OwnStream prd)
return ()
-- | Get the RequestPort of the PortRegistry.
It can be used to give access to the PortRegistry , eg . you can serialize
-- this information and transfer it over the network to grant access to the
-- clients.
getPortRegistryRequestPort :: PortRegistryData -> IO PortRegistryRequestPort
getPortRegistryRequestPort prd = newPortFromStream (prd_OwnStream prd)
-- | The main dispatch-function. It handles the incomming messages and reacts.
dispatch
:: PortRegistryData
-> PortRegistryRequestMessage
-> PortRegistryResponsePort
-> IO ()
dispatch prd msg replyPort
= do
case msg of
(PRReqRegister sn soid) ->
do
handleRequest replyPort (registerPort sn soid prd) (\_ -> PRRspSuccess)
return ()
(PRReqUnregister sn) ->
do
handleRequest replyPort (unregisterPort sn prd) (\_ -> PRRspSuccess)
return ()
(PRReqLookup sn) ->
do
handleRequest replyPort (lookupPort sn prd) (\soid -> PRRspLookup soid)
return ()
(PRReqGetPorts) ->
do
handleRequest replyPort (getPorts prd) (\ls -> PRRspGetPorts ls)
return ()
_ ->
do
infoM localLogger $ "dispatch: unknown request " ++ show msg
handleRequest replyPort (return ()) (\_ -> PRRspUnknown)
-- ----------------------------------------------------------------------------
( PortRegistry )
-- ----------------------------------------------------------------------------
The PortRegistry - typeclass instanciation for the PortRegistryData .
instance PortRegistry PortRegistryData where
registerPort sn soid prd
= do
infoM localLogger $ "register: " ++ sn ++ " - at: " ++ show soid
modifyMVar (prd_SocketMap prd) $
\sm -> return (Map.insert sn soid sm, ())
unregisterPort sn prd
= do
infoM localLogger $ "unregister: " ++ sn
modifyMVar (prd_SocketMap prd) $
\sm -> return (Map.delete sn sm, ())
lookupPort sn prd
= do
infoM localLogger $ "looking up: " ++ sn
soid <- withMVar (prd_SocketMap prd) $
\sm -> return (Map.lookup sn sm)
infoM localLogger $ "result for: " ++ sn ++ " -> " ++ show soid
return soid
getPorts prd
= do
infoM localLogger $ "getting all ports"
withMVar (prd_SocketMap prd) $
\sm -> return (Map.toList sm)
| null | https://raw.githubusercontent.com/fortytools/holumbus/4b2f7b832feab2715a4d48be0b07dca018eaa8e8/distribution/source/Holumbus/Network/PortRegistry/PortRegistryData.hs | haskell | ----------------------------------------------------------------------------
----------------------------------------------------------------------------
* Creation and Destruction
----------------------------------------------------------------------------
----------------------------------------------------------------------------
^ The thread-data of the message-dispatcher thread.
^ The Stream for all incomming messages.
^ The map storing the port-data (the real registry).
----------------------------------------------------------------------------
Creation and Destruction
----------------------------------------------------------------------------
| Creates a new PortRegistry.
| Closes the PortRegistry with its streams and threads.
| Get the RequestPort of the PortRegistry.
this information and transfer it over the network to grant access to the
clients.
| The main dispatch-function. It handles the incomming messages and reacts.
----------------------------------------------------------------------------
---------------------------------------------------------------------------- | |
Module : Holumbus . Network . PortRegistry . PortRegistryData
Copyright : Copyright ( C ) 2008
License : MIT
Maintainer : ( )
Stability : experimental
Portability : portable
Version : 0.1
This module contains the main datatype for the PortRegistry .
Module : Holumbus.Network.PortRegistry.PortRegistryData
Copyright : Copyright (C) 2008 Stefan Schmidt
License : MIT
Maintainer : Stefan Schmidt ()
Stability : experimental
Portability: portable
Version : 0.1
This module contains the main datatype for the PortRegistry.
-}
module Holumbus.Network.PortRegistry.PortRegistryData
# DEPRECATED " this module will be remove in the next release , please use the packages from Holumbus . Distribution . * " #
(
*
PortRegistryData
, newPortRegistryData
, closePortRegistryData
, getPortRegistryRequestPort
*
, setPortRegistry
)
where
import Control.Concurrent
import qualified Data.Map as Map
import Network
import System.Log.Logger
import Holumbus.Common.Threading
import Holumbus.Network.Port
import Holumbus.Network.Messages
import Holumbus.Network.PortRegistry
import Holumbus.Network.PortRegistry.Messages
localLogger :: String
localLogger = "Holumbus.Network.PortRegistry.PortRegistryData"
| The data needed by the PortRegistry
data PortRegistryData = PortRegistryData {
}
newPortRegistryData :: StreamName -> Maybe PortNumber -> IO PortRegistryData
newPortRegistryData sn pn
= do
st <- (newStream STLocal (Just sn) pn)::IO PortRegistryRequestStream
mMVar <- newMVar Map.empty
sMVar <- newThread
let prd = PortRegistryData sMVar st mMVar
startRequestDispatcher sMVar st (dispatch prd)
return prd
closePortRegistryData :: PortRegistryData -> IO ()
closePortRegistryData prd
= do
stopRequestDispatcher (prd_ServerThreadId prd)
closeStream (prd_OwnStream prd)
return ()
It can be used to give access to the PortRegistry , eg . you can serialize
getPortRegistryRequestPort :: PortRegistryData -> IO PortRegistryRequestPort
getPortRegistryRequestPort prd = newPortFromStream (prd_OwnStream prd)
dispatch
:: PortRegistryData
-> PortRegistryRequestMessage
-> PortRegistryResponsePort
-> IO ()
dispatch prd msg replyPort
= do
case msg of
(PRReqRegister sn soid) ->
do
handleRequest replyPort (registerPort sn soid prd) (\_ -> PRRspSuccess)
return ()
(PRReqUnregister sn) ->
do
handleRequest replyPort (unregisterPort sn prd) (\_ -> PRRspSuccess)
return ()
(PRReqLookup sn) ->
do
handleRequest replyPort (lookupPort sn prd) (\soid -> PRRspLookup soid)
return ()
(PRReqGetPorts) ->
do
handleRequest replyPort (getPorts prd) (\ls -> PRRspGetPorts ls)
return ()
_ ->
do
infoM localLogger $ "dispatch: unknown request " ++ show msg
handleRequest replyPort (return ()) (\_ -> PRRspUnknown)
( PortRegistry )
The PortRegistry - typeclass instanciation for the PortRegistryData .
instance PortRegistry PortRegistryData where
registerPort sn soid prd
= do
infoM localLogger $ "register: " ++ sn ++ " - at: " ++ show soid
modifyMVar (prd_SocketMap prd) $
\sm -> return (Map.insert sn soid sm, ())
unregisterPort sn prd
= do
infoM localLogger $ "unregister: " ++ sn
modifyMVar (prd_SocketMap prd) $
\sm -> return (Map.delete sn sm, ())
lookupPort sn prd
= do
infoM localLogger $ "looking up: " ++ sn
soid <- withMVar (prd_SocketMap prd) $
\sm -> return (Map.lookup sn sm)
infoM localLogger $ "result for: " ++ sn ++ " -> " ++ show soid
return soid
getPorts prd
= do
infoM localLogger $ "getting all ports"
withMVar (prd_SocketMap prd) $
\sm -> return (Map.toList sm)
|
b6c42da98200dbc7374e134bbcb6f95d55a54c1a27b847f03094090c8754b07a | Novus-School/novus | datomic.clj | (ns griffin.components.datomic
(:require [datomic.client.api :as d]
; [novus.validation :as validation]
[clojure.edn :as edn]
[clojure.java.io :as io]))
(defn ident-has-attr?
[db ident attr]
(contains? (d/pull db {:eid ident :selector '[*]}) attr))
;;
(defn load-dataset
[conn]
(let [db (d/db conn)
tx #(d/transact conn {:tx-data %})]
(when-not (ident-has-attr? db :student/id :db/ident)
(tx (-> (io/resource "novus/schema.edn") slurp edn/read-string))
(tx (-> (io/resource "novus/seed.edn") slurp edn/read-string)))))
| null | https://raw.githubusercontent.com/Novus-School/novus/505ac5c6126a588ff833d0efca1526e89e0fc66e/novus/src/main/griffin/components/datomic.clj | clojure | [novus.validation :as validation]
| (ns griffin.components.datomic
(:require [datomic.client.api :as d]
[clojure.edn :as edn]
[clojure.java.io :as io]))
(defn ident-has-attr?
[db ident attr]
(contains? (d/pull db {:eid ident :selector '[*]}) attr))
(defn load-dataset
[conn]
(let [db (d/db conn)
tx #(d/transact conn {:tx-data %})]
(when-not (ident-has-attr? db :student/id :db/ident)
(tx (-> (io/resource "novus/schema.edn") slurp edn/read-string))
(tx (-> (io/resource "novus/seed.edn") slurp edn/read-string)))))
|
45dccad0412cf0094b4b1d1dbcc132070d0f87f9381cb648effa4420d9d85075 | ocharles/blog | 2013-12-07-threepenny-gui.hs | import Control.Monad (void)
import Control.Concurrent.STM
import Data.Map (Map)
import Data.Set (Set)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Graphics.UI.Threepenny.Core
import qualified Graphics.UI.Threepenny as UI
type Database = Map UserName ToDoList
type UserName = String
type ToDoList = Set String
main :: IO ()
main = do
database <- atomically $ newTVar (Map.empty)
startGUI defaultConfig (setup database)
setup :: TVar Database -> Window -> UI ()
setup database rootWindow = void $ do
userNameInput <- UI.input # set (attr "placeholder") "User name"
loginButton <- UI.button #+ [ string "Login" ]
getBody rootWindow #+
map element [ userNameInput, loginButton ]
on UI.click loginButton $ \_ -> do
userName <- get value userNameInput
currentItems <- fmap Set.toList $ liftIO $ atomically $ do
db <- readTVar database
case Map.lookup userName db of
Nothing -> do
writeTVar database (Map.insert userName Set.empty db)
return Set.empty
Just items -> return items
let showItem item = UI.li #+ [ string item ]
toDoContainer <- UI.ul #+ map showItem currentItems
newItem <- UI.input
on UI.sendValue newItem $ \input -> do
liftIO $ atomically $ modifyTVar database $
Map.adjust (Set.insert input) userName
set UI.value "" (element newItem)
element toDoContainer #+ [ showItem input ]
header <- UI.h1 #+ [ string $ userName ++ "'s To-Do List" ]
set children
[ header, toDoContainer, newItem ]
(getBody rootWindow)
| null | https://raw.githubusercontent.com/ocharles/blog/fa8e911d3c03b134eee891d187a1bb574f23a530/code/2013-12-07-threepenny-gui.hs | haskell | import Control.Monad (void)
import Control.Concurrent.STM
import Data.Map (Map)
import Data.Set (Set)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Graphics.UI.Threepenny.Core
import qualified Graphics.UI.Threepenny as UI
type Database = Map UserName ToDoList
type UserName = String
type ToDoList = Set String
main :: IO ()
main = do
database <- atomically $ newTVar (Map.empty)
startGUI defaultConfig (setup database)
setup :: TVar Database -> Window -> UI ()
setup database rootWindow = void $ do
userNameInput <- UI.input # set (attr "placeholder") "User name"
loginButton <- UI.button #+ [ string "Login" ]
getBody rootWindow #+
map element [ userNameInput, loginButton ]
on UI.click loginButton $ \_ -> do
userName <- get value userNameInput
currentItems <- fmap Set.toList $ liftIO $ atomically $ do
db <- readTVar database
case Map.lookup userName db of
Nothing -> do
writeTVar database (Map.insert userName Set.empty db)
return Set.empty
Just items -> return items
let showItem item = UI.li #+ [ string item ]
toDoContainer <- UI.ul #+ map showItem currentItems
newItem <- UI.input
on UI.sendValue newItem $ \input -> do
liftIO $ atomically $ modifyTVar database $
Map.adjust (Set.insert input) userName
set UI.value "" (element newItem)
element toDoContainer #+ [ showItem input ]
header <- UI.h1 #+ [ string $ userName ++ "'s To-Do List" ]
set children
[ header, toDoContainer, newItem ]
(getBody rootWindow)
|
|
11cf1bedcd26ac8ea3b9e9b67e26a6df8b27489e20d4f575771bb187b2003f48 | clarle/ai-class | project.clj | (defproject unit02 "1.0.0-SNAPSHOT"
:description "ai-class unit 2 algorithms in Clojure"
:dependencies [[org.clojure/clojure "1.2.1"]
[org.clojure/clojure-contrib "1.2.0"]
[incanter "1.2.4"]]
:dev-dependencies [[lein-marginalia "0.6.1"]])
| null | https://raw.githubusercontent.com/clarle/ai-class/44ca6d34380942600fb3a61a09e6a2dc4a4841c1/unit02/clojure/unit02/project.clj | clojure | (defproject unit02 "1.0.0-SNAPSHOT"
:description "ai-class unit 2 algorithms in Clojure"
:dependencies [[org.clojure/clojure "1.2.1"]
[org.clojure/clojure-contrib "1.2.0"]
[incanter "1.2.4"]]
:dev-dependencies [[lein-marginalia "0.6.1"]])
|
|
37993af6f34a2ffb9e20462f0d64c9b6a97f0085ea53ea688fe322af47e658c7 | appleshan/cl-http | sysdcl.lisp | -*- Syntax : Ansi - Common - Lisp ; Base : 10 ; Mode : lisp ; Package : common - lisp - user -*-
;;;
Copyright 1994 - 99 , 2005 , .
;;; All rights reserved.
;;;-------------------------------------------------------------------
;;;
SYSTEM DEFINITION FOR MCL CL - HTTP
;;;
;; If you want to just start up the server using the standard demo configuration,
;; you should load http:mcl;start-server.lisp instead.
;; If you load this file and evaluate the form
;; (http-user:enable-http-service), you can access the URL
;; / and peruse the server documentation.
(in-package :cl-user)
;;;-------------------------------------------------------------------
;;;
;;; DEFINE THE COMMON LISP HTTP SYSTEM
;;;
;; Add feature for process polling
#+ccl-3
(when (fboundp 'ccl::process-poll) (pushnew :process-poll *features*))
Check whether to run the native Open Transport interface
#+ppc-target
(when (probe-file "ccl:library;OpenTransport.lisp")
(pushnew :open-transport *features*))
Establish whether we have multiple reader locks .
#+(and ppc-target CCL-4.3)
(pushnew :multiple-reader-locks *features*)
#+CCL-4.4
(when (ccl::osx-p)
(pushnew :osx *features*)
(pushnew :unix *features*))
;; options are :load :compile :eval-load :compile-load-always, :compile-load
(define-system
(cl-http)
()
Run with the new scheduler which is putatively more efficient -- JCMa 5/15/1999 .
(:in-order-to-compile :compile-load "ccl:library;new-scheduler")
load MCL libraries
(:in-order-to-compile :compile-load "ccl:library;loop") ; loop macro, required for compilation only?
needed for process interface code in MCL 3.0
(:in-order-to-compile :compile-load "ccl:library;lispequ")
locking primitive used by xmactcp
(:in-order-to-compile :compile-load "http:mcl;server;store-conditional")
#+(and ccl-3 (not process-poll)) ; polling process wait facility
(:in-order-to-compile :compile-load "http:mcl;server;process-poll")
#+(and ccl-3 (not :multiple-reader-locks)) ; multiple simultaneous reader locks
(:in-order-to-compile :compile-load "http:mcl;server;lock-multiple-readers")
#+ccl-3 ;; processes that stick around and can be assigned new tasks
(:in-order-to-compile :compile-load "http:mcl;server;task-process")
TCP interface MCL 2.0.1
(:in-order-to-load :compile-load "ccl:library;mactcp")
TCP interface MCL 3.0
(:in-order-to-load :compile-load "http:mcl;server;xmactcp")
#+Open-Transport ; Stream buffer package used by OT native
(:in-order-to-load :compile-load
#+CCL-4.4"ccl:library;io-buffer" ; Released version
#-CCL-4.4"http:mcl;server;xio-buffer")
TCP - OpenTransport Native Interface PPC MCL 3.9 , 4.0 , 4.1 , 4.2 , 4.3 , 4.4
(:in-order-to-load :compile-load
#+CCL-4.4"ccl:library;opentransport" ; Released version
#-CCL-4.4"http:mcl;server;xopentransport")
fast file access loaded for 2.0.1 but built - in for 3.0
(:in-order-to-load :compile-load "ccl:examples;mac-file-io" )
CLOS patch fixes dispatch on strings ( essential for Web Walker )
(:in-order-to-load :compile-load "http:mcl;server;mcl-clos-patch")
#+(and (or ccl-3 ccl-3.1 ccl-4) (not CCL-4.2))
Timer facility for MCL 3.0 , 3.9 , 3.1 , 4.0 ( 3.1/4.0 CD version is buggy )
Released Timer Facility
"http:mcl;server;resources" ; portable resource package
"http:mcl;server;with-timeout.lisp" ; timeouts based on timer facility
;; server code.
"http:server;package" ; all package definitions
#-Open-Transport
TCP stream building on mactcp or xmactcp
#+Open-Transport
"http:mcl;server;tcp-ot-stream" ; TCP stream building on OpenTransport
TCP conditions for MCL 2.0.1 but built into MCL 3.0 mactcp
"http:server;preliminary" ; documentation macros
"http:server;variables" ; variable definitions
"http:mcl;server;package" ; Port Package definitions
"http:mcl;server;www-utils" ; Portable non-Genera utilities
"http:mcl;server;mcl" ; Platform dependent code
"http:mcl;server;log-window" ; Log window and logging
Base 64 utility RFC-1113 and RFC-1341 .
MD5 Digests based on RFC 1321
Fast , cons - free MD5 specialization code
SHA Digests based on Internet FIPS 180
#+ccl-3 "http:smtp;package" ; SMTP package
#+ccl-3 "http:smtp;smtp" ; Simple SMTP mailer
#+ccl-3 "http:smtp;mail" ; Interfaces for sending email
"http:server;task-queue" ; Thread-Safe queuing facility
"http:server;class" ; Server class definitions
"http:server;url-class" ; URL class definitions
"http:server;http-conditions" ; HTTP conditions
property list mixin for CLOS
"http:server;utils" ; utility functions
"http:server;tokenizer" ; Simple tokenizer
"http:server;url" ; Object-Oriented URLs
"http:server;headers" ; HTTP headers
"http:server;host" ; Host objects and operations
"http:server;html2" ; HTML generation
Netscape 1.1 HTML generation
"http:server;vrml-1-0" ; VRML 1.0 Generation
"http:server;image-maps" ; Image maps
Netscape 2.0 HTML generation
Netscape 3.0 HTML generation
"http:server;html-3-2" ; HTML 3.2 Generation
HTML 4.0 Generation
"http:server;xhtml1" ; XHTML 1.0 Generation
"http:server;scripts" ; Client-Side Scripts
Netscape 4.0 HTML generation
"http:server;rss-2-0" ; RSS 2.0 Generation
"http:server;shtml" ; Server-Parsed HTML
"http:mcl;w3p;sysdcl" ; W3P Presentation System
"http:server;report" ; Reporting for HTTP Conditions
"http:server;log" ; Logging HTTP transactions
"http:server;authentication" ; User authentication
"http:server;data-cache" ; Data caching
Main server code
Common Gateway Interface and Server Interface
"http:server;preferences" ; Server preference system
Server Configuration via the Web
Server TCP Interface for MCL 2.0.1
Server TCP Interface for MCL 3.0
Control Browser via AppleEvents
"http:mcl;server;cl-http-menu.lisp"
CLIM Interface Package
CLIM Server Interface
| null | https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/mcl/server/sysdcl.lisp | lisp | Base : 10 ; Mode : lisp ; Package : common - lisp - user -*-
All rights reserved.
-------------------------------------------------------------------
If you want to just start up the server using the standard demo configuration,
you should load http:mcl;start-server.lisp instead.
If you load this file and evaluate the form
(http-user:enable-http-service), you can access the URL
/ and peruse the server documentation.
-------------------------------------------------------------------
DEFINE THE COMMON LISP HTTP SYSTEM
Add feature for process polling
options are :load :compile :eval-load :compile-load-always, :compile-load
loop macro, required for compilation only?
polling process wait facility
multiple simultaneous reader locks
processes that stick around and can be assigned new tasks
Stream buffer package used by OT native
Released version
Released version
portable resource package
timeouts based on timer facility
server code.
all package definitions
TCP stream building on OpenTransport
documentation macros
variable definitions
Port Package definitions
Portable non-Genera utilities
Platform dependent code
Log window and logging
SMTP package
Simple SMTP mailer
Interfaces for sending email
Thread-Safe queuing facility
Server class definitions
URL class definitions
HTTP conditions
utility functions
Simple tokenizer
Object-Oriented URLs
HTTP headers
Host objects and operations
HTML generation
VRML 1.0 Generation
Image maps
HTML 3.2 Generation
XHTML 1.0 Generation
Client-Side Scripts
RSS 2.0 Generation
Server-Parsed HTML
W3P Presentation System
Reporting for HTTP Conditions
Logging HTTP transactions
User authentication
Data caching
Server preference system | Copyright 1994 - 99 , 2005 , .
SYSTEM DEFINITION FOR MCL CL - HTTP
(in-package :cl-user)
#+ccl-3
(when (fboundp 'ccl::process-poll) (pushnew :process-poll *features*))
Check whether to run the native Open Transport interface
#+ppc-target
(when (probe-file "ccl:library;OpenTransport.lisp")
(pushnew :open-transport *features*))
Establish whether we have multiple reader locks .
#+(and ppc-target CCL-4.3)
(pushnew :multiple-reader-locks *features*)
#+CCL-4.4
(when (ccl::osx-p)
(pushnew :osx *features*)
(pushnew :unix *features*))
(define-system
(cl-http)
()
Run with the new scheduler which is putatively more efficient -- JCMa 5/15/1999 .
(:in-order-to-compile :compile-load "ccl:library;new-scheduler")
load MCL libraries
needed for process interface code in MCL 3.0
(:in-order-to-compile :compile-load "ccl:library;lispequ")
locking primitive used by xmactcp
(:in-order-to-compile :compile-load "http:mcl;server;store-conditional")
(:in-order-to-compile :compile-load "http:mcl;server;process-poll")
(:in-order-to-compile :compile-load "http:mcl;server;lock-multiple-readers")
(:in-order-to-compile :compile-load "http:mcl;server;task-process")
TCP interface MCL 2.0.1
(:in-order-to-load :compile-load "ccl:library;mactcp")
TCP interface MCL 3.0
(:in-order-to-load :compile-load "http:mcl;server;xmactcp")
(:in-order-to-load :compile-load
#-CCL-4.4"http:mcl;server;xio-buffer")
TCP - OpenTransport Native Interface PPC MCL 3.9 , 4.0 , 4.1 , 4.2 , 4.3 , 4.4
(:in-order-to-load :compile-load
#-CCL-4.4"http:mcl;server;xopentransport")
fast file access loaded for 2.0.1 but built - in for 3.0
(:in-order-to-load :compile-load "ccl:examples;mac-file-io" )
CLOS patch fixes dispatch on strings ( essential for Web Walker )
(:in-order-to-load :compile-load "http:mcl;server;mcl-clos-patch")
#+(and (or ccl-3 ccl-3.1 ccl-4) (not CCL-4.2))
Timer facility for MCL 3.0 , 3.9 , 3.1 , 4.0 ( 3.1/4.0 CD version is buggy )
Released Timer Facility
#-Open-Transport
TCP stream building on mactcp or xmactcp
#+Open-Transport
TCP conditions for MCL 2.0.1 but built into MCL 3.0 mactcp
Base 64 utility RFC-1113 and RFC-1341 .
MD5 Digests based on RFC 1321
Fast , cons - free MD5 specialization code
SHA Digests based on Internet FIPS 180
property list mixin for CLOS
Netscape 1.1 HTML generation
Netscape 2.0 HTML generation
Netscape 3.0 HTML generation
HTML 4.0 Generation
Netscape 4.0 HTML generation
Main server code
Common Gateway Interface and Server Interface
Server Configuration via the Web
Server TCP Interface for MCL 2.0.1
Server TCP Interface for MCL 3.0
Control Browser via AppleEvents
"http:mcl;server;cl-http-menu.lisp"
CLIM Interface Package
CLIM Server Interface
|
aad32582e70d993c1aa0be988569aef564108e02ae1628bed0b220a7ba14a75a | dyzsr/ocaml-selectml | t165-apply.ml | TEST
include tool - ocaml - lib
flags = " -w -a "
ocaml_script_as_argument = " true "
* setup - ocaml - build - env
* *
include tool-ocaml-lib
flags = "-w -a"
ocaml_script_as_argument = "true"
* setup-ocaml-build-env
** ocaml
*)
open Lib;;
let f _ _ _ _ = 0 in f 0 0 0 0;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 BRANCH 17
11 RESTART
12 GRAB 3
14 CONST0
15 RETURN 4
17 CLOSURE 0 , 12
20 PUSH
21 PUSH_RETADDR 30
23 CONST0
24 PUSHCONST0
25 PUSHCONST0
26 PUSHCONST0
27 PUSHACC7
28 APPLY 4
30 POP 1
32 ATOM0
33 SETGLOBAL T165 - apply
35 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 BRANCH 17
11 RESTART
12 GRAB 3
14 CONST0
15 RETURN 4
17 CLOSURE 0, 12
20 PUSH
21 PUSH_RETADDR 30
23 CONST0
24 PUSHCONST0
25 PUSHCONST0
26 PUSHCONST0
27 PUSHACC7
28 APPLY 4
30 POP 1
32 ATOM0
33 SETGLOBAL T165-apply
35 STOP
**)
| null | https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/tool-ocaml/t165-apply.ml | ocaml | TEST
include tool - ocaml - lib
flags = " -w -a "
ocaml_script_as_argument = " true "
* setup - ocaml - build - env
* *
include tool-ocaml-lib
flags = "-w -a"
ocaml_script_as_argument = "true"
* setup-ocaml-build-env
** ocaml
*)
open Lib;;
let f _ _ _ _ = 0 in f 0 0 0 0;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 BRANCH 17
11 RESTART
12 GRAB 3
14 CONST0
15 RETURN 4
17 CLOSURE 0 , 12
20 PUSH
21 PUSH_RETADDR 30
23 CONST0
24 PUSHCONST0
25 PUSHCONST0
26 PUSHCONST0
27 PUSHACC7
28 APPLY 4
30 POP 1
32 ATOM0
33 SETGLOBAL T165 - apply
35 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 BRANCH 17
11 RESTART
12 GRAB 3
14 CONST0
15 RETURN 4
17 CLOSURE 0, 12
20 PUSH
21 PUSH_RETADDR 30
23 CONST0
24 PUSHCONST0
25 PUSHCONST0
26 PUSHCONST0
27 PUSHACC7
28 APPLY 4
30 POP 1
32 ATOM0
33 SETGLOBAL T165-apply
35 STOP
**)
|
|
647a9abcfe117a74f553b7783ff7fef471fcae7f45f8d55cd7df9eb3aa510ba3 | fare/xcvb | helpers.lisp | #+xcvb (module (:depends-on ("package")))
(in-package #:xcvb-test)
(declaim (optimize (debug 3) (safety 3)))
(defun rm-rfv (x)
(let* ((p (pathname x))
(d (pathname-directory p))
(n (namestring p)))
(assert (not (wild-pathname-p p)))
(assert (consp d))
(assert (eq :absolute (first d)))
(assert (<= 2 (length d)))
(assert (directory-pathname-p p))
(unless (search "xcvb" n)
(break "Do you really want to rm -rfv ~A ???" n))
(run-program
`("/bin/rm" "-rfv" ,n)
:ignore-error-status t)))
(defun rsync (&rest args)
(run `("rsync" ,@args)))
(defvar *driver* nil
"path to the driver")
(defun find-driver ()
(or *driver*
(setf *driver* (asdf:system-relative-pathname :xcvb "driver.lisp"))))
(defvar *asdf* nil
"path to asdf")
(defun find-asdf ()
(or *asdf*
(setf *asdf* (asdf:system-relative-pathname :asdf "asdf.lisp"))))
| null | https://raw.githubusercontent.com/fare/xcvb/460e27bd4cbd4db5e7ddf5b22c2ee455df445258/t/helpers.lisp | lisp | #+xcvb (module (:depends-on ("package")))
(in-package #:xcvb-test)
(declaim (optimize (debug 3) (safety 3)))
(defun rm-rfv (x)
(let* ((p (pathname x))
(d (pathname-directory p))
(n (namestring p)))
(assert (not (wild-pathname-p p)))
(assert (consp d))
(assert (eq :absolute (first d)))
(assert (<= 2 (length d)))
(assert (directory-pathname-p p))
(unless (search "xcvb" n)
(break "Do you really want to rm -rfv ~A ???" n))
(run-program
`("/bin/rm" "-rfv" ,n)
:ignore-error-status t)))
(defun rsync (&rest args)
(run `("rsync" ,@args)))
(defvar *driver* nil
"path to the driver")
(defun find-driver ()
(or *driver*
(setf *driver* (asdf:system-relative-pathname :xcvb "driver.lisp"))))
(defvar *asdf* nil
"path to asdf")
(defun find-asdf ()
(or *asdf*
(setf *asdf* (asdf:system-relative-pathname :asdf "asdf.lisp"))))
|
|
0b2e414434d1a28ffd4e2871900743bf09c75f67ec03a9892cfcb931d8c28990 | nunchaku-inria/nunchaku | nunchaku.ml |
* { 1 Main program }
open Nunchaku_core
module E = CCResult
module A = UntypedAST
module TI = TermInner
module Backends = Nunchaku_backends
module Tr = Nunchaku_transformations
type input =
| I_guess
| I_nunchaku
| I_tptp
| I_tip
let inputs_ =
[ "nunchaku", I_nunchaku
; "tptp", I_tptp
; "tip", I_tip
]
(* TODO: tip output? *)
type output =
| O_nunchaku
| O_tptp
| O_sexp
let outputs_ =
[ "nunchaku", O_nunchaku
; "tptp", O_tptp
; "sexp", O_sexp
]
(* NOTE: also modify list_solvers_ below if you modify this *)
type solver =
| S_CVC4
| S_kodkod
| S_paradox
| S_smbc
let list_solvers_ () = "(available choices: cvc4 kodkod paradox smbc)"
* { 2 Options }
let input_ = ref I_guess
let output_ = ref O_nunchaku
let check_all_ = ref true
let polarize_rec_ = ref false
let pp_ = ref false
let pp_all_ = ref false
let pp_pipeline_ = ref false
let pp_typed_ = ref false
let pp_skolem_ = ref false
let pp_mono_ = ref false
let pp_elim_match_ = ref false
let pp_elim_recursion_ = ref false
let pp_elim_hof_ = ref false
let pp_lambda_lift_ = ref false
let pp_specialize_ = ref false
let pp_elim_infinite = ref false
let pp_elim_multi_eqns = ref false
let pp_polarize_ = ref false
let pp_unroll_ = ref false
let pp_elim_preds_ = ref false
let pp_cstor_as_fun_ = ref false
let pp_elim_data_ = ref false
let pp_elim_codata_ = ref false
let pp_copy_ = ref false
let pp_intro_guards_ = ref false
let pp_elim_ite_ = ref false
let pp_elim_prop_args_ = ref false
let pp_elim_types_ = ref false
let pp_fo_ = ref false
let pp_fo_to_rel_ = ref false
let pp_smt_ = ref false
let pp_raw_model_ = ref false
let pp_model_ = ref false
let enable_polarize_ = ref true
let enable_specialize_ = ref true
let skolems_in_model_ = ref true
let cvc4_schedule_ = ref true
let kodkod_min_bound_ = ref Backends.Kodkod.default_min_size
let kodkod_max_bound_ = ref None
let kodkod_bound_increment_ = ref Backends.Kodkod.default_size_increment
let timeout_ = ref 30
let version_ = ref false
let dump_ : [`No | `Yes | `Into of string] ref = ref `No
let file = ref ""
let solvers = ref [S_CVC4; S_kodkod; S_paradox; S_smbc]
let j = ref 3
let prelude_ = ref []
let set_file f =
if !file <> ""
then raise (Arg.Bad "please provide only one file")
else file := f
let add_prelude p = prelude_ := p :: !prelude_
let input_opt = Utils.arg_choice inputs_ ((:=) input_)
let output_opt = Utils.arg_choice outputs_ ((:=) output_)
(* solver string specification *)
let parse_solvers_ s =
let s = String.trim s |> CCString.lowercase_ascii in
let l = CCString.Split.list_cpy ~by:"," s in
List.map
(function
| "cvc4" -> S_CVC4
| "paradox" -> S_paradox
| "kodkod" -> S_kodkod
| "smbc" -> S_smbc
| s ->
failwith (Utils.err_sprintf "unknown solver `%s` %s" s (list_solvers_())))
l
let set_solvers_ s =
let l = parse_solvers_ s |> CCList.uniq ~eq:(=) in
solvers := l
let set_dump () = dump_ := `Yes
let set_dump_into s = dump_ := `Into s
let call_with x f = Arg.Unit (fun () -> f x)
let options =
let open CCFun in
Arg.align @@ List.sort Stdlib.compare @@ (
Utils.Options.get_all () @
[ "--pp-input", Arg.Set pp_, " print input"
; "--pp-all", Arg.Set pp_all_, " print every step of the pipeline"
; "--pp-pipeline", Arg.Set pp_pipeline_, " print full pipeline and exit"
; "--pp-typed", Arg.Set pp_typed_, " print input after typing"
; "--pp-" ^ Tr.Skolem.name, Arg.Set pp_skolem_, " print input after Skolemization"
; "--pp-" ^ Tr.Monomorphization.name, Arg.Set pp_mono_, " print input after monomorphization"
; "--pp-" ^ Tr.ElimPatternMatch.name
, Arg.Set pp_elim_match_
, " print input after elimination of pattern matching"
; "--pp-" ^ Tr.ElimIndPreds.name
, Arg.Set pp_elim_preds_
, " print input after elimination of (co)inductive predicates"
; "--pp-" ^ Tr.ElimRecursion.name
, Arg.Set pp_elim_recursion_
, " print input after elimination of recursive functions"
; "--pp-" ^ Tr.Specialize.name
, Arg.Set pp_specialize_
, " print input after specialization"
; "--pp-" ^ Tr.LambdaLift.name, Arg.Set pp_lambda_lift_, " print after λ-lifting"
; "--pp-" ^ Tr.Cstor_as_fun.long_name
, Arg.Set pp_cstor_as_fun_
, " print input after removal of partial applications of constructors"
; "--pp-" ^ Tr.Elim_HOF.name
, Arg.Set pp_elim_hof_
, " print input after elimination of higher-order/partial functions"
; "--pp-" ^ Tr.ElimMultipleEqns.name
, Arg.Set pp_elim_multi_eqns
, " print input after elimination of multiple equations"
; "--pp-" ^ Tr.Elim_infinite.name
, Arg.Set pp_elim_infinite
, " print input after elimination of infinite types"
; "--pp-" ^ Tr.Polarize.name , Arg.Set pp_polarize_, " print input after polarization"
; "--pp-" ^ Tr.Unroll.name, Arg.Set pp_unroll_, " print input after unrolling"
; "--pp-" ^ Tr.ElimCopy.name, Arg.Set pp_copy_, " print input after elimination of copy types"
; "--pp-" ^ Tr.ElimData.Data.name
, Arg.Set pp_elim_data_
, " print input after elimination of (co)datatypes"
; "--pp-" ^ Tr.ElimData.Codata.name
, Arg.Set pp_elim_codata_
, " print input after elimination of (co)datatypes"
; "--pp-" ^ Tr.IntroGuards.name, Arg.Set pp_intro_guards_,
" print input after introduction of guards"
; "--pp-" ^ Tr.Elim_ite.name, Arg.Set pp_elim_ite_,
" print input after elimination of if/then/else"
; "--pp-" ^ Tr.Elim_prop_args.name, Arg.Set pp_elim_prop_args_,
" print input after elimination of propositional function subterms"
; "--pp-" ^ Tr.ElimTypes.name, Arg.Set pp_elim_types_,
" print input after elimination of types"
; "--pp-fo", Arg.Set pp_fo_, " print first-order problem"
; "--pp-" ^ Tr.FoToRelational.name, Arg.Set pp_fo_to_rel_,
" print first-order relational problem"
; "--pp-smt", Arg.Set pp_smt_, " print SMT problem"
; "--pp-raw-model", Arg.Set pp_raw_model_, " print raw model"
; "--pp-model", Arg.Set pp_model_, " print model after cleanup"
; "--checks", Arg.Set check_all_, " check invariants after each pass"
; "--no-checks", Arg.Clear check_all_, " disable checking invariants after each pass"
; "--color", call_with true CCFormat.set_color_default, " enable color"
; "--no-color", call_with false CCFormat.set_color_default, " disable color"
; "-nc", call_with false CCFormat.set_color_default, " disable color (alias to --no-color)"
; "-j", Arg.Set_int j, " set parallelism level"
; "--dump", Arg.Unit set_dump, " instead of running solvers, dump their problem into files"
; "--dump-into",
Arg.String set_dump_into,
" instead of running solvers, dump their problem into files in <directory>"
; "--polarize-rec", Arg.Set polarize_rec_, " enable polarization of rec predicates"
; "--no-polarize-rec", Arg.Clear polarize_rec_, " disable polarization of rec predicates"
; "--no-polarize", Arg.Clear enable_polarize_, " disable polarization"
; "--no-specialize", Arg.Clear enable_specialize_, " disable specialization"
; "--skolems-in-model", Arg.Set skolems_in_model_, " enable skolem constants in models"
; "--no-skolems-in-model", Arg.Clear skolems_in_model_, " disable skolem constants in models"
; "--cvc4-schedule", Arg.Set cvc4_schedule_, " enable scheduling of multiple CVC4 instances"
; "--no-cvc4-schedule", Arg.Clear cvc4_schedule_,
" disable scheduling of multiple CVC4 instances"
; "--kodkod-min-bound", Arg.Set_int kodkod_min_bound_,
" set lower cardinality bound for Kodkod"
; "--kodkod-max-bound", Arg.Int (fun n -> kodkod_max_bound_ := Some n),
" set upper cardinality bound for Kodkod"
; "--kodkod-bound-increment", Arg.Set_int kodkod_bound_increment_,
" set cardinality bound increment for Kodkod"
; "--solvers", Arg.String set_solvers_,
" solvers to use (comma-separated list) " ^ list_solvers_ ()
; "-s", Arg.String set_solvers_, " synonym for --solvers"
; "--timeout", Arg.Set_int timeout_, " set timeout (in s)"
; "-t", Arg.Set_int timeout_, " alias to --timeout"
; "--input", input_opt , " set input format"
; "-i", input_opt, " synonym for --input"
; "--output", output_opt, " set output format"
; "-o", output_opt, " synonym for --output"
; "--prelude", Arg.String add_prelude, " parse given prelude file"
; "--backtrace", Arg.Unit (fun () -> Printexc.record_backtrace true), " enable stack traces"
; "--version", Arg.Set version_, " print version and exit"
; "-d", Arg.Int Utils.set_debug, " alias to --debug"
; "-bt", Arg.Unit (fun () -> Printexc.record_backtrace true), " alias to --backtrace"
; "--cvc4-1.5", Arg.Unit Backends.CVC4.use_cvc4_1_5, " use CVC4 1.5 format"
]
)
let pp_version_if_needed () =
if !version_ then (
Format.printf "nunchaku %s %s@." Const.version GitVersion.id;
exit 0
);
()
let parse_file ~into ~input () =
let open E.Infix in
let src = if !file = "" then `Stdin else `File !file in
let rec by_input = function
| I_guess ->
begin match src with
| `Stdin -> by_input I_nunchaku
| `File f when CCString.suffix ~suf:".nun" f -> by_input I_nunchaku
| `File f when CCString.suffix ~suf:".p" f -> by_input I_tptp
| `File f when CCString.suffix ~suf:".smt2" f -> by_input I_tip
| `File f -> raise (Arg.Bad ("cannot guess format of " ^ f))
end
| I_nunchaku ->
Nunchaku_parsers.Lexer.parse ~into src
>|= CCVector.freeze
| I_tptp ->
Nunchaku_parsers.TPTP_lexer.parse ~into ~mode:(`Env "TPTP") src
>|= CCVector.to_iter
>>= Nunchaku_parsers.TPTP_preprocess.preprocess
| I_tip ->
Nunchaku_parsers.Parse_tip.parse ~into src
>|= CCVector.freeze
in
let res =
try by_input input
with e -> Utils.err_of_exn e
in
E.map_err
(fun msg -> CCFormat.sprintf "@[<2>could not parse `%s`:@ %s@]" !file msg)
res
(* parse list of prelude files *)
let parse_prelude files =
let open E.Infix in
let res = CCVector.of_list Prelude.decls in
E.fold_l
(fun () file ->
Nunchaku_parsers.Lexer.parse (`File file) >|= fun vec ->
CCVector.append res vec)
()
files
>|= fun () -> res
let pp_input_if_needed statements =
if !pp_ then
Format.printf "@[<v2>input: {@,@[<v>%a@]@]@,}@."
(Utils.pp_iter ~sep:"" A.pp_statement)
(CCVector.to_iter statements);
()
module Pipes = struct
module HO = Term
module Typed = TermTyped.Default
(* type inference *)
module Step_tyinfer = Tr.TypeInference.Make(Typed)
module Step_conv_ty = Problem.Convert(Typed)(HO)
(* conversion to FO *)
module Step_tofo = Tr.Trans_ho_fo.Make(HO)
end
let close_task p =
Transform.Pipe.close p
~f:(fun task ret ->
Scheduling.Task.map ~f:ret task, CCFun.id)
get a file name prefix for " " , or [ None ] if " " was not specified
let get_dump_file () = match !dump_ with
| `No -> None
| `Into dir ->
let filename = match !file with
| "" -> "nunchaku_problem"
| f -> Filename.chop_extension (Filename.basename f) ^ ".nunchaku"
in
Some (Filename.concat dir filename)
| `Yes ->
begin match !file with
| "" -> Some "nunchaku_problem"
| f ->
Some (Filename.chop_extension (Filename.basename f) ^ ".nunchaku")
end
let make_cvc4 ~j () =
let open Transform.Pipe in
if List.mem S_CVC4 !solvers && Backends.CVC4.is_available ()
then
Backends.CVC4.pipes
~options:Backends.CVC4.options_l
~slice:(1. *. float j)
~dump:(get_dump_file ())
~print:!pp_all_
~schedule_options:!cvc4_schedule_
~print_smt:(!pp_all_ || !pp_smt_)
~print_model:(!pp_all_ || !pp_raw_model_)
()
@@@ id
else fail
let make_paradox () =
let open Transform.Pipe in
if List.mem S_paradox !solvers && Backends.Paradox.is_available ()
then
Backends.Paradox.pipe
~print_model:(!pp_all_ || !pp_raw_model_)
~dump:(get_dump_file ())
~print:!pp_all_ ()
@@@ id
else fail
let make_kodkod () =
let open Transform.Pipe in
if List.mem S_kodkod !solvers && Backends.Kodkod.is_available ()
then
Backends.Kodkod.pipe
~min_size:!kodkod_min_bound_
?max_size:!kodkod_max_bound_
~size_increment:!kodkod_bound_increment_
~print:!pp_all_
~dump:(get_dump_file ())
~print_model:(!pp_all_ || !pp_raw_model_)
()
@@@ id
else fail
let make_smbc () =
let open Transform.Pipe in
if List.mem S_smbc !solvers && Backends.Smbc.is_available ()
then
Backends.Smbc.pipe
~print:!pp_all_
~dump:(get_dump_file ())
~print_model:(!pp_all_ || !pp_raw_model_)
()
@@@ id
else fail
(* build a pipeline, depending on options *)
let make_model_pipeline () =
let open Transform.Pipe in
let open Pipes in
(* setup pipeline *)
let check = !check_all_ in
(* solvers *)
let cvc4 = make_cvc4 ~j:!j () in
let paradox = make_paradox () in
let kodkod = make_kodkod () in
let smbc = make_smbc () in
let pipe_common k =
Step_tyinfer.pipe ~print:(!pp_typed_ || !pp_all_) @@@
Step_conv_ty.pipe () @@@
Tr.Skolem.pipe
~skolems_in_model:!skolems_in_model_
~print:(!pp_skolem_ || !pp_all_) ~check ~mode:`Sk_types @@@
k
and pipe_mono_common k =
Tr.Monomorphization.pipe
~always_mangle:false ~print:(!pp_mono_ || !pp_all_) ~check @@@
Tr.Elim_infinite.pipe ~print:(!pp_elim_infinite || !pp_all_) ~check @@@
Tr.ElimCopy.pipe ~print:(!pp_copy_ || !pp_all_) ~check @@@
Tr.ElimMultipleEqns.pipe
~decode:(fun x->x) ~check
~print:(!pp_elim_multi_eqns || !pp_all_) @@@
(if !enable_specialize_
then Tr.Specialize.pipe ~print:(!pp_specialize_ || !pp_all_) ~check
else Transform.nop ()) @@@
Tr.Cstor_as_fun.pipe ~print:(!pp_cstor_as_fun_ || !pp_all_) ~check @@@
k
and pipe_common_paradox_kodkod k =
Tr.ElimData.Codata.pipe ~print:(!pp_elim_codata_ || !pp_all_) ~check @@@
(if !enable_polarize_
then Tr.Polarize.pipe ~print:(!pp_polarize_ || !pp_all_)
~check ~polarize_rec:!polarize_rec_
else Transform.nop ()) @@@
Tr.Unroll.pipe ~print:(!pp_unroll_ || !pp_all_) ~check @@@
Tr.Skolem.pipe
~skolems_in_model:!skolems_in_model_
~print:(!pp_skolem_ || !pp_all_) ~mode:`Sk_all ~check @@@
Tr.ElimIndPreds.pipe ~print:(!pp_elim_preds_ || !pp_all_)
~check ~mode:`Use_selectors @@@
Tr.ElimData.Data.pipe ~print:(!pp_elim_data_ || !pp_all_) ~check @@@
Tr.LambdaLift.pipe ~print:(!pp_lambda_lift_ || !pp_all_) ~check @@@
Tr.Elim_HOF.pipe ~print:(!pp_elim_hof_ || !pp_all_) ~check @@@
Tr.ElimRecursion.pipe ~print:(!pp_elim_recursion_ || !pp_all_) ~check @@@
Tr.IntroGuards.pipe ~print:(!pp_intro_guards_ || !pp_all_) ~check @@@
Tr.Elim_prop_args.pipe ~print:(!pp_elim_prop_args_ || !pp_all_) ~check @@@
k
and pipe_paradox =
Tr.ElimTypes.pipe ~print:(!pp_elim_types_ || !pp_all_) ~check @@@
Tr.Model_clean.pipe ~print:(!pp_model_ || !pp_all_) @@@
close_task (
Step_tofo.pipe ~print:!pp_all_ () @@@
Tr.Elim_ite.pipe ~print:(!pp_elim_ite_ || !pp_all_) @@@
Tr.Trans_fo_tptp.pipe @@@
paradox
)
and pipe_kodkod =
Tr.Model_clean.pipe ~print:(!pp_model_ || !pp_all_) @@@
close_task (
Step_tofo.pipe ~print:!pp_all_ () @@@
Tr.FoToRelational.pipe ~print:(!pp_fo_to_rel_ || !pp_all_) @@@
kodkod
)
and pipe_smbc =
Tr.Monomorphization.pipe
~always_mangle:true ~print:(!pp_mono_ || !pp_all_) ~check @@@
Tr.Elim_infinite.pipe ~print:(!pp_elim_infinite || !pp_all_) ~check @@@
Tr.ElimCopy.pipe ~print:(!pp_copy_ || !pp_all_) ~check @@@
Tr.ElimMultipleEqns.pipe
~decode:(fun x->x) ~check
~print:(!pp_elim_multi_eqns || !pp_all_) @@@
(if !enable_specialize_
then Tr.Specialize.pipe ~print:(!pp_specialize_ || !pp_all_) ~check
else Transform.nop ()) @@@
(*
Tr.Skolem.pipe
~skolems_in_model:!skolems_in_model_
~print:(!pp_skolem_ || !pp_all_) ~mode:`Sk_all ~check @@@
*)
Tr.ElimPatternMatch.pipe ~mode:Tr.ElimPatternMatch.Elim_codata_match
~print:(!pp_elim_codata_ || !pp_all_) ~check @@@
Tr.Cstor_as_fun.pipe ~print:(!pp_cstor_as_fun_ || !pp_all_) ~check @@@
Tr.ElimData.Codata.pipe ~print:(!pp_elim_codata_ || !pp_all_) ~check @@@
(if !enable_polarize_
then Tr.Polarize.pipe ~print:(!pp_polarize_ || !pp_all_)
~check ~polarize_rec:!polarize_rec_
else Transform.nop ()) @@@
Tr.Unroll.pipe ~print:(!pp_unroll_ || !pp_all_) ~check @@@
skolemize first , to have proper decoding of model
Tr.Skolem.pipe
~skolems_in_model:!skolems_in_model_
~print:(!pp_skolem_ || !pp_all_) ~mode:`Sk_all ~check @@@
Tr.ElimIndPreds.pipe ~mode:`Use_match
~print:(!pp_elim_preds_ || !pp_all_) ~check @@@
~print:(!pp_lambda_lift _ || ! pp_all _ ) ~check @@@
Tr.Elim_HOF.pipe ~print:(!pp_elim_hof _ || ! pp_all _ ) ~check @@@
Tr.LambdaLift.pipe ~print:(!pp_lambda_lift_ || !pp_all_) ~check @@@
Tr.Elim_HOF.pipe ~print:(!pp_elim_hof_ || !pp_all_) ~check @@@
*)
Tr.Lift_undefined.pipe ~print:!pp_all_ ~check @@@
Tr.Model_clean.pipe ~print:(!pp_model_ || !pp_all_) @@@
close_task smbc
and pipe_cvc4 =
(if !enable_polarize_
then Tr.Polarize.pipe ~print:(!pp_polarize_ || !pp_all_)
~check ~polarize_rec:!polarize_rec_
else Transform.nop ()) @@@
Tr.Unroll.pipe ~print:(!pp_unroll_ || !pp_all_) ~check @@@
Tr.Skolem.pipe
~skolems_in_model:!skolems_in_model_
~print:(!pp_skolem_ || !pp_all_) ~mode:`Sk_all ~check @@@
Tr.ElimIndPreds.pipe
~mode:`Use_selectors
~print:(!pp_elim_preds_ || !pp_all_) ~check @@@
Tr.LambdaLift.pipe ~print:(!pp_lambda_lift_ || !pp_all_) ~check @@@
Tr.Elim_HOF.pipe ~print:(!pp_elim_hof_ || !pp_all_) ~check @@@
Tr.ElimRecursion.pipe ~print:(!pp_elim_recursion_ || !pp_all_) ~check @@@
Tr.IntroGuards.pipe ~print:(!pp_intro_guards_ || !pp_all_) ~check @@@
Tr.Model_clean.pipe ~print:(!pp_model_ || !pp_all_) @@@
close_task (
Step_tofo.pipe ~print:!pp_all_ () @@@
Transform.Pipe.flatten cvc4
)
in
let pipe =
pipe_common
(fork
pipe_smbc
(pipe_mono_common @@
Tr.ElimPatternMatch.pipe ~mode:Tr.ElimPatternMatch.Elim_both
~print:(!pp_elim_match_ || !pp_all_) ~check @@@
fork
(pipe_common_paradox_kodkod (fork pipe_paradox pipe_kodkod))
pipe_cvc4))
in
pipe
let process_res_ r =
let module Res = Problem.Res in
(* [l] only contains unknown-like results (+timeout+out_of_scope),
id recover accurate info *)
let find_result_if_unknown l =
let l =
CCList.flat_map (function Res.Unknown l -> l | _ -> assert false) l
in
Res.Unknown l
in
match r with
| Scheduling.Res_fail e -> E.fail (Printexc.to_string e)
| Scheduling.Res_list [] -> E.fail "no task succeeded"
| Scheduling.Res_list l ->
assert
(List.for_all
(function
| Res.Unknown _ -> true
| Res.Error _ | Res.Sat _ | Res.Unsat _ -> false)
l);
let res = find_result_if_unknown l in
E.return res
| Scheduling.Res_one r -> E.return r
(* run the pipeline on this problem, then run tasks, and return the
result *)
let run_tasks ~j ~deadline pipe pb =
let module Res = Problem.Res in
let tasks =
Transform.run ~pipe pb
|> Lazy_list.map ~f:(fun (task,ret) -> Scheduling.Task.map ~f:ret task)
|> Lazy_list.to_list
in
match tasks with
| [] -> E.return (Res.Unknown [])
| _::_ ->
let res = Scheduling.run ~j ~deadline tasks in
process_res_ res
(* negate the goal *)
let negate_goal stmts =
let module A = UntypedAST in
CCVector.map
(fun st ->
match st.A.stmt_value with
| A.Goal f ->
let loc = Location.get_loc f in
{st with A.stmt_value=A.Goal (A.not_ ~loc f); }
| _ -> st)
stmts
(* additional printers *)
let () = Printexc.register_printer
(function
| Failure msg -> Some ("failure: " ^ msg)
| _ -> None)
(* model mode *)
let main_model ~output statements =
let open E.Infix in
let module T = Term in
let module P = TI.Print(T) in
let module Res = Problem.Res in
(* run pipeline *)
let pipe = make_model_pipeline() in
Transform.Pipe.check pipe;
(* check that there is something in the pipeline *)
begin match pipe with
| Transform.Pipe.Fail -> failwith "solvers are unavailable"
| _ -> ()
end;
assert (not !pp_pipeline_);
let deadline = Utils.Time.start () +. (float_of_int !timeout_) in
run_tasks ~j:!j ~deadline pipe statements
>|= fun res ->
match res, output with
| _, O_sexp ->
let s = Problem.Res.to_sexp P.to_sexp P.to_sexp res in
Format.printf "@[<hv2>%a@]@." Sexp_lib.pp s
| Res.Sat (m,i), O_nunchaku when m.Model.potentially_spurious ->
Format.printf "@[<v>@[<v2>SAT: (potentially spurious) {@,@[<v>%a@]@]@,}@,%a@]@."
(Model.pp P.pp' P.pp) m Res.pp_info i;
| Res.Sat (m,i), O_nunchaku ->
Format.printf "@[<v>@[<v2>SAT: {@,@[<v>%a@]@]@,}@,%a@]@."
Model.Default.pp_standard m Res.pp_info i;
| Res.Sat (m,i), O_tptp ->
(* XXX: if potentially spurious, what should we print? *)
let module PM = Nunchaku_parsers.TPTP_print in
Format.printf "@[<v2>%a@]@,%% %a@." PM.pp_model m Res.pp_info i
| Res.Unsat i, O_nunchaku ->
Format.printf "@[UNSAT@]@.%a@." Res.pp_info i
| Res.Unsat i, O_tptp ->
Format.printf "@[SZS Status: Unsatisfiable@]@.%% %a@." Res.pp_info i
| Res.Unknown l, _ ->
Format.printf "@[UNKNOWN@]@.(@[<hv>%a@])@." (Utils.pp_list Res.pp_unknown_info) l
| Res.Error (e,_), _ ->
raise e
(* main *)
let main () =
let open E.Infix in
CCFormat.set_color_default true; (* default: enable colors *)
Arg.parse options set_file "usage: nunchaku [options] file";
pp_version_if_needed ();
if !pp_pipeline_ then (
let pipe = make_model_pipeline() in
Format.printf "@[Pipeline: %a@]@." Transform.Pipe.pp pipe;
Transform.Pipe.check pipe;
exit 0
);
(* parse *)
parse_prelude (List.rev !prelude_)
>>= fun statements ->
parse_file ~into:statements ~input:!input_ ()
>>= fun statements ->
pp_input_if_needed statements;
main_model ~output:!output_ statements
let () =
E.catch (try main () with e -> Utils.err_of_exn e)
~ok:(fun () -> exit 0)
~err:(fun msg ->
Format.eprintf "%s@." msg;
exit 1
)
| null | https://raw.githubusercontent.com/nunchaku-inria/nunchaku/16f33db3f5e92beecfb679a13329063b194f753d/src/main/nunchaku.ml | ocaml | TODO: tip output?
NOTE: also modify list_solvers_ below if you modify this
solver string specification
parse list of prelude files
type inference
conversion to FO
build a pipeline, depending on options
setup pipeline
solvers
Tr.Skolem.pipe
~skolems_in_model:!skolems_in_model_
~print:(!pp_skolem_ || !pp_all_) ~mode:`Sk_all ~check @@@
[l] only contains unknown-like results (+timeout+out_of_scope),
id recover accurate info
run the pipeline on this problem, then run tasks, and return the
result
negate the goal
additional printers
model mode
run pipeline
check that there is something in the pipeline
XXX: if potentially spurious, what should we print?
main
default: enable colors
parse |
* { 1 Main program }
open Nunchaku_core
module E = CCResult
module A = UntypedAST
module TI = TermInner
module Backends = Nunchaku_backends
module Tr = Nunchaku_transformations
type input =
| I_guess
| I_nunchaku
| I_tptp
| I_tip
let inputs_ =
[ "nunchaku", I_nunchaku
; "tptp", I_tptp
; "tip", I_tip
]
type output =
| O_nunchaku
| O_tptp
| O_sexp
let outputs_ =
[ "nunchaku", O_nunchaku
; "tptp", O_tptp
; "sexp", O_sexp
]
type solver =
| S_CVC4
| S_kodkod
| S_paradox
| S_smbc
let list_solvers_ () = "(available choices: cvc4 kodkod paradox smbc)"
* { 2 Options }
let input_ = ref I_guess
let output_ = ref O_nunchaku
let check_all_ = ref true
let polarize_rec_ = ref false
let pp_ = ref false
let pp_all_ = ref false
let pp_pipeline_ = ref false
let pp_typed_ = ref false
let pp_skolem_ = ref false
let pp_mono_ = ref false
let pp_elim_match_ = ref false
let pp_elim_recursion_ = ref false
let pp_elim_hof_ = ref false
let pp_lambda_lift_ = ref false
let pp_specialize_ = ref false
let pp_elim_infinite = ref false
let pp_elim_multi_eqns = ref false
let pp_polarize_ = ref false
let pp_unroll_ = ref false
let pp_elim_preds_ = ref false
let pp_cstor_as_fun_ = ref false
let pp_elim_data_ = ref false
let pp_elim_codata_ = ref false
let pp_copy_ = ref false
let pp_intro_guards_ = ref false
let pp_elim_ite_ = ref false
let pp_elim_prop_args_ = ref false
let pp_elim_types_ = ref false
let pp_fo_ = ref false
let pp_fo_to_rel_ = ref false
let pp_smt_ = ref false
let pp_raw_model_ = ref false
let pp_model_ = ref false
let enable_polarize_ = ref true
let enable_specialize_ = ref true
let skolems_in_model_ = ref true
let cvc4_schedule_ = ref true
let kodkod_min_bound_ = ref Backends.Kodkod.default_min_size
let kodkod_max_bound_ = ref None
let kodkod_bound_increment_ = ref Backends.Kodkod.default_size_increment
let timeout_ = ref 30
let version_ = ref false
let dump_ : [`No | `Yes | `Into of string] ref = ref `No
let file = ref ""
let solvers = ref [S_CVC4; S_kodkod; S_paradox; S_smbc]
let j = ref 3
let prelude_ = ref []
let set_file f =
if !file <> ""
then raise (Arg.Bad "please provide only one file")
else file := f
let add_prelude p = prelude_ := p :: !prelude_
let input_opt = Utils.arg_choice inputs_ ((:=) input_)
let output_opt = Utils.arg_choice outputs_ ((:=) output_)
let parse_solvers_ s =
let s = String.trim s |> CCString.lowercase_ascii in
let l = CCString.Split.list_cpy ~by:"," s in
List.map
(function
| "cvc4" -> S_CVC4
| "paradox" -> S_paradox
| "kodkod" -> S_kodkod
| "smbc" -> S_smbc
| s ->
failwith (Utils.err_sprintf "unknown solver `%s` %s" s (list_solvers_())))
l
let set_solvers_ s =
let l = parse_solvers_ s |> CCList.uniq ~eq:(=) in
solvers := l
let set_dump () = dump_ := `Yes
let set_dump_into s = dump_ := `Into s
let call_with x f = Arg.Unit (fun () -> f x)
let options =
let open CCFun in
Arg.align @@ List.sort Stdlib.compare @@ (
Utils.Options.get_all () @
[ "--pp-input", Arg.Set pp_, " print input"
; "--pp-all", Arg.Set pp_all_, " print every step of the pipeline"
; "--pp-pipeline", Arg.Set pp_pipeline_, " print full pipeline and exit"
; "--pp-typed", Arg.Set pp_typed_, " print input after typing"
; "--pp-" ^ Tr.Skolem.name, Arg.Set pp_skolem_, " print input after Skolemization"
; "--pp-" ^ Tr.Monomorphization.name, Arg.Set pp_mono_, " print input after monomorphization"
; "--pp-" ^ Tr.ElimPatternMatch.name
, Arg.Set pp_elim_match_
, " print input after elimination of pattern matching"
; "--pp-" ^ Tr.ElimIndPreds.name
, Arg.Set pp_elim_preds_
, " print input after elimination of (co)inductive predicates"
; "--pp-" ^ Tr.ElimRecursion.name
, Arg.Set pp_elim_recursion_
, " print input after elimination of recursive functions"
; "--pp-" ^ Tr.Specialize.name
, Arg.Set pp_specialize_
, " print input after specialization"
; "--pp-" ^ Tr.LambdaLift.name, Arg.Set pp_lambda_lift_, " print after λ-lifting"
; "--pp-" ^ Tr.Cstor_as_fun.long_name
, Arg.Set pp_cstor_as_fun_
, " print input after removal of partial applications of constructors"
; "--pp-" ^ Tr.Elim_HOF.name
, Arg.Set pp_elim_hof_
, " print input after elimination of higher-order/partial functions"
; "--pp-" ^ Tr.ElimMultipleEqns.name
, Arg.Set pp_elim_multi_eqns
, " print input after elimination of multiple equations"
; "--pp-" ^ Tr.Elim_infinite.name
, Arg.Set pp_elim_infinite
, " print input after elimination of infinite types"
; "--pp-" ^ Tr.Polarize.name , Arg.Set pp_polarize_, " print input after polarization"
; "--pp-" ^ Tr.Unroll.name, Arg.Set pp_unroll_, " print input after unrolling"
; "--pp-" ^ Tr.ElimCopy.name, Arg.Set pp_copy_, " print input after elimination of copy types"
; "--pp-" ^ Tr.ElimData.Data.name
, Arg.Set pp_elim_data_
, " print input after elimination of (co)datatypes"
; "--pp-" ^ Tr.ElimData.Codata.name
, Arg.Set pp_elim_codata_
, " print input after elimination of (co)datatypes"
; "--pp-" ^ Tr.IntroGuards.name, Arg.Set pp_intro_guards_,
" print input after introduction of guards"
; "--pp-" ^ Tr.Elim_ite.name, Arg.Set pp_elim_ite_,
" print input after elimination of if/then/else"
; "--pp-" ^ Tr.Elim_prop_args.name, Arg.Set pp_elim_prop_args_,
" print input after elimination of propositional function subterms"
; "--pp-" ^ Tr.ElimTypes.name, Arg.Set pp_elim_types_,
" print input after elimination of types"
; "--pp-fo", Arg.Set pp_fo_, " print first-order problem"
; "--pp-" ^ Tr.FoToRelational.name, Arg.Set pp_fo_to_rel_,
" print first-order relational problem"
; "--pp-smt", Arg.Set pp_smt_, " print SMT problem"
; "--pp-raw-model", Arg.Set pp_raw_model_, " print raw model"
; "--pp-model", Arg.Set pp_model_, " print model after cleanup"
; "--checks", Arg.Set check_all_, " check invariants after each pass"
; "--no-checks", Arg.Clear check_all_, " disable checking invariants after each pass"
; "--color", call_with true CCFormat.set_color_default, " enable color"
; "--no-color", call_with false CCFormat.set_color_default, " disable color"
; "-nc", call_with false CCFormat.set_color_default, " disable color (alias to --no-color)"
; "-j", Arg.Set_int j, " set parallelism level"
; "--dump", Arg.Unit set_dump, " instead of running solvers, dump their problem into files"
; "--dump-into",
Arg.String set_dump_into,
" instead of running solvers, dump their problem into files in <directory>"
; "--polarize-rec", Arg.Set polarize_rec_, " enable polarization of rec predicates"
; "--no-polarize-rec", Arg.Clear polarize_rec_, " disable polarization of rec predicates"
; "--no-polarize", Arg.Clear enable_polarize_, " disable polarization"
; "--no-specialize", Arg.Clear enable_specialize_, " disable specialization"
; "--skolems-in-model", Arg.Set skolems_in_model_, " enable skolem constants in models"
; "--no-skolems-in-model", Arg.Clear skolems_in_model_, " disable skolem constants in models"
; "--cvc4-schedule", Arg.Set cvc4_schedule_, " enable scheduling of multiple CVC4 instances"
; "--no-cvc4-schedule", Arg.Clear cvc4_schedule_,
" disable scheduling of multiple CVC4 instances"
; "--kodkod-min-bound", Arg.Set_int kodkod_min_bound_,
" set lower cardinality bound for Kodkod"
; "--kodkod-max-bound", Arg.Int (fun n -> kodkod_max_bound_ := Some n),
" set upper cardinality bound for Kodkod"
; "--kodkod-bound-increment", Arg.Set_int kodkod_bound_increment_,
" set cardinality bound increment for Kodkod"
; "--solvers", Arg.String set_solvers_,
" solvers to use (comma-separated list) " ^ list_solvers_ ()
; "-s", Arg.String set_solvers_, " synonym for --solvers"
; "--timeout", Arg.Set_int timeout_, " set timeout (in s)"
; "-t", Arg.Set_int timeout_, " alias to --timeout"
; "--input", input_opt , " set input format"
; "-i", input_opt, " synonym for --input"
; "--output", output_opt, " set output format"
; "-o", output_opt, " synonym for --output"
; "--prelude", Arg.String add_prelude, " parse given prelude file"
; "--backtrace", Arg.Unit (fun () -> Printexc.record_backtrace true), " enable stack traces"
; "--version", Arg.Set version_, " print version and exit"
; "-d", Arg.Int Utils.set_debug, " alias to --debug"
; "-bt", Arg.Unit (fun () -> Printexc.record_backtrace true), " alias to --backtrace"
; "--cvc4-1.5", Arg.Unit Backends.CVC4.use_cvc4_1_5, " use CVC4 1.5 format"
]
)
let pp_version_if_needed () =
if !version_ then (
Format.printf "nunchaku %s %s@." Const.version GitVersion.id;
exit 0
);
()
let parse_file ~into ~input () =
let open E.Infix in
let src = if !file = "" then `Stdin else `File !file in
let rec by_input = function
| I_guess ->
begin match src with
| `Stdin -> by_input I_nunchaku
| `File f when CCString.suffix ~suf:".nun" f -> by_input I_nunchaku
| `File f when CCString.suffix ~suf:".p" f -> by_input I_tptp
| `File f when CCString.suffix ~suf:".smt2" f -> by_input I_tip
| `File f -> raise (Arg.Bad ("cannot guess format of " ^ f))
end
| I_nunchaku ->
Nunchaku_parsers.Lexer.parse ~into src
>|= CCVector.freeze
| I_tptp ->
Nunchaku_parsers.TPTP_lexer.parse ~into ~mode:(`Env "TPTP") src
>|= CCVector.to_iter
>>= Nunchaku_parsers.TPTP_preprocess.preprocess
| I_tip ->
Nunchaku_parsers.Parse_tip.parse ~into src
>|= CCVector.freeze
in
let res =
try by_input input
with e -> Utils.err_of_exn e
in
E.map_err
(fun msg -> CCFormat.sprintf "@[<2>could not parse `%s`:@ %s@]" !file msg)
res
let parse_prelude files =
let open E.Infix in
let res = CCVector.of_list Prelude.decls in
E.fold_l
(fun () file ->
Nunchaku_parsers.Lexer.parse (`File file) >|= fun vec ->
CCVector.append res vec)
()
files
>|= fun () -> res
let pp_input_if_needed statements =
if !pp_ then
Format.printf "@[<v2>input: {@,@[<v>%a@]@]@,}@."
(Utils.pp_iter ~sep:"" A.pp_statement)
(CCVector.to_iter statements);
()
module Pipes = struct
module HO = Term
module Typed = TermTyped.Default
module Step_tyinfer = Tr.TypeInference.Make(Typed)
module Step_conv_ty = Problem.Convert(Typed)(HO)
module Step_tofo = Tr.Trans_ho_fo.Make(HO)
end
let close_task p =
Transform.Pipe.close p
~f:(fun task ret ->
Scheduling.Task.map ~f:ret task, CCFun.id)
get a file name prefix for " " , or [ None ] if " " was not specified
let get_dump_file () = match !dump_ with
| `No -> None
| `Into dir ->
let filename = match !file with
| "" -> "nunchaku_problem"
| f -> Filename.chop_extension (Filename.basename f) ^ ".nunchaku"
in
Some (Filename.concat dir filename)
| `Yes ->
begin match !file with
| "" -> Some "nunchaku_problem"
| f ->
Some (Filename.chop_extension (Filename.basename f) ^ ".nunchaku")
end
let make_cvc4 ~j () =
let open Transform.Pipe in
if List.mem S_CVC4 !solvers && Backends.CVC4.is_available ()
then
Backends.CVC4.pipes
~options:Backends.CVC4.options_l
~slice:(1. *. float j)
~dump:(get_dump_file ())
~print:!pp_all_
~schedule_options:!cvc4_schedule_
~print_smt:(!pp_all_ || !pp_smt_)
~print_model:(!pp_all_ || !pp_raw_model_)
()
@@@ id
else fail
let make_paradox () =
let open Transform.Pipe in
if List.mem S_paradox !solvers && Backends.Paradox.is_available ()
then
Backends.Paradox.pipe
~print_model:(!pp_all_ || !pp_raw_model_)
~dump:(get_dump_file ())
~print:!pp_all_ ()
@@@ id
else fail
let make_kodkod () =
let open Transform.Pipe in
if List.mem S_kodkod !solvers && Backends.Kodkod.is_available ()
then
Backends.Kodkod.pipe
~min_size:!kodkod_min_bound_
?max_size:!kodkod_max_bound_
~size_increment:!kodkod_bound_increment_
~print:!pp_all_
~dump:(get_dump_file ())
~print_model:(!pp_all_ || !pp_raw_model_)
()
@@@ id
else fail
let make_smbc () =
let open Transform.Pipe in
if List.mem S_smbc !solvers && Backends.Smbc.is_available ()
then
Backends.Smbc.pipe
~print:!pp_all_
~dump:(get_dump_file ())
~print_model:(!pp_all_ || !pp_raw_model_)
()
@@@ id
else fail
let make_model_pipeline () =
let open Transform.Pipe in
let open Pipes in
let check = !check_all_ in
let cvc4 = make_cvc4 ~j:!j () in
let paradox = make_paradox () in
let kodkod = make_kodkod () in
let smbc = make_smbc () in
let pipe_common k =
Step_tyinfer.pipe ~print:(!pp_typed_ || !pp_all_) @@@
Step_conv_ty.pipe () @@@
Tr.Skolem.pipe
~skolems_in_model:!skolems_in_model_
~print:(!pp_skolem_ || !pp_all_) ~check ~mode:`Sk_types @@@
k
and pipe_mono_common k =
Tr.Monomorphization.pipe
~always_mangle:false ~print:(!pp_mono_ || !pp_all_) ~check @@@
Tr.Elim_infinite.pipe ~print:(!pp_elim_infinite || !pp_all_) ~check @@@
Tr.ElimCopy.pipe ~print:(!pp_copy_ || !pp_all_) ~check @@@
Tr.ElimMultipleEqns.pipe
~decode:(fun x->x) ~check
~print:(!pp_elim_multi_eqns || !pp_all_) @@@
(if !enable_specialize_
then Tr.Specialize.pipe ~print:(!pp_specialize_ || !pp_all_) ~check
else Transform.nop ()) @@@
Tr.Cstor_as_fun.pipe ~print:(!pp_cstor_as_fun_ || !pp_all_) ~check @@@
k
and pipe_common_paradox_kodkod k =
Tr.ElimData.Codata.pipe ~print:(!pp_elim_codata_ || !pp_all_) ~check @@@
(if !enable_polarize_
then Tr.Polarize.pipe ~print:(!pp_polarize_ || !pp_all_)
~check ~polarize_rec:!polarize_rec_
else Transform.nop ()) @@@
Tr.Unroll.pipe ~print:(!pp_unroll_ || !pp_all_) ~check @@@
Tr.Skolem.pipe
~skolems_in_model:!skolems_in_model_
~print:(!pp_skolem_ || !pp_all_) ~mode:`Sk_all ~check @@@
Tr.ElimIndPreds.pipe ~print:(!pp_elim_preds_ || !pp_all_)
~check ~mode:`Use_selectors @@@
Tr.ElimData.Data.pipe ~print:(!pp_elim_data_ || !pp_all_) ~check @@@
Tr.LambdaLift.pipe ~print:(!pp_lambda_lift_ || !pp_all_) ~check @@@
Tr.Elim_HOF.pipe ~print:(!pp_elim_hof_ || !pp_all_) ~check @@@
Tr.ElimRecursion.pipe ~print:(!pp_elim_recursion_ || !pp_all_) ~check @@@
Tr.IntroGuards.pipe ~print:(!pp_intro_guards_ || !pp_all_) ~check @@@
Tr.Elim_prop_args.pipe ~print:(!pp_elim_prop_args_ || !pp_all_) ~check @@@
k
and pipe_paradox =
Tr.ElimTypes.pipe ~print:(!pp_elim_types_ || !pp_all_) ~check @@@
Tr.Model_clean.pipe ~print:(!pp_model_ || !pp_all_) @@@
close_task (
Step_tofo.pipe ~print:!pp_all_ () @@@
Tr.Elim_ite.pipe ~print:(!pp_elim_ite_ || !pp_all_) @@@
Tr.Trans_fo_tptp.pipe @@@
paradox
)
and pipe_kodkod =
Tr.Model_clean.pipe ~print:(!pp_model_ || !pp_all_) @@@
close_task (
Step_tofo.pipe ~print:!pp_all_ () @@@
Tr.FoToRelational.pipe ~print:(!pp_fo_to_rel_ || !pp_all_) @@@
kodkod
)
and pipe_smbc =
Tr.Monomorphization.pipe
~always_mangle:true ~print:(!pp_mono_ || !pp_all_) ~check @@@
Tr.Elim_infinite.pipe ~print:(!pp_elim_infinite || !pp_all_) ~check @@@
Tr.ElimCopy.pipe ~print:(!pp_copy_ || !pp_all_) ~check @@@
Tr.ElimMultipleEqns.pipe
~decode:(fun x->x) ~check
~print:(!pp_elim_multi_eqns || !pp_all_) @@@
(if !enable_specialize_
then Tr.Specialize.pipe ~print:(!pp_specialize_ || !pp_all_) ~check
else Transform.nop ()) @@@
Tr.ElimPatternMatch.pipe ~mode:Tr.ElimPatternMatch.Elim_codata_match
~print:(!pp_elim_codata_ || !pp_all_) ~check @@@
Tr.Cstor_as_fun.pipe ~print:(!pp_cstor_as_fun_ || !pp_all_) ~check @@@
Tr.ElimData.Codata.pipe ~print:(!pp_elim_codata_ || !pp_all_) ~check @@@
(if !enable_polarize_
then Tr.Polarize.pipe ~print:(!pp_polarize_ || !pp_all_)
~check ~polarize_rec:!polarize_rec_
else Transform.nop ()) @@@
Tr.Unroll.pipe ~print:(!pp_unroll_ || !pp_all_) ~check @@@
skolemize first , to have proper decoding of model
Tr.Skolem.pipe
~skolems_in_model:!skolems_in_model_
~print:(!pp_skolem_ || !pp_all_) ~mode:`Sk_all ~check @@@
Tr.ElimIndPreds.pipe ~mode:`Use_match
~print:(!pp_elim_preds_ || !pp_all_) ~check @@@
~print:(!pp_lambda_lift _ || ! pp_all _ ) ~check @@@
Tr.Elim_HOF.pipe ~print:(!pp_elim_hof _ || ! pp_all _ ) ~check @@@
Tr.LambdaLift.pipe ~print:(!pp_lambda_lift_ || !pp_all_) ~check @@@
Tr.Elim_HOF.pipe ~print:(!pp_elim_hof_ || !pp_all_) ~check @@@
*)
Tr.Lift_undefined.pipe ~print:!pp_all_ ~check @@@
Tr.Model_clean.pipe ~print:(!pp_model_ || !pp_all_) @@@
close_task smbc
and pipe_cvc4 =
(if !enable_polarize_
then Tr.Polarize.pipe ~print:(!pp_polarize_ || !pp_all_)
~check ~polarize_rec:!polarize_rec_
else Transform.nop ()) @@@
Tr.Unroll.pipe ~print:(!pp_unroll_ || !pp_all_) ~check @@@
Tr.Skolem.pipe
~skolems_in_model:!skolems_in_model_
~print:(!pp_skolem_ || !pp_all_) ~mode:`Sk_all ~check @@@
Tr.ElimIndPreds.pipe
~mode:`Use_selectors
~print:(!pp_elim_preds_ || !pp_all_) ~check @@@
Tr.LambdaLift.pipe ~print:(!pp_lambda_lift_ || !pp_all_) ~check @@@
Tr.Elim_HOF.pipe ~print:(!pp_elim_hof_ || !pp_all_) ~check @@@
Tr.ElimRecursion.pipe ~print:(!pp_elim_recursion_ || !pp_all_) ~check @@@
Tr.IntroGuards.pipe ~print:(!pp_intro_guards_ || !pp_all_) ~check @@@
Tr.Model_clean.pipe ~print:(!pp_model_ || !pp_all_) @@@
close_task (
Step_tofo.pipe ~print:!pp_all_ () @@@
Transform.Pipe.flatten cvc4
)
in
let pipe =
pipe_common
(fork
pipe_smbc
(pipe_mono_common @@
Tr.ElimPatternMatch.pipe ~mode:Tr.ElimPatternMatch.Elim_both
~print:(!pp_elim_match_ || !pp_all_) ~check @@@
fork
(pipe_common_paradox_kodkod (fork pipe_paradox pipe_kodkod))
pipe_cvc4))
in
pipe
let process_res_ r =
let module Res = Problem.Res in
let find_result_if_unknown l =
let l =
CCList.flat_map (function Res.Unknown l -> l | _ -> assert false) l
in
Res.Unknown l
in
match r with
| Scheduling.Res_fail e -> E.fail (Printexc.to_string e)
| Scheduling.Res_list [] -> E.fail "no task succeeded"
| Scheduling.Res_list l ->
assert
(List.for_all
(function
| Res.Unknown _ -> true
| Res.Error _ | Res.Sat _ | Res.Unsat _ -> false)
l);
let res = find_result_if_unknown l in
E.return res
| Scheduling.Res_one r -> E.return r
let run_tasks ~j ~deadline pipe pb =
let module Res = Problem.Res in
let tasks =
Transform.run ~pipe pb
|> Lazy_list.map ~f:(fun (task,ret) -> Scheduling.Task.map ~f:ret task)
|> Lazy_list.to_list
in
match tasks with
| [] -> E.return (Res.Unknown [])
| _::_ ->
let res = Scheduling.run ~j ~deadline tasks in
process_res_ res
let negate_goal stmts =
let module A = UntypedAST in
CCVector.map
(fun st ->
match st.A.stmt_value with
| A.Goal f ->
let loc = Location.get_loc f in
{st with A.stmt_value=A.Goal (A.not_ ~loc f); }
| _ -> st)
stmts
let () = Printexc.register_printer
(function
| Failure msg -> Some ("failure: " ^ msg)
| _ -> None)
let main_model ~output statements =
let open E.Infix in
let module T = Term in
let module P = TI.Print(T) in
let module Res = Problem.Res in
let pipe = make_model_pipeline() in
Transform.Pipe.check pipe;
begin match pipe with
| Transform.Pipe.Fail -> failwith "solvers are unavailable"
| _ -> ()
end;
assert (not !pp_pipeline_);
let deadline = Utils.Time.start () +. (float_of_int !timeout_) in
run_tasks ~j:!j ~deadline pipe statements
>|= fun res ->
match res, output with
| _, O_sexp ->
let s = Problem.Res.to_sexp P.to_sexp P.to_sexp res in
Format.printf "@[<hv2>%a@]@." Sexp_lib.pp s
| Res.Sat (m,i), O_nunchaku when m.Model.potentially_spurious ->
Format.printf "@[<v>@[<v2>SAT: (potentially spurious) {@,@[<v>%a@]@]@,}@,%a@]@."
(Model.pp P.pp' P.pp) m Res.pp_info i;
| Res.Sat (m,i), O_nunchaku ->
Format.printf "@[<v>@[<v2>SAT: {@,@[<v>%a@]@]@,}@,%a@]@."
Model.Default.pp_standard m Res.pp_info i;
| Res.Sat (m,i), O_tptp ->
let module PM = Nunchaku_parsers.TPTP_print in
Format.printf "@[<v2>%a@]@,%% %a@." PM.pp_model m Res.pp_info i
| Res.Unsat i, O_nunchaku ->
Format.printf "@[UNSAT@]@.%a@." Res.pp_info i
| Res.Unsat i, O_tptp ->
Format.printf "@[SZS Status: Unsatisfiable@]@.%% %a@." Res.pp_info i
| Res.Unknown l, _ ->
Format.printf "@[UNKNOWN@]@.(@[<hv>%a@])@." (Utils.pp_list Res.pp_unknown_info) l
| Res.Error (e,_), _ ->
raise e
let main () =
let open E.Infix in
Arg.parse options set_file "usage: nunchaku [options] file";
pp_version_if_needed ();
if !pp_pipeline_ then (
let pipe = make_model_pipeline() in
Format.printf "@[Pipeline: %a@]@." Transform.Pipe.pp pipe;
Transform.Pipe.check pipe;
exit 0
);
parse_prelude (List.rev !prelude_)
>>= fun statements ->
parse_file ~into:statements ~input:!input_ ()
>>= fun statements ->
pp_input_if_needed statements;
main_model ~output:!output_ statements
let () =
E.catch (try main () with e -> Utils.err_of_exn e)
~ok:(fun () -> exit 0)
~err:(fun msg ->
Format.eprintf "%s@." msg;
exit 1
)
|
1892a09c79dd9dad491a1e268aca944f77f1cb2a4e3d9f8dd2ffc4bff817112f | dwayne/eopl3 | exb.5.test.rkt | #lang racket
(require "./exb.5.interpreter.rkt")
(require rackunit)
(check-eq? (interpret "-1") -1)
(check-eq? (interpret "-x") -5)
(check-eq? (interpret "-(x+y)") -15)
(check-eq? (interpret "-x--y+z") 20)
| null | https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/appendix-b/exb.5.test.rkt | racket | #lang racket
(require "./exb.5.interpreter.rkt")
(require rackunit)
(check-eq? (interpret "-1") -1)
(check-eq? (interpret "-x") -5)
(check-eq? (interpret "-(x+y)") -15)
(check-eq? (interpret "-x--y+z") 20)
|
|
68ea77d7b99c071fddc8b4ff2bdcc7f3cc5b6a4e0765eab614d6df9d8bc9e105 | mpickering/eventlog2html | Data.hs | {-# LANGUAGE OverloadedStrings #-}
module Eventlog.Data (generateJson, generateJsonValidate, generateJsonData ) where
import Prelude hiding (readFile)
import Data.Aeson (Value(..), (.=), object)
import qualified Data.Map as Map
import Eventlog.Args (Args(..))
import Eventlog.Bands (bands)
import qualified Eventlog.Events as E
import qualified Eventlog.HeapProf as H
import Eventlog.Prune
import Eventlog.Vega
import Eventlog.Types (Header(..), ProfData(..), HeapProfBreakdown(..))
import Data.List
import Data.Ord
import Eventlog.Trie
import Eventlog.Detailed
import Text.Blaze.Html
generateJsonData :: Args -> ProfData -> IO (Header, Value, Maybe Value, Maybe Html)
generateJsonData a (ProfData h binfo ccMap fs traces heap_info ipes) = do
let keeps = pruneBands a binfo
bs = bands h (Map.map fst keeps) fs
combinedJson = object [
"samples" .= bandsToVega keeps bs
, "traces" .= tracesToVega traces
, "heap" .= heapToVega heap_info
]
mdescs =
sortBy (flip (comparing (fst . snd))) $ Map.toList keeps
-- Only supply the cost centre view in cost centre profiling mode.
cc_descs = case hHeapProfileType h of
Just HeapProfBreakdownCostCentre -> Just (outputTree ccMap mdescs)
_ -> Nothing
let use_ipes = case hHeapProfileType h of
Just HeapProfBreakdownInfoTable -> Just ipes
_ -> Nothing
desc_buckets = pruneDetailed a binfo
bs' = bands h (Map.map fst desc_buckets) fs
closure_table =
case detailedLimit a of
Just 0 -> Nothing
_ -> Just (renderClosureInfo bs' use_ipes desc_buckets)
return (h, combinedJson, cc_descs, closure_table)
generateJson :: FilePath -> Args -> IO (Header, Value, Maybe Value, Maybe Html)
generateJson = generateJsonValidate (const (return ()))
generateJsonValidate :: (ProfData -> IO ()) -> FilePath
-> Args -> IO (Header, Value, Maybe Value, Maybe Html)
generateJsonValidate validate file a = do
let chunk = if heapProfile a then H.chunk else E.chunk a
dat <- chunk file
validate dat
generateJsonData a dat
| null | https://raw.githubusercontent.com/mpickering/eventlog2html/a18ec810328c71122ccc630fccfcea5b48c0e937/src/Eventlog/Data.hs | haskell | # LANGUAGE OverloadedStrings #
Only supply the cost centre view in cost centre profiling mode. | module Eventlog.Data (generateJson, generateJsonValidate, generateJsonData ) where
import Prelude hiding (readFile)
import Data.Aeson (Value(..), (.=), object)
import qualified Data.Map as Map
import Eventlog.Args (Args(..))
import Eventlog.Bands (bands)
import qualified Eventlog.Events as E
import qualified Eventlog.HeapProf as H
import Eventlog.Prune
import Eventlog.Vega
import Eventlog.Types (Header(..), ProfData(..), HeapProfBreakdown(..))
import Data.List
import Data.Ord
import Eventlog.Trie
import Eventlog.Detailed
import Text.Blaze.Html
generateJsonData :: Args -> ProfData -> IO (Header, Value, Maybe Value, Maybe Html)
generateJsonData a (ProfData h binfo ccMap fs traces heap_info ipes) = do
let keeps = pruneBands a binfo
bs = bands h (Map.map fst keeps) fs
combinedJson = object [
"samples" .= bandsToVega keeps bs
, "traces" .= tracesToVega traces
, "heap" .= heapToVega heap_info
]
mdescs =
sortBy (flip (comparing (fst . snd))) $ Map.toList keeps
cc_descs = case hHeapProfileType h of
Just HeapProfBreakdownCostCentre -> Just (outputTree ccMap mdescs)
_ -> Nothing
let use_ipes = case hHeapProfileType h of
Just HeapProfBreakdownInfoTable -> Just ipes
_ -> Nothing
desc_buckets = pruneDetailed a binfo
bs' = bands h (Map.map fst desc_buckets) fs
closure_table =
case detailedLimit a of
Just 0 -> Nothing
_ -> Just (renderClosureInfo bs' use_ipes desc_buckets)
return (h, combinedJson, cc_descs, closure_table)
generateJson :: FilePath -> Args -> IO (Header, Value, Maybe Value, Maybe Html)
generateJson = generateJsonValidate (const (return ()))
generateJsonValidate :: (ProfData -> IO ()) -> FilePath
-> Args -> IO (Header, Value, Maybe Value, Maybe Html)
generateJsonValidate validate file a = do
let chunk = if heapProfile a then H.chunk else E.chunk a
dat <- chunk file
validate dat
generateJsonData a dat
|
e8451c31578bd9d9464225fdaa7925d216cdda772935af2353690e7e5543cfda | artyom-poptsov/guile-dsv | dsv.scm | dsv.scm -- DSV parser .
Copyright ( C ) 2013 , 2014 < >
;;
;; 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.
;;
;; The 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 the program. If not, see </>.
;;; Commentary:
;;
Procedures for working with delimiter - separated values ( DSV ) format that is
widespread in the Unix world . Notable examples of DSV are ' /etc / passwd ' and
' /etc / inittab ' files .
;;
;; Most of the procedures take an optinal #:format argument that specifies the
format of DSV . Default value of the # : format is ' unix .
;;
;; Some examples:
;;
;; (dsv-string->scm "a:b:c")
;; => '(("a" "b" "c"))
;;
;; (dsv-string->scm "a;b;c" #\;)
;; => '(("a" "b" "c"))
;;
;; (dsv-string->scm "a,b\\,c" #\,)
;; => '(("a" "b,c"))
;;
;; (scm->dsv-string '(("a" "b" "c")))
;; => "a:b:c"
;;
( dsv->scm ( open - input - file " /etc / passwd " ) )
;; => (...
( " news " " x " " 9 " " 13 " " news " " /usr / lib / news " " /bin / false " )
;; ("root" "x" "0" "0" "root" "/root" "/bin/zsh"))
;;
;; (guess-delimiter "a:b,c,d")
;; => #\,
;;
;; These procedures are exported:
;;
;; dsv->scm [port [delimiter]] [#:format 'unix] [#:comment-prefix #\#]
;; dsv-string->scm string [delimiter] [#:format 'unix] [#:comment-prefix #\#]
;; scm->dsv [port [delimiter]] [#:format 'unix]
;; scm->dsv-string lst [delimiter] [#:format 'unix]
;; guess-delimiter str [known-delimiters] [#:format 'unix]
;; set-debug! [enabled?]
;;
;;; Code:
(define-module (dsv)
DSV
#:use-module ((dsv rfc4180) #:renamer (symbol-prefix-proc 'rfc4180:))
#:use-module ((dsv unix) #:renamer (symbol-prefix-proc 'unix:))
#:use-module (dsv common)
#:export (dsv-string->scm
scm->dsv-string
dsv->scm
scm->dsv
guess-delimiter)
#:re-export (set-debug!))
(define* (dsv->scm #:optional
(port (current-input-port))
(delimiter 'default)
#:key
(format 'unix)
(comment-prefix 'default))
"Read DSV data from a PORT. If the PORT is not set, read from the default
input port. If a DELIMITER is not set, use the default delimiter for a
FORMAT. Skip lines commented with a COMMENT-PREFIX. Return a list of
values, or throw 'dsv-parser-error' on an error."
(case format
((unix)
(let ((parser (unix:make-parser port delimiter 'default
comment-prefix)))
(unix:dsv->scm parser)))
((rfc4180)
(let ((parser (rfc4180:make-parser port delimiter 'default
comment-prefix)))
(rfc4180:dsv->scm parser)))
(else
(dsv-error "Unknown format" format))))
(define* (dsv-string->scm str
#:optional (delimiter 'default)
#:key
(format 'unix)
(comment-prefix 'default))
"Convert a DSV string STR to a list of values using a DELIMITER. If the
DELIMITER is not set, use the default delimiter for a FORMAT. Skip lines
commented with a COMMENT-PREFIX. Return a list of values, or throw
'dsv-parser-error' on an error."
(case format
((unix)
(let ((parser (unix:make-string-parser str delimiter 'default comment-prefix)))
(unix:dsv->scm parser)))
((rfc4180)
(let ((parser (rfc4180:make-string-parser str delimiter 'default comment-prefix)))
(rfc4180:dsv->scm parser)))
(else
(dsv-error "Unknown format" format))))
(define* (scm->dsv lst
#:optional
(port (current-output-port))
(delimiter 'default)
#:key
(format 'unix))
"Write a list of values LST as a sequence of DSV strings to a PORT using a
specified DSV FORMAT. If the PORT is not set, write to the default output
port. If a DELIMITER is not set, use the default delimiter for a FORMAT.
Throws 'dsv-parser-error' on an error. Return value is unspecified."
(let ((lst (if (or (null? lst) (list? (car lst)))
lst
(list lst))))
(case format
((unix)
(let ((builder (unix:make-builder lst port delimiter 'default)))
(unix:scm->dsv builder)))
((rfc4180)
(let ((builder (rfc4180:make-builder lst port delimiter 'default)))
(rfc4180:scm->dsv builder)))
(else
(dsv-error "Unknown format" format)))))
(define* (scm->dsv-string lst
#:optional (delimiter 'default)
#:key (format 'unix))
"Convert a list LST to a DSV string using a specified DSV FORMAT. If the
DELIMITER is not set, use the default delimiter for a FORMAT. Return a DSV
string; or throw a 'dsv-parser-error' on an error."
(let ((lst (if (or (null? lst) (list? (car lst)))
lst
(list lst))))
(case format
((unix)
(unix:scm->dsv-string lst delimiter 'default))
((rfc4180)
(rfc4180:scm->dsv-string lst delimiter 'default))
(else
(dsv-error "Unknown format" format)))))
(define* (guess-delimiter str #:optional (known-delimiters 'default)
#:key (format 'unix))
"Guess a DSV string STR delimiter. Optionally accept list of
KNOWN-DELIMITERS as an argument. The procedure returns guessed delimiter or
'#f' if it cannot determine a delimiter based on the given arguments, or
throws 'dsv-parser-error' on an error.
Note that when KNOWN-DELIMITERS list contains less than two elements, the
procedure returns '#f'."
(case format
((unix)
(let ((parser (unix:make-string-parser str 'default known-delimiters
'default)))
(unix:guess-delimiter parser)))
((rfc4180)
(let ((parser (rfc4180:make-string-parser str 'default known-delimiters
'default)))
(rfc4180:guess-delimiter parser)))
(else
(dsv-error "Unknown format." format))))
;;; dsv.scm ends here.
| null | https://raw.githubusercontent.com/artyom-poptsov/guile-dsv/ece5701906a900a42ab184b03c8c9e9110b7caa3/modules/dsv.scm | scheme |
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
The 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 the program. If not, see </>.
Commentary:
Most of the procedures take an optinal #:format argument that specifies the
Some examples:
(dsv-string->scm "a:b:c")
=> '(("a" "b" "c"))
(dsv-string->scm "a;b;c" #\;)
=> '(("a" "b" "c"))
(dsv-string->scm "a,b\\,c" #\,)
=> '(("a" "b,c"))
(scm->dsv-string '(("a" "b" "c")))
=> "a:b:c"
=> (...
("root" "x" "0" "0" "root" "/root" "/bin/zsh"))
(guess-delimiter "a:b,c,d")
=> #\,
These procedures are exported:
dsv->scm [port [delimiter]] [#:format 'unix] [#:comment-prefix #\#]
dsv-string->scm string [delimiter] [#:format 'unix] [#:comment-prefix #\#]
scm->dsv [port [delimiter]] [#:format 'unix]
scm->dsv-string lst [delimiter] [#:format 'unix]
guess-delimiter str [known-delimiters] [#:format 'unix]
set-debug! [enabled?]
Code:
or throw a 'dsv-parser-error' on an error."
dsv.scm ends here. | dsv.scm -- DSV parser .
Copyright ( C ) 2013 , 2014 < >
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
Procedures for working with delimiter - separated values ( DSV ) format that is
widespread in the Unix world . Notable examples of DSV are ' /etc / passwd ' and
' /etc / inittab ' files .
format of DSV . Default value of the # : format is ' unix .
( dsv->scm ( open - input - file " /etc / passwd " ) )
( " news " " x " " 9 " " 13 " " news " " /usr / lib / news " " /bin / false " )
(define-module (dsv)
DSV
#:use-module ((dsv rfc4180) #:renamer (symbol-prefix-proc 'rfc4180:))
#:use-module ((dsv unix) #:renamer (symbol-prefix-proc 'unix:))
#:use-module (dsv common)
#:export (dsv-string->scm
scm->dsv-string
dsv->scm
scm->dsv
guess-delimiter)
#:re-export (set-debug!))
(define* (dsv->scm #:optional
(port (current-input-port))
(delimiter 'default)
#:key
(format 'unix)
(comment-prefix 'default))
"Read DSV data from a PORT. If the PORT is not set, read from the default
input port. If a DELIMITER is not set, use the default delimiter for a
FORMAT. Skip lines commented with a COMMENT-PREFIX. Return a list of
values, or throw 'dsv-parser-error' on an error."
(case format
((unix)
(let ((parser (unix:make-parser port delimiter 'default
comment-prefix)))
(unix:dsv->scm parser)))
((rfc4180)
(let ((parser (rfc4180:make-parser port delimiter 'default
comment-prefix)))
(rfc4180:dsv->scm parser)))
(else
(dsv-error "Unknown format" format))))
(define* (dsv-string->scm str
#:optional (delimiter 'default)
#:key
(format 'unix)
(comment-prefix 'default))
"Convert a DSV string STR to a list of values using a DELIMITER. If the
DELIMITER is not set, use the default delimiter for a FORMAT. Skip lines
commented with a COMMENT-PREFIX. Return a list of values, or throw
'dsv-parser-error' on an error."
(case format
((unix)
(let ((parser (unix:make-string-parser str delimiter 'default comment-prefix)))
(unix:dsv->scm parser)))
((rfc4180)
(let ((parser (rfc4180:make-string-parser str delimiter 'default comment-prefix)))
(rfc4180:dsv->scm parser)))
(else
(dsv-error "Unknown format" format))))
(define* (scm->dsv lst
#:optional
(port (current-output-port))
(delimiter 'default)
#:key
(format 'unix))
"Write a list of values LST as a sequence of DSV strings to a PORT using a
specified DSV FORMAT. If the PORT is not set, write to the default output
port. If a DELIMITER is not set, use the default delimiter for a FORMAT.
Throws 'dsv-parser-error' on an error. Return value is unspecified."
(let ((lst (if (or (null? lst) (list? (car lst)))
lst
(list lst))))
(case format
((unix)
(let ((builder (unix:make-builder lst port delimiter 'default)))
(unix:scm->dsv builder)))
((rfc4180)
(let ((builder (rfc4180:make-builder lst port delimiter 'default)))
(rfc4180:scm->dsv builder)))
(else
(dsv-error "Unknown format" format)))))
(define* (scm->dsv-string lst
#:optional (delimiter 'default)
#:key (format 'unix))
"Convert a list LST to a DSV string using a specified DSV FORMAT. If the
DELIMITER is not set, use the default delimiter for a FORMAT. Return a DSV
(let ((lst (if (or (null? lst) (list? (car lst)))
lst
(list lst))))
(case format
((unix)
(unix:scm->dsv-string lst delimiter 'default))
((rfc4180)
(rfc4180:scm->dsv-string lst delimiter 'default))
(else
(dsv-error "Unknown format" format)))))
(define* (guess-delimiter str #:optional (known-delimiters 'default)
#:key (format 'unix))
"Guess a DSV string STR delimiter. Optionally accept list of
KNOWN-DELIMITERS as an argument. The procedure returns guessed delimiter or
'#f' if it cannot determine a delimiter based on the given arguments, or
throws 'dsv-parser-error' on an error.
Note that when KNOWN-DELIMITERS list contains less than two elements, the
procedure returns '#f'."
(case format
((unix)
(let ((parser (unix:make-string-parser str 'default known-delimiters
'default)))
(unix:guess-delimiter parser)))
((rfc4180)
(let ((parser (rfc4180:make-string-parser str 'default known-delimiters
'default)))
(rfc4180:guess-delimiter parser)))
(else
(dsv-error "Unknown format." format))))
|
6d53803329bcb9eee80aab1e5e3eb1238d1ce06d487c7b3efe1fd9c0a082e61c | mfoemmel/erlang-otp | wxAuiPaneInfo.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
%% @doc See external documentation: <a href="">wxAuiPaneInfo</a>.
%% @type wxAuiPaneInfo(). An object reference, The representation is internal
%% and can be changed without notice. It can't be used for comparsion
%% stored on disc or distributed for use on other nodes.
-module(wxAuiPaneInfo).
-include("wxe.hrl").
-export([bestSize/2,bestSize/3,bottom/1,bottomDockable/1,bottomDockable/2,caption/2,
captionVisible/1,captionVisible/2,centre/1,centrePane/1,closeButton/1,
closeButton/2,defaultPane/1,destroy/1,destroyOnClose/1,destroyOnClose/2,
direction/2,dock/1,dockable/1,dockable/2,fixed/1,float/1,floatable/1,
floatable/2,floatingPosition/2,floatingPosition/3,floatingSize/2,
floatingSize/3,gripper/1,gripper/2,gripperTop/1,gripperTop/2,hasBorder/1,
hasCaption/1,hasCloseButton/1,hasFlag/2,hasGripper/1,hasGripperTop/1,
hasMaximizeButton/1,hasMinimizeButton/1,hasPinButton/1,hide/1,isBottomDockable/1,
isDocked/1,isFixed/1,isFloatable/1,isFloating/1,isLeftDockable/1,isMovable/1,
isOk/1,isResizable/1,isRightDockable/1,isShown/1,isToolbar/1,isTopDockable/1,
layer/2,left/1,leftDockable/1,leftDockable/2,maxSize/2,maxSize/3,maximizeButton/1,
maximizeButton/2,minSize/2,minSize/3,minimizeButton/1,minimizeButton/2,
movable/1,movable/2,name/2,new/0,new/1,paneBorder/1,paneBorder/2,pinButton/1,
pinButton/2,position/2,resizable/1,resizable/2,right/1,rightDockable/1,
rightDockable/2,row/2,safeSet/2,setFlag/3,show/1,show/2,toolbarPane/1,
top/1,topDockable/1,topDockable/2,window/2]).
%% inherited exports
-export([parent_class/1]).
%% @hidden
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
( ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfowxauipaneinfo">external documentation</a>.
new() ->
wxe_util:construct(?wxAuiPaneInfo_new_0,
<<>>).
( C::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfowxauipaneinfo">external documentation</a>.
new(#wx_ref{type=CT,ref=CRef}) ->
?CLASS(CT,wxAuiPaneInfo),
wxe_util:construct(?wxAuiPaneInfo_new_1,
<<CRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) , Size::{W::integer(),H::integer ( ) } ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfobestsize">external documentation</a>.
bestSize(#wx_ref{type=ThisT,ref=ThisRef},{SizeW,SizeH})
when is_integer(SizeW),is_integer(SizeH) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_BestSize_1,
<<ThisRef:32/?UI,SizeW:32/?UI,SizeH:32/?UI>>).
( This::wxAuiPaneInfo ( ) , X::integer ( ) , Y::integer ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfobestsize">external documentation</a>.
bestSize(#wx_ref{type=ThisT,ref=ThisRef},X,Y)
when is_integer(X),is_integer(Y) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_BestSize_2,
<<ThisRef:32/?UI,X:32/?UI,Y:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfobottom">external documentation</a>.
bottom(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Bottom,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv bottomDockable(This, [])
bottomDockable(This)
when is_record(This, wx_ref) ->
bottomDockable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
%% @doc See <a href="#wxauipaneinfobottomdockable">external documentation</a>.
bottomDockable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_BottomDockable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , C::string ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfocaption">external documentation</a>.
caption(#wx_ref{type=ThisT,ref=ThisRef},C)
when is_list(C) ->
?CLASS(ThisT,wxAuiPaneInfo),
C_UC = unicode:characters_to_binary([C,0]),
wxe_util:call(?wxAuiPaneInfo_Caption,
<<ThisRef:32/?UI,(byte_size(C_UC)):32/?UI,(C_UC)/binary, 0:(((8- ((0+byte_size(C_UC)) band 16#7)) band 16#7))/unit:8>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv captionVisible(This, [])
captionVisible(This)
when is_record(This, wx_ref) ->
captionVisible(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
%% Option = {visible, bool()}
%% @doc See <a href="#wxauipaneinfocaptionvisible">external documentation</a>.
captionVisible(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_CaptionVisible,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfocentre">external documentation</a>.
centre(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Centre,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfocentrepane">external documentation</a>.
centrePane(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_CentrePane,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv closeButton(This, [])
closeButton(This)
when is_record(This, wx_ref) ->
closeButton(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
%% Option = {visible, bool()}
%% @doc See <a href="#wxauipaneinfoclosebutton">external documentation</a>.
closeButton(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_CloseButton,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfodefaultpane">external documentation</a>.
defaultPane(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_DefaultPane,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv destroyOnClose(This, [])
destroyOnClose(This)
when is_record(This, wx_ref) ->
destroyOnClose(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
%% @doc See <a href="#wxauipaneinfodestroyonclose">external documentation</a>.
destroyOnClose(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_DestroyOnClose,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , Direction::integer ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfodirection">external documentation</a>.
direction(#wx_ref{type=ThisT,ref=ThisRef},Direction)
when is_integer(Direction) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Direction,
<<ThisRef:32/?UI,Direction:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfodock">external documentation</a>.
dock(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Dock,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv dockable(This, [])
dockable(This)
when is_record(This, wx_ref) ->
dockable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
%% @doc See <a href="#wxauipaneinfodockable">external documentation</a>.
dockable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_Dockable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfofixed">external documentation</a>.
fixed(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Fixed,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfofloat">external documentation</a>.
float(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Float,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv floatable(This, [])
floatable(This)
when is_record(This, wx_ref) ->
floatable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
%% @doc See <a href="#wxauipaneinfofloatable">external documentation</a>.
floatable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_Floatable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , Pos::{X::integer(),Y::integer ( ) } ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfofloatingposition">external documentation</a>.
floatingPosition(#wx_ref{type=ThisT,ref=ThisRef},{PosX,PosY})
when is_integer(PosX),is_integer(PosY) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_FloatingPosition_1,
<<ThisRef:32/?UI,PosX:32/?UI,PosY:32/?UI>>).
( This::wxAuiPaneInfo ( ) , X::integer ( ) , Y::integer ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfofloatingposition">external documentation</a>.
floatingPosition(#wx_ref{type=ThisT,ref=ThisRef},X,Y)
when is_integer(X),is_integer(Y) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_FloatingPosition_2,
<<ThisRef:32/?UI,X:32/?UI,Y:32/?UI>>).
( This::wxAuiPaneInfo ( ) , Size::{W::integer(),H::integer ( ) } ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfofloatingsize">external documentation</a>.
floatingSize(#wx_ref{type=ThisT,ref=ThisRef},{SizeW,SizeH})
when is_integer(SizeW),is_integer(SizeH) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_FloatingSize_1,
<<ThisRef:32/?UI,SizeW:32/?UI,SizeH:32/?UI>>).
( This::wxAuiPaneInfo ( ) , X::integer ( ) , Y::integer ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfofloatingsize">external documentation</a>.
floatingSize(#wx_ref{type=ThisT,ref=ThisRef},X,Y)
when is_integer(X),is_integer(Y) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_FloatingSize_2,
<<ThisRef:32/?UI,X:32/?UI,Y:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv gripper(This, [])
gripper(This)
when is_record(This, wx_ref) ->
gripper(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
%% Option = {visible, bool()}
%% @doc See <a href="#wxauipaneinfogripper">external documentation</a>.
gripper(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_Gripper,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv gripperTop(This, [])
gripperTop(This)
when is_record(This, wx_ref) ->
gripperTop(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
%% Option = {attop, bool()}
%% @doc See <a href="#wxauipaneinfogrippertop">external documentation</a>.
gripperTop(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({attop, Attop}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Attop)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_GripperTop,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfohasborder">external documentation</a>.
hasBorder(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasBorder,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfohascaption">external documentation</a>.
hasCaption(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasCaption,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfohasclosebutton">external documentation</a>.
hasCloseButton(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasCloseButton,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) , Flag::integer ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfohasflag">external documentation</a>.
hasFlag(#wx_ref{type=ThisT,ref=ThisRef},Flag)
when is_integer(Flag) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasFlag,
<<ThisRef:32/?UI,Flag:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfohasgripper">external documentation</a>.
hasGripper(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasGripper,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfohasgrippertop">external documentation</a>.
hasGripperTop(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasGripperTop,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfohasmaximizebutton">external documentation</a>.
hasMaximizeButton(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasMaximizeButton,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfohasminimizebutton">external documentation</a>.
hasMinimizeButton(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasMinimizeButton,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfohaspinbutton">external documentation</a>.
hasPinButton(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasPinButton,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfohide">external documentation</a>.
hide(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Hide,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfoisbottomdockable">external documentation</a>.
isBottomDockable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsBottomDockable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfoisdocked">external documentation</a>.
isDocked(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsDocked,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfoisfixed">external documentation</a>.
isFixed(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsFixed,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfoisfloatable">external documentation</a>.
isFloatable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsFloatable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfoisfloating">external documentation</a>.
isFloating(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsFloating,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfoisleftdockable">external documentation</a>.
isLeftDockable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsLeftDockable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfoismovable">external documentation</a>.
isMovable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsMovable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfoisok">external documentation</a>.
isOk(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsOk,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfoisresizable">external documentation</a>.
isResizable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsResizable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfoisrightdockable">external documentation</a>.
isRightDockable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsRightDockable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfoisshown">external documentation</a>.
isShown(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsShown,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfoistoolbar">external documentation</a>.
isToolbar(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsToolbar,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
%% @doc See <a href="#wxauipaneinfoistopdockable">external documentation</a>.
isTopDockable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsTopDockable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) , Layer::integer ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfolayer">external documentation</a>.
layer(#wx_ref{type=ThisT,ref=ThisRef},Layer)
when is_integer(Layer) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Layer,
<<ThisRef:32/?UI,Layer:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfoleft">external documentation</a>.
left(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Left,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv leftDockable(This, [])
leftDockable(This)
when is_record(This, wx_ref) ->
leftDockable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
%% @doc See <a href="#wxauipaneinfoleftdockable">external documentation</a>.
leftDockable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_LeftDockable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , Size::{W::integer(),H::integer ( ) } ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfomaxsize">external documentation</a>.
maxSize(#wx_ref{type=ThisT,ref=ThisRef},{SizeW,SizeH})
when is_integer(SizeW),is_integer(SizeH) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_MaxSize_1,
<<ThisRef:32/?UI,SizeW:32/?UI,SizeH:32/?UI>>).
( This::wxAuiPaneInfo ( ) , X::integer ( ) , Y::integer ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfomaxsize">external documentation</a>.
maxSize(#wx_ref{type=ThisT,ref=ThisRef},X,Y)
when is_integer(X),is_integer(Y) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_MaxSize_2,
<<ThisRef:32/?UI,X:32/?UI,Y:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv maximizeButton(This, [])
maximizeButton(This)
when is_record(This, wx_ref) ->
maximizeButton(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
%% Option = {visible, bool()}
%% @doc See <a href="#wxauipaneinfomaximizebutton">external documentation</a>.
maximizeButton(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_MaximizeButton,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , Size::{W::integer(),H::integer ( ) } ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfominsize">external documentation</a>.
minSize(#wx_ref{type=ThisT,ref=ThisRef},{SizeW,SizeH})
when is_integer(SizeW),is_integer(SizeH) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_MinSize_1,
<<ThisRef:32/?UI,SizeW:32/?UI,SizeH:32/?UI>>).
( This::wxAuiPaneInfo ( ) , X::integer ( ) , Y::integer ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfominsize">external documentation</a>.
minSize(#wx_ref{type=ThisT,ref=ThisRef},X,Y)
when is_integer(X),is_integer(Y) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_MinSize_2,
<<ThisRef:32/?UI,X:32/?UI,Y:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv minimizeButton(This, [])
minimizeButton(This)
when is_record(This, wx_ref) ->
minimizeButton(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
%% Option = {visible, bool()}
%% @doc See <a href="#wxauipaneinfominimizebutton">external documentation</a>.
minimizeButton(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_MinimizeButton,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv movable(This, [])
movable(This)
when is_record(This, wx_ref) ->
movable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
%% @doc See <a href="#wxauipaneinfomovable">external documentation</a>.
movable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_Movable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfoname">external documentation</a>.
name(#wx_ref{type=ThisT,ref=ThisRef},N)
when is_list(N) ->
?CLASS(ThisT,wxAuiPaneInfo),
N_UC = unicode:characters_to_binary([N,0]),
wxe_util:call(?wxAuiPaneInfo_Name,
<<ThisRef:32/?UI,(byte_size(N_UC)):32/?UI,(N_UC)/binary, 0:(((8- ((0+byte_size(N_UC)) band 16#7)) band 16#7))/unit:8>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv paneBorder(This, [])
paneBorder(This)
when is_record(This, wx_ref) ->
paneBorder(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
%% Option = {visible, bool()}
%% @doc See <a href="#wxauipaneinfopaneborder">external documentation</a>.
paneBorder(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_PaneBorder,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv pinButton(This, [])
pinButton(This)
when is_record(This, wx_ref) ->
pinButton(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
%% Option = {visible, bool()}
%% @doc See <a href="#wxauipaneinfopinbutton">external documentation</a>.
pinButton(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_PinButton,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , Pos::integer ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfoposition">external documentation</a>.
position(#wx_ref{type=ThisT,ref=ThisRef},Pos)
when is_integer(Pos) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Position,
<<ThisRef:32/?UI,Pos:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv resizable(This, [])
resizable(This)
when is_record(This, wx_ref) ->
resizable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
%% Option = {resizable, bool()}
%% @doc See <a href="#wxauipaneinforesizable">external documentation</a>.
resizable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({resizable, Resizable}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Resizable)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_Resizable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinforight">external documentation</a>.
right(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Right,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv rightDockable(This, [])
rightDockable(This)
when is_record(This, wx_ref) ->
rightDockable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
%% @doc See <a href="#wxauipaneinforightdockable">external documentation</a>.
rightDockable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_RightDockable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , Row::integer ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinforow">external documentation</a>.
row(#wx_ref{type=ThisT,ref=ThisRef},Row)
when is_integer(Row) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Row,
<<ThisRef:32/?UI,Row:32/?UI>>).
( This::wxAuiPaneInfo ( ) , Source::wxAuiPaneInfo ( ) ) - > ok
%% @doc See <a href="#wxauipaneinfosafeset">external documentation</a>.
safeSet(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=SourceT,ref=SourceRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
?CLASS(SourceT,wxAuiPaneInfo),
wxe_util:cast(?wxAuiPaneInfo_SafeSet,
<<ThisRef:32/?UI,SourceRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) , Flag::integer ( ) , ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfosetflag">external documentation</a>.
setFlag(#wx_ref{type=ThisT,ref=ThisRef},Flag,Option_state)
when is_integer(Flag),is_boolean(Option_state) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_SetFlag,
<<ThisRef:32/?UI,Flag:32/?UI,(wxe_util:from_bool(Option_state)):32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv show(This, [])
show(This)
when is_record(This, wx_ref) ->
show(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
%% Option = {show, bool()}
%% @doc See <a href="#wxauipaneinfoshow">external documentation</a>.
show(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({show, Show}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Show)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_Show,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
@doc See < a href=" / manuals / stable / wx_wxauipaneinfo.html#wxauipaneinfotoolbarpane">external documentation</a > .
toolbarPane(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_ToolbarPane,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfotop">external documentation</a>.
top(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Top,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
%% @equiv topDockable(This, [])
topDockable(This)
when is_record(This, wx_ref) ->
topDockable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
%% @doc See <a href="#wxauipaneinfotopdockable">external documentation</a>.
topDockable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_TopDockable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , W::wxWindow : wxWindow ( ) ) - > wxAuiPaneInfo ( )
%% @doc See <a href="#wxauipaneinfowindow">external documentation</a>.
window(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=WT,ref=WRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
?CLASS(WT,wxWindow),
wxe_util:call(?wxAuiPaneInfo_Window,
<<ThisRef:32/?UI,WRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > ok
%% @doc Destroys this object, do not use object again
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxAuiPaneInfo),
wxe_util:destroy(?wxAuiPaneInfo_destruct,Obj),
ok.
| null | https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/wx/src/gen/wxAuiPaneInfo.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
This file is generated DO NOT EDIT
@doc See external documentation: <a href="">wxAuiPaneInfo</a>.
@type wxAuiPaneInfo(). An object reference, The representation is internal
and can be changed without notice. It can't be used for comparsion
stored on disc or distributed for use on other nodes.
inherited exports
@hidden
@doc See <a href="#wxauipaneinfowxauipaneinfo">external documentation</a>.
@doc See <a href="#wxauipaneinfowxauipaneinfo">external documentation</a>.
@doc See <a href="#wxauipaneinfobestsize">external documentation</a>.
@doc See <a href="#wxauipaneinfobestsize">external documentation</a>.
@doc See <a href="#wxauipaneinfobottom">external documentation</a>.
@equiv bottomDockable(This, [])
@doc See <a href="#wxauipaneinfobottomdockable">external documentation</a>.
@doc See <a href="#wxauipaneinfocaption">external documentation</a>.
@equiv captionVisible(This, [])
Option = {visible, bool()}
@doc See <a href="#wxauipaneinfocaptionvisible">external documentation</a>.
@doc See <a href="#wxauipaneinfocentre">external documentation</a>.
@doc See <a href="#wxauipaneinfocentrepane">external documentation</a>.
@equiv closeButton(This, [])
Option = {visible, bool()}
@doc See <a href="#wxauipaneinfoclosebutton">external documentation</a>.
@doc See <a href="#wxauipaneinfodefaultpane">external documentation</a>.
@equiv destroyOnClose(This, [])
@doc See <a href="#wxauipaneinfodestroyonclose">external documentation</a>.
@doc See <a href="#wxauipaneinfodirection">external documentation</a>.
@doc See <a href="#wxauipaneinfodock">external documentation</a>.
@equiv dockable(This, [])
@doc See <a href="#wxauipaneinfodockable">external documentation</a>.
@doc See <a href="#wxauipaneinfofixed">external documentation</a>.
@doc See <a href="#wxauipaneinfofloat">external documentation</a>.
@equiv floatable(This, [])
@doc See <a href="#wxauipaneinfofloatable">external documentation</a>.
@doc See <a href="#wxauipaneinfofloatingposition">external documentation</a>.
@doc See <a href="#wxauipaneinfofloatingposition">external documentation</a>.
@doc See <a href="#wxauipaneinfofloatingsize">external documentation</a>.
@doc See <a href="#wxauipaneinfofloatingsize">external documentation</a>.
@equiv gripper(This, [])
Option = {visible, bool()}
@doc See <a href="#wxauipaneinfogripper">external documentation</a>.
@equiv gripperTop(This, [])
Option = {attop, bool()}
@doc See <a href="#wxauipaneinfogrippertop">external documentation</a>.
@doc See <a href="#wxauipaneinfohasborder">external documentation</a>.
@doc See <a href="#wxauipaneinfohascaption">external documentation</a>.
@doc See <a href="#wxauipaneinfohasclosebutton">external documentation</a>.
@doc See <a href="#wxauipaneinfohasflag">external documentation</a>.
@doc See <a href="#wxauipaneinfohasgripper">external documentation</a>.
@doc See <a href="#wxauipaneinfohasgrippertop">external documentation</a>.
@doc See <a href="#wxauipaneinfohasmaximizebutton">external documentation</a>.
@doc See <a href="#wxauipaneinfohasminimizebutton">external documentation</a>.
@doc See <a href="#wxauipaneinfohaspinbutton">external documentation</a>.
@doc See <a href="#wxauipaneinfohide">external documentation</a>.
@doc See <a href="#wxauipaneinfoisbottomdockable">external documentation</a>.
@doc See <a href="#wxauipaneinfoisdocked">external documentation</a>.
@doc See <a href="#wxauipaneinfoisfixed">external documentation</a>.
@doc See <a href="#wxauipaneinfoisfloatable">external documentation</a>.
@doc See <a href="#wxauipaneinfoisfloating">external documentation</a>.
@doc See <a href="#wxauipaneinfoisleftdockable">external documentation</a>.
@doc See <a href="#wxauipaneinfoismovable">external documentation</a>.
@doc See <a href="#wxauipaneinfoisok">external documentation</a>.
@doc See <a href="#wxauipaneinfoisresizable">external documentation</a>.
@doc See <a href="#wxauipaneinfoisrightdockable">external documentation</a>.
@doc See <a href="#wxauipaneinfoisshown">external documentation</a>.
@doc See <a href="#wxauipaneinfoistoolbar">external documentation</a>.
@doc See <a href="#wxauipaneinfoistopdockable">external documentation</a>.
@doc See <a href="#wxauipaneinfolayer">external documentation</a>.
@doc See <a href="#wxauipaneinfoleft">external documentation</a>.
@equiv leftDockable(This, [])
@doc See <a href="#wxauipaneinfoleftdockable">external documentation</a>.
@doc See <a href="#wxauipaneinfomaxsize">external documentation</a>.
@doc See <a href="#wxauipaneinfomaxsize">external documentation</a>.
@equiv maximizeButton(This, [])
Option = {visible, bool()}
@doc See <a href="#wxauipaneinfomaximizebutton">external documentation</a>.
@doc See <a href="#wxauipaneinfominsize">external documentation</a>.
@doc See <a href="#wxauipaneinfominsize">external documentation</a>.
@equiv minimizeButton(This, [])
Option = {visible, bool()}
@doc See <a href="#wxauipaneinfominimizebutton">external documentation</a>.
@equiv movable(This, [])
@doc See <a href="#wxauipaneinfomovable">external documentation</a>.
@doc See <a href="#wxauipaneinfoname">external documentation</a>.
@equiv paneBorder(This, [])
Option = {visible, bool()}
@doc See <a href="#wxauipaneinfopaneborder">external documentation</a>.
@equiv pinButton(This, [])
Option = {visible, bool()}
@doc See <a href="#wxauipaneinfopinbutton">external documentation</a>.
@doc See <a href="#wxauipaneinfoposition">external documentation</a>.
@equiv resizable(This, [])
Option = {resizable, bool()}
@doc See <a href="#wxauipaneinforesizable">external documentation</a>.
@doc See <a href="#wxauipaneinforight">external documentation</a>.
@equiv rightDockable(This, [])
@doc See <a href="#wxauipaneinforightdockable">external documentation</a>.
@doc See <a href="#wxauipaneinforow">external documentation</a>.
@doc See <a href="#wxauipaneinfosafeset">external documentation</a>.
@doc See <a href="#wxauipaneinfosetflag">external documentation</a>.
@equiv show(This, [])
Option = {show, bool()}
@doc See <a href="#wxauipaneinfoshow">external documentation</a>.
@doc See <a href="#wxauipaneinfotop">external documentation</a>.
@equiv topDockable(This, [])
@doc See <a href="#wxauipaneinfotopdockable">external documentation</a>.
@doc See <a href="#wxauipaneinfowindow">external documentation</a>.
@doc Destroys this object, do not use object again | Copyright Ericsson AB 2008 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(wxAuiPaneInfo).
-include("wxe.hrl").
-export([bestSize/2,bestSize/3,bottom/1,bottomDockable/1,bottomDockable/2,caption/2,
captionVisible/1,captionVisible/2,centre/1,centrePane/1,closeButton/1,
closeButton/2,defaultPane/1,destroy/1,destroyOnClose/1,destroyOnClose/2,
direction/2,dock/1,dockable/1,dockable/2,fixed/1,float/1,floatable/1,
floatable/2,floatingPosition/2,floatingPosition/3,floatingSize/2,
floatingSize/3,gripper/1,gripper/2,gripperTop/1,gripperTop/2,hasBorder/1,
hasCaption/1,hasCloseButton/1,hasFlag/2,hasGripper/1,hasGripperTop/1,
hasMaximizeButton/1,hasMinimizeButton/1,hasPinButton/1,hide/1,isBottomDockable/1,
isDocked/1,isFixed/1,isFloatable/1,isFloating/1,isLeftDockable/1,isMovable/1,
isOk/1,isResizable/1,isRightDockable/1,isShown/1,isToolbar/1,isTopDockable/1,
layer/2,left/1,leftDockable/1,leftDockable/2,maxSize/2,maxSize/3,maximizeButton/1,
maximizeButton/2,minSize/2,minSize/3,minimizeButton/1,minimizeButton/2,
movable/1,movable/2,name/2,new/0,new/1,paneBorder/1,paneBorder/2,pinButton/1,
pinButton/2,position/2,resizable/1,resizable/2,right/1,rightDockable/1,
rightDockable/2,row/2,safeSet/2,setFlag/3,show/1,show/2,toolbarPane/1,
top/1,topDockable/1,topDockable/2,window/2]).
-export([parent_class/1]).
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
( ) - > wxAuiPaneInfo ( )
new() ->
wxe_util:construct(?wxAuiPaneInfo_new_0,
<<>>).
( C::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
new(#wx_ref{type=CT,ref=CRef}) ->
?CLASS(CT,wxAuiPaneInfo),
wxe_util:construct(?wxAuiPaneInfo_new_1,
<<CRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) , Size::{W::integer(),H::integer ( ) } ) - > wxAuiPaneInfo ( )
bestSize(#wx_ref{type=ThisT,ref=ThisRef},{SizeW,SizeH})
when is_integer(SizeW),is_integer(SizeH) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_BestSize_1,
<<ThisRef:32/?UI,SizeW:32/?UI,SizeH:32/?UI>>).
( This::wxAuiPaneInfo ( ) , X::integer ( ) , Y::integer ( ) ) - > wxAuiPaneInfo ( )
bestSize(#wx_ref{type=ThisT,ref=ThisRef},X,Y)
when is_integer(X),is_integer(Y) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_BestSize_2,
<<ThisRef:32/?UI,X:32/?UI,Y:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
bottom(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Bottom,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
bottomDockable(This)
when is_record(This, wx_ref) ->
bottomDockable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
bottomDockable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_BottomDockable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , C::string ( ) ) - > wxAuiPaneInfo ( )
caption(#wx_ref{type=ThisT,ref=ThisRef},C)
when is_list(C) ->
?CLASS(ThisT,wxAuiPaneInfo),
C_UC = unicode:characters_to_binary([C,0]),
wxe_util:call(?wxAuiPaneInfo_Caption,
<<ThisRef:32/?UI,(byte_size(C_UC)):32/?UI,(C_UC)/binary, 0:(((8- ((0+byte_size(C_UC)) band 16#7)) band 16#7))/unit:8>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
captionVisible(This)
when is_record(This, wx_ref) ->
captionVisible(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
captionVisible(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_CaptionVisible,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
centre(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Centre,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
centrePane(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_CentrePane,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
closeButton(This)
when is_record(This, wx_ref) ->
closeButton(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
closeButton(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_CloseButton,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
defaultPane(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_DefaultPane,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
destroyOnClose(This)
when is_record(This, wx_ref) ->
destroyOnClose(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
destroyOnClose(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_DestroyOnClose,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , Direction::integer ( ) ) - > wxAuiPaneInfo ( )
direction(#wx_ref{type=ThisT,ref=ThisRef},Direction)
when is_integer(Direction) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Direction,
<<ThisRef:32/?UI,Direction:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
dock(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Dock,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
dockable(This)
when is_record(This, wx_ref) ->
dockable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
dockable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_Dockable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
fixed(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Fixed,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
float(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Float,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
floatable(This)
when is_record(This, wx_ref) ->
floatable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
floatable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_Floatable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , Pos::{X::integer(),Y::integer ( ) } ) - > wxAuiPaneInfo ( )
floatingPosition(#wx_ref{type=ThisT,ref=ThisRef},{PosX,PosY})
when is_integer(PosX),is_integer(PosY) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_FloatingPosition_1,
<<ThisRef:32/?UI,PosX:32/?UI,PosY:32/?UI>>).
( This::wxAuiPaneInfo ( ) , X::integer ( ) , Y::integer ( ) ) - > wxAuiPaneInfo ( )
floatingPosition(#wx_ref{type=ThisT,ref=ThisRef},X,Y)
when is_integer(X),is_integer(Y) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_FloatingPosition_2,
<<ThisRef:32/?UI,X:32/?UI,Y:32/?UI>>).
( This::wxAuiPaneInfo ( ) , Size::{W::integer(),H::integer ( ) } ) - > wxAuiPaneInfo ( )
floatingSize(#wx_ref{type=ThisT,ref=ThisRef},{SizeW,SizeH})
when is_integer(SizeW),is_integer(SizeH) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_FloatingSize_1,
<<ThisRef:32/?UI,SizeW:32/?UI,SizeH:32/?UI>>).
( This::wxAuiPaneInfo ( ) , X::integer ( ) , Y::integer ( ) ) - > wxAuiPaneInfo ( )
floatingSize(#wx_ref{type=ThisT,ref=ThisRef},X,Y)
when is_integer(X),is_integer(Y) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_FloatingSize_2,
<<ThisRef:32/?UI,X:32/?UI,Y:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
gripper(This)
when is_record(This, wx_ref) ->
gripper(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
gripper(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_Gripper,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
gripperTop(This)
when is_record(This, wx_ref) ->
gripperTop(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
gripperTop(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({attop, Attop}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Attop)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_GripperTop,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
hasBorder(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasBorder,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
hasCaption(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasCaption,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
hasCloseButton(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasCloseButton,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) , Flag::integer ( ) ) - > bool ( )
hasFlag(#wx_ref{type=ThisT,ref=ThisRef},Flag)
when is_integer(Flag) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasFlag,
<<ThisRef:32/?UI,Flag:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
hasGripper(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasGripper,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
hasGripperTop(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasGripperTop,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
hasMaximizeButton(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasMaximizeButton,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
hasMinimizeButton(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasMinimizeButton,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
hasPinButton(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_HasPinButton,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
hide(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Hide,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
isBottomDockable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsBottomDockable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
isDocked(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsDocked,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
isFixed(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsFixed,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
isFloatable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsFloatable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
isFloating(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsFloating,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
isLeftDockable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsLeftDockable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
isMovable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsMovable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
isOk(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsOk,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
isResizable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsResizable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
isRightDockable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsRightDockable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
isShown(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsShown,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
isToolbar(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsToolbar,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > bool ( )
isTopDockable(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_IsTopDockable,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) , Layer::integer ( ) ) - > wxAuiPaneInfo ( )
layer(#wx_ref{type=ThisT,ref=ThisRef},Layer)
when is_integer(Layer) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Layer,
<<ThisRef:32/?UI,Layer:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
left(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Left,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
leftDockable(This)
when is_record(This, wx_ref) ->
leftDockable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
leftDockable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_LeftDockable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , Size::{W::integer(),H::integer ( ) } ) - > wxAuiPaneInfo ( )
maxSize(#wx_ref{type=ThisT,ref=ThisRef},{SizeW,SizeH})
when is_integer(SizeW),is_integer(SizeH) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_MaxSize_1,
<<ThisRef:32/?UI,SizeW:32/?UI,SizeH:32/?UI>>).
( This::wxAuiPaneInfo ( ) , X::integer ( ) , Y::integer ( ) ) - > wxAuiPaneInfo ( )
maxSize(#wx_ref{type=ThisT,ref=ThisRef},X,Y)
when is_integer(X),is_integer(Y) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_MaxSize_2,
<<ThisRef:32/?UI,X:32/?UI,Y:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
maximizeButton(This)
when is_record(This, wx_ref) ->
maximizeButton(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
maximizeButton(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_MaximizeButton,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , Size::{W::integer(),H::integer ( ) } ) - > wxAuiPaneInfo ( )
minSize(#wx_ref{type=ThisT,ref=ThisRef},{SizeW,SizeH})
when is_integer(SizeW),is_integer(SizeH) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_MinSize_1,
<<ThisRef:32/?UI,SizeW:32/?UI,SizeH:32/?UI>>).
( This::wxAuiPaneInfo ( ) , X::integer ( ) , Y::integer ( ) ) - > wxAuiPaneInfo ( )
minSize(#wx_ref{type=ThisT,ref=ThisRef},X,Y)
when is_integer(X),is_integer(Y) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_MinSize_2,
<<ThisRef:32/?UI,X:32/?UI,Y:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
minimizeButton(This)
when is_record(This, wx_ref) ->
minimizeButton(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
minimizeButton(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_MinimizeButton,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
movable(This)
when is_record(This, wx_ref) ->
movable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
movable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_Movable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , ( ) ) - > wxAuiPaneInfo ( )
name(#wx_ref{type=ThisT,ref=ThisRef},N)
when is_list(N) ->
?CLASS(ThisT,wxAuiPaneInfo),
N_UC = unicode:characters_to_binary([N,0]),
wxe_util:call(?wxAuiPaneInfo_Name,
<<ThisRef:32/?UI,(byte_size(N_UC)):32/?UI,(N_UC)/binary, 0:(((8- ((0+byte_size(N_UC)) band 16#7)) band 16#7))/unit:8>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
paneBorder(This)
when is_record(This, wx_ref) ->
paneBorder(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
paneBorder(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_PaneBorder,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
pinButton(This)
when is_record(This, wx_ref) ->
pinButton(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
pinButton(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({visible, Visible}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Visible)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_PinButton,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , Pos::integer ( ) ) - > wxAuiPaneInfo ( )
position(#wx_ref{type=ThisT,ref=ThisRef},Pos)
when is_integer(Pos) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Position,
<<ThisRef:32/?UI,Pos:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
resizable(This)
when is_record(This, wx_ref) ->
resizable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
resizable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({resizable, Resizable}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Resizable)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_Resizable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
right(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Right,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
rightDockable(This)
when is_record(This, wx_ref) ->
rightDockable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
rightDockable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_RightDockable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , Row::integer ( ) ) - > wxAuiPaneInfo ( )
row(#wx_ref{type=ThisT,ref=ThisRef},Row)
when is_integer(Row) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Row,
<<ThisRef:32/?UI,Row:32/?UI>>).
( This::wxAuiPaneInfo ( ) , Source::wxAuiPaneInfo ( ) ) - > ok
safeSet(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=SourceT,ref=SourceRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
?CLASS(SourceT,wxAuiPaneInfo),
wxe_util:cast(?wxAuiPaneInfo_SafeSet,
<<ThisRef:32/?UI,SourceRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) , Flag::integer ( ) , ( ) ) - > wxAuiPaneInfo ( )
setFlag(#wx_ref{type=ThisT,ref=ThisRef},Flag,Option_state)
when is_integer(Flag),is_boolean(Option_state) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_SetFlag,
<<ThisRef:32/?UI,Flag:32/?UI,(wxe_util:from_bool(Option_state)):32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
show(This)
when is_record(This, wx_ref) ->
show(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
show(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({show, Show}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Show)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_Show,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
@doc See < a href=" / manuals / stable / wx_wxauipaneinfo.html#wxauipaneinfotoolbarpane">external documentation</a > .
toolbarPane(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_ToolbarPane,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
top(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
wxe_util:call(?wxAuiPaneInfo_Top,
<<ThisRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > wxAuiPaneInfo ( )
topDockable(This)
when is_record(This, wx_ref) ->
topDockable(This, []).
( This::wxAuiPaneInfo ( ) , [ Option ] ) - > wxAuiPaneInfo ( )
Option = { b , ( ) }
topDockable(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxAuiPaneInfo),
MOpts = fun({b, B}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(B)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxAuiPaneInfo_TopDockable,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
( This::wxAuiPaneInfo ( ) , W::wxWindow : wxWindow ( ) ) - > wxAuiPaneInfo ( )
window(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=WT,ref=WRef}) ->
?CLASS(ThisT,wxAuiPaneInfo),
?CLASS(WT,wxWindow),
wxe_util:call(?wxAuiPaneInfo_Window,
<<ThisRef:32/?UI,WRef:32/?UI>>).
( This::wxAuiPaneInfo ( ) ) - > ok
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxAuiPaneInfo),
wxe_util:destroy(?wxAuiPaneInfo_destruct,Obj),
ok.
|
25e87dd98975b30a5f76ed99439eac111ae402f185e67696ee7acbc84ae42f5c | fortytools/holumbus | Console.hs | -- ----------------------------------------------------------------------------
|
Module : Holumbus . Console . Console
Copyright : Copyright ( C ) 2008
License : MIT
Maintainer : ( )
Stability : experimental
Portability : portable
Version : 0.1
This module provides a tiny and nice implementation of a little command
shell . It can be feed with individual commands and provides a simple but
powerful way to interact with your program . The following functions are
implemented by default :
exit - exit the console loop
help - print a nice help
There was a little " bug " with the System . Console . Readline package . When
we use this option , we make a foreign call ... and the library
documentation say this about concurrency and GHC :
" If you do n't use the -threaded option , then the runtime does not make
use of multiple OS threads . Foreign calls will block all other running
Haskell threads until the call returns .
The System . IO library still does multiplexing , so there can be multiple
threads doing IO , and this is handled internally by the runtime using
select . "
We make a foreign call , which is not in the System . IO library , so we
have to work with -threaded when we want a fancy command history .
Module : Holumbus.Console.Console
Copyright : Copyright (C) 2008 Stefan Schmidt
License : MIT
Maintainer : Stefan Schmidt ()
Stability : experimental
Portability: portable
Version : 0.1
This module provides a tiny and nice implementation of a little command
shell. It can be feed with individual commands and provides a simple but
powerful way to interact with your program. The following functions are
implemented by default:
exit - exit the console loop
help - print a nice help
There was a little "bug" with the System.Console.Readline package. When
we use this option, we make a foreign call... and the Haskell library
documentation say this about concurrency and GHC:
"If you don't use the -threaded option, then the runtime does not make
use of multiple OS threads. Foreign calls will block all other running
Haskell threads until the call returns.
The System.IO library still does multiplexing, so there can be multiple
threads doing IO, and this is handled internally by the runtime using
select."
We make a foreign call, which is not in the System.IO library, so we
have to work with -threaded when we want a fancy command history.
-}
-- ----------------------------------------------------------------------------
module Holumbus.Console.Console
(
-- * Console datatype
ConsoleData
-- * Operations
, nextOption
, parseOption
, initializeConsole
, addConsoleCommand
, handleUserInput
)
where
import Control.Concurrent
import qualified Data.Map as Map
import System.Console.Readline
import Holumbus.Common.Utils ( handleAll )
-- ----------------------------------------------------------------------------
-- datatypes
-- ----------------------------------------------------------------------------
-- | Map which contains all commands that the user can execute
type ConsoleData a = Map.Map String (ConsoleCommand a)
-- | Console command, only a pair of a function which will be executed
-- and a description
type ConsoleCommand a = ( Maybe (ConsoleFunction a), String )
-- | A console function. The string list represents the arguments
type ConsoleFunction a = (a -> [String] -> IO())
-- ----------------------------------------------------------------------------
-- operations
-- ----------------------------------------------------------------------------
-- | Creates a new console datatype
initializeConsole :: ConsoleData a
initializeConsole = Map.fromList [(exitString, exitCommand), (helpString, helpCommand)]
-- | Adds a new console command to the function, an existing command with the
-- same name will be overwritten
addConsoleCommand
:: String -- ^ command string (the word the user has to enter when he wants to execute the command)
-> ConsoleFunction a -- ^ the function which should be executed
-> String -- ^ the function description
-> ConsoleData a -- ^ the old console data
-> ConsoleData a
addConsoleCommand c f d m = Map.insert c (Just f, d) m
-- | The exit function string.
exitString :: String
exitString = "exit"
-- | A dummy exit function (Just to print the help description, the command
-- is handled in the main loop.
exitCommand :: ConsoleCommand a
exitCommand = ( Nothing, "exit the console")
-- | The help function string.
helpString :: String
helpString = "help"
-- | A dummy help function (Just to print the help description, the command
-- is handled in the main loop.
helpCommand :: ConsoleCommand a
helpCommand = (Nothing, "print this help")
-- | The command-line prompt string.
shellString :: String
shellString = "command> "
-- | gets the next option from the command line as string
nextOption :: [String] -> IO (Maybe String, [String])
nextOption o
= handleAll (\_ -> return (Nothing, o)) $
do
if ( null o ) then
return (Nothing, o)
else
return (Just $ head o, tail o)
-- | Simple "parser" for the commandline...
parseOption :: Read a => [String] -> IO (Maybe a, [String])
parseOption o
= handleAll (\_ -> return (Nothing, o)) $
do
if ( null o ) then
return (Nothing, o)
else
return (Just $ read $ head o, tail o)
| Reads the input from the stdin .
getCommandLine :: IO (String)
getCommandLine
-- no commandline history
= do
putStr shellString
hFlush stdout
maybeLine < - getLine --readline shellString
return maybeLine
putStr shellString
hFlush stdout
maybeLine <- getLine --readline shellString
return maybeLine
-}
-- with commandline history, please use -threaded option
= do
maybeLine <- readline shellString
yield
case maybeLine of
EOF / control - d
Just line ->
do
if (not $ null line) then do addHistory line else return ()
return line
| The main loop . You know ... read stdin , parse the input , execute command .
-- You can quit it by the exit-command.
handleUserInput :: ConsoleData a -> a -> IO ()
handleUserInput cdata conf
= do
line <- getCommandLine
input <- return (words line)
cmd <- return (command input)
args <- return (arguments input)
if (cmd == exitString)
then do
return ()
else do
if (not $ null cmd) then do handleCommand cdata conf cmd args else return ()
handleUserInput cdata conf
where
command s = if (not $ null s) then head s else ""
arguments s = tail s
-- | Picks the command an execute the command function.
handleCommand :: ConsoleData a -> a -> String -> [String] -> IO ()
handleCommand cdata conf cmd args
= do
if (cmd == helpString)
then do
printHelp cdata
else do
handleCommand' (Map.lookup cmd cdata)
where
handleCommand' Nothing = do printError
handleCommand' (Just (Nothing, _ )) = do printNoHandler
handleCommand' (Just (Just f, _ )) = do f conf args
-- | Is executed when the function has no handler
printNoHandler :: IO ()
printNoHandler
= do
putStrLn "no function handler found"
-- | Prints the "command-not-found" message.
printError :: IO ()
printError
= do
putStrLn "unknown command, try help for a list of available commands"
-- | Prints the help text.
printHelp :: ConsoleData a -> IO ()
printHelp cdata
= do
putStrLn "available Commands:"
printCommands (Map.toAscList cdata)
where
printCommands [] = do return ()
printCommands (x:xs) = do
printCommand x
printCommands xs
printCommand (c, (_, t)) = do
putStrLn ((prettyCommandName 15 c) ++ " - " ++ t)
-- | Does some pretty printing for the function descriptions
prettyCommandName :: Int -> String -> String
prettyCommandName n s
| n <= 0 = s
| (n > 0) && (null s) = ' ' : prettyCommandName (n-1) s
| otherwise = x : prettyCommandName (n-1) xs
where
(x:xs) = s
| null | https://raw.githubusercontent.com/fortytools/holumbus/4b2f7b832feab2715a4d48be0b07dca018eaa8e8/distribution/source/Holumbus/Console/Console.hs | haskell | ----------------------------------------------------------------------------
----------------------------------------------------------------------------
* Console datatype
* Operations
----------------------------------------------------------------------------
datatypes
----------------------------------------------------------------------------
| Map which contains all commands that the user can execute
| Console command, only a pair of a function which will be executed
and a description
| A console function. The string list represents the arguments
----------------------------------------------------------------------------
operations
----------------------------------------------------------------------------
| Creates a new console datatype
| Adds a new console command to the function, an existing command with the
same name will be overwritten
^ command string (the word the user has to enter when he wants to execute the command)
^ the function which should be executed
^ the function description
^ the old console data
| The exit function string.
| A dummy exit function (Just to print the help description, the command
is handled in the main loop.
| The help function string.
| A dummy help function (Just to print the help description, the command
is handled in the main loop.
| The command-line prompt string.
| gets the next option from the command line as string
| Simple "parser" for the commandline...
no commandline history
readline shellString
readline shellString
with commandline history, please use -threaded option
You can quit it by the exit-command.
| Picks the command an execute the command function.
| Is executed when the function has no handler
| Prints the "command-not-found" message.
| Prints the help text.
| Does some pretty printing for the function descriptions |
|
Module : Holumbus . Console . Console
Copyright : Copyright ( C ) 2008
License : MIT
Maintainer : ( )
Stability : experimental
Portability : portable
Version : 0.1
This module provides a tiny and nice implementation of a little command
shell . It can be feed with individual commands and provides a simple but
powerful way to interact with your program . The following functions are
implemented by default :
exit - exit the console loop
help - print a nice help
There was a little " bug " with the System . Console . Readline package . When
we use this option , we make a foreign call ... and the library
documentation say this about concurrency and GHC :
" If you do n't use the -threaded option , then the runtime does not make
use of multiple OS threads . Foreign calls will block all other running
Haskell threads until the call returns .
The System . IO library still does multiplexing , so there can be multiple
threads doing IO , and this is handled internally by the runtime using
select . "
We make a foreign call , which is not in the System . IO library , so we
have to work with -threaded when we want a fancy command history .
Module : Holumbus.Console.Console
Copyright : Copyright (C) 2008 Stefan Schmidt
License : MIT
Maintainer : Stefan Schmidt ()
Stability : experimental
Portability: portable
Version : 0.1
This module provides a tiny and nice implementation of a little command
shell. It can be feed with individual commands and provides a simple but
powerful way to interact with your program. The following functions are
implemented by default:
exit - exit the console loop
help - print a nice help
There was a little "bug" with the System.Console.Readline package. When
we use this option, we make a foreign call... and the Haskell library
documentation say this about concurrency and GHC:
"If you don't use the -threaded option, then the runtime does not make
use of multiple OS threads. Foreign calls will block all other running
Haskell threads until the call returns.
The System.IO library still does multiplexing, so there can be multiple
threads doing IO, and this is handled internally by the runtime using
select."
We make a foreign call, which is not in the System.IO library, so we
have to work with -threaded when we want a fancy command history.
-}
module Holumbus.Console.Console
(
ConsoleData
, nextOption
, parseOption
, initializeConsole
, addConsoleCommand
, handleUserInput
)
where
import Control.Concurrent
import qualified Data.Map as Map
import System.Console.Readline
import Holumbus.Common.Utils ( handleAll )
type ConsoleData a = Map.Map String (ConsoleCommand a)
type ConsoleCommand a = ( Maybe (ConsoleFunction a), String )
type ConsoleFunction a = (a -> [String] -> IO())
initializeConsole :: ConsoleData a
initializeConsole = Map.fromList [(exitString, exitCommand), (helpString, helpCommand)]
addConsoleCommand
-> ConsoleData a
addConsoleCommand c f d m = Map.insert c (Just f, d) m
exitString :: String
exitString = "exit"
exitCommand :: ConsoleCommand a
exitCommand = ( Nothing, "exit the console")
helpString :: String
helpString = "help"
helpCommand :: ConsoleCommand a
helpCommand = (Nothing, "print this help")
shellString :: String
shellString = "command> "
nextOption :: [String] -> IO (Maybe String, [String])
nextOption o
= handleAll (\_ -> return (Nothing, o)) $
do
if ( null o ) then
return (Nothing, o)
else
return (Just $ head o, tail o)
parseOption :: Read a => [String] -> IO (Maybe a, [String])
parseOption o
= handleAll (\_ -> return (Nothing, o)) $
do
if ( null o ) then
return (Nothing, o)
else
return (Just $ read $ head o, tail o)
| Reads the input from the stdin .
getCommandLine :: IO (String)
getCommandLine
= do
putStr shellString
hFlush stdout
return maybeLine
putStr shellString
hFlush stdout
return maybeLine
-}
= do
maybeLine <- readline shellString
yield
case maybeLine of
EOF / control - d
Just line ->
do
if (not $ null line) then do addHistory line else return ()
return line
| The main loop . You know ... read stdin , parse the input , execute command .
handleUserInput :: ConsoleData a -> a -> IO ()
handleUserInput cdata conf
= do
line <- getCommandLine
input <- return (words line)
cmd <- return (command input)
args <- return (arguments input)
if (cmd == exitString)
then do
return ()
else do
if (not $ null cmd) then do handleCommand cdata conf cmd args else return ()
handleUserInput cdata conf
where
command s = if (not $ null s) then head s else ""
arguments s = tail s
handleCommand :: ConsoleData a -> a -> String -> [String] -> IO ()
handleCommand cdata conf cmd args
= do
if (cmd == helpString)
then do
printHelp cdata
else do
handleCommand' (Map.lookup cmd cdata)
where
handleCommand' Nothing = do printError
handleCommand' (Just (Nothing, _ )) = do printNoHandler
handleCommand' (Just (Just f, _ )) = do f conf args
printNoHandler :: IO ()
printNoHandler
= do
putStrLn "no function handler found"
printError :: IO ()
printError
= do
putStrLn "unknown command, try help for a list of available commands"
printHelp :: ConsoleData a -> IO ()
printHelp cdata
= do
putStrLn "available Commands:"
printCommands (Map.toAscList cdata)
where
printCommands [] = do return ()
printCommands (x:xs) = do
printCommand x
printCommands xs
printCommand (c, (_, t)) = do
putStrLn ((prettyCommandName 15 c) ++ " - " ++ t)
prettyCommandName :: Int -> String -> String
prettyCommandName n s
| n <= 0 = s
| (n > 0) && (null s) = ' ' : prettyCommandName (n-1) s
| otherwise = x : prettyCommandName (n-1) xs
where
(x:xs) = s
|
bf39de71cab4b76bfff82628b2e21ddaac70288937106488983c3dc857548e98 | bbarker/timekeeping-template | hledger-time-report.hs | #!/usr/bin/env stack
stack script --nix --resolver lts-15.12
--nix - packages pcre
--no - nix - pure
--package conduit
--package containers
--package csv - conduit
--package non - empty - text
--package optparse - generic
--package pcre - heavy
--package safe
--package text
--package time
--package transformers
--package turtle
--package unexceptionalio - trans
--extra - dep unexceptionalio-0.5.1
--ghc - options -Wall
--nix-packages pcre
--no-nix-pure
--package conduit
--package containers
--package csv-conduit
--package non-empty-text
--package optparse-generic
--package pcre-heavy
--package safe
--package text
--package time
--package transformers
--package turtle
--package unexceptionalio-trans
--extra-dep unexceptionalio-0.5.1
--ghc-options -Wall
-}
-- Use --verbose above for better error messages for library build failures
{-# LANGUAGE DeriveGeneric #-}
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
for pcre - heavy
module Main where
import Prelude hiding (error)
import Conduit
import Control.Monad (forM)
import Control.Monad.Trans.Except (ExceptT(..), except, runExceptT)
import Data.Bifunctor
import qualified Data.Conduit.List as CL
import Data.CSV.Conduit
import Data.Maybe
import qualified Data.Map.Strict as DM
import qualified Data.NonEmptyText as DTNE
import Data.List (isSubsequenceOf)
import qualified Data.Set as DS
import qualified Data.Text as DT
import qualified Data.Text.Lazy as DTL
import qualified Data.Text.IO as DTIO
import Data.Time.Clock
import Data.Time.Calendar
import Options.Generic
import Safe (lastMay)
import qualified Text.Read as TR
import Text.Regex.PCRE.Heavy
import Turtle
import UnexceptionalIO.Trans (UIO, fromIO, run)
active_cac_entries :: Text
active_cac_entries = "ACTIVE_CAC_ENTRIES"
active_cac_projects :: Text
active_cac_projects = "ACTIVE_CAC_PROJECTS"
billPfx :: Text
billPfx = "Billed"
projPfx :: Text
projPfx = "project"
notProjPfx :: Text
notProjPfx = "unbilled"
unbillPfx :: Text
unbillPfx = "ReportNotBilled"
acctIndent :: Text
acctIndent = " "
notReportEntry :: Text
notReportEntry = " not:acct:Report"
data ReportOpts = ReportOpts {start :: Text, end :: Text}
deriving (Generic, Show)
instance ParseRecord ReportOpts
type EitherIO a = ExceptT String UIO a
main :: IO ()
main = (either putStrLn pure) =<< ((run . runExceptT) script)
eToStr :: (Show e, Bifunctor p) => p e a -> p String a
eToStr pea = first show pea
ulift :: IO a -> EitherIO a
ulift ioa = except =<< (eToStr <$> (runExceptT $ fromIO ioa))
printLn :: String -> EitherIO ()
printLn = ulift . putStrLn
script :: EitherIO ()
script = do
dateNow <- getDateNow
opts :: ReportOpts <- ulift $ getRecord "hledger time report"
repRange@(fromDay, untilDay) <- except $ dateRange dateNow (start opts) (end opts)
journalFileMay <- ulift $ need "LEDGER_FILE"
journalFile <- pure $ case journalFileMay of
Just jf -> DT.unpack jf
Nothing -> "report.journal"
entryKeys <- getEnvList active_cac_entries
projs <- getEnvList active_cac_projects
_ <- except $ entryNameCheck entryKeys
let entryKeySet = DS.fromList entryKeys
let projSet = DS.fromList projs
let unbilledKeySet = entryKeySet `DS.difference` projSet
_ <- except $ assertOrErr (projSet `DS.isProperSubsetOf` entryKeySet)
"Project set is not a subset of entry set"
estDescrMap <- DM.fromList <$>
((zip entryKeys) <$> (sequence $ (projectReport repRange) <$> entryKeys))
let estMap = DM.map fst estDescrMap
let descrMap = DM.map snd estDescrMap
projBals :: [Double] <- sequence $ (projectBalance untilDay) <$> entryKeys
let balMap = DM.fromList $ zip entryKeys projBals
let billMap = DM.map floor $ DM.restrictKeys balMap projSet
let unbillMap = DM.restrictKeys balMap unbilledKeySet
let reportValMap = DM.union (DM.map fromIntegral billMap) unbillMap
_ <- except $ sequence $ projs <&> (\ek -> do
valueCheck ek estMap billMap
)
linesOut :: [Text] <- pure $ catMaybes $ entryKeys <&> (\ek -> do
hours <- DM.lookup ek reportValMap
descr <- DM.lookup ek descrMap
if hours > 0 then Just $
(dQ ek) <> ","
<> (dQ $ tshow hours) <> ","
<> (dQ descr)
else Nothing
)
_ <- ulift $ forM linesOut DTIO.putStrLn
billEntriesMay <- except $ sequence $
(billEntry fromDay reportValMap projSet descrMap) <$> entryKeys
billEntries <- pure $ catMaybes $ billEntriesMay
ulift $ DTIO.appendFile journalFile $ "\n\n; Adding billing entry on "
<> dateToTxt dateNow <> "\n\n"
_ <- ulift $ forM billEntries (\entry -> DTIO.appendFile journalFile entry)
pure ()
where
valueCheck :: Text -> DM.Map Text Double -> DM.Map Text Int -> Either String ()
valueCheck eKey m1 m2 = do
est <- getEst
bill <- getBill
assertOrErr (bill < 0 || est <= bill) (msg est bill)
where
msg est bill = "weekly hours estimate " <> show est
<> " is not <= to bill " <> show bill <> " for " <> DT.unpack eKey
getEst = case DM.lookup eKey m1 of
Just b -> Right $ floor b
Nothing -> Left $ "couldn't lookup est for "
<> DT.unpack eKey <> " in valueNotGE: " <> show m1
getBill = case DM.lookup eKey m2 of
Just b -> Right b
Nothing -> Left $ "couldn't lookup bill for "
<> DT.unpack eKey <> " in valueNotGE: " <> show m2
absolveUnits :: f () -> ()
absolveUnits _ = ()
This does n't need to be IO , but am using for debugging
entryNameCheck :: [Text] -> Either String ()
entryNameCheck eNames = absolveUnits <$> (sequence $ checkPair <$> namePairs)
where
lStr = DT.unpack . DT.toLower
namePairs = [(lStr i, lStr j) | i <- eNames, j <- eNames]
errmsg ns = "!! " <> fst ns <> " is a substring of " <> snd ns
checkPair p = assertOrErr ((fst p == snd p) || (not $ isSubsequenceOf (fst p) (snd p))) (errmsg p)
debugCheck :: [Text] -> [(String, String)]
debugCheck eNames = namePairs
where
lStr = DT.unpack . DT.toLower
namePairs = [(lStr i,lStr j) | i <- eNames, j <- eNames, i /= j]
projectReport :: (Text, Text) -> Text -> EitherIO (Double, Text)
projectReport (fromDay, untilDay) projKey = do
-- putStrLn $ "<< " <> DT.unpack projKey <> " >>" -- DEBUG
let regCmd = "hledger print -b " <> fromDay <> " -e " <> untilDay <> notReportEntry
<> " | hledger register -f- " <> projKey <> " -O csv"
(_, regOut) <- ulift $ shellStrict regCmd empty
let regLines = DT.lines regOut
weeklyEst <- except $ getWeeklyEst regLines
projNotes :: [Text] <- ulift $ runConduitRes $ sourceLazy (DTL.fromStrict regOut)
.| intoCSV defCSVSettings .| regProcessor .| sinkList
let projNotesProcessed = DT.dropWhileEnd (=='.') <$> DT.strip <$> projNotes
let projNotesUniq = removeTags <$> (DS.toList . DS.fromList) projNotesProcessed
let projReport =
let projRep = (DT.intercalate ". " projNotesUniq) in
if DT.length projRep == 0 then "" else projRep <> "."
pure (weeklyEst, stripExtraPunct projReport)
projectBalance :: Text -> Text -> EitherIO Double
projectBalance untilDay projKey = do
balCmd <- pure $
"hledger print -e " <> untilDay
<> " | hledger -f- b -N --depth 2 --format \"%(total)\" " <> projKey
(_, balOut) <- ulift $ shellStrict balCmd empty
let balLines = DT.strip <$> DT.lines balOut
let subProjBals = readBal <$> balLines
projBal <- except $ (eitherReduce sum) subProjBals
-- putStrLn $ "Balance for " <> DT.unpack projKey -- DEBUG
-- <> " is " <> show projBal -- DEBUG
when (projBal < 0) $ printLn $ (DT.unpack projKey)
<> " has negative balance " <> show projBal
pure projBal
where
readBal :: Text -> Either String Double
readBal balTxt = case readMay $ stripHour balTxt of
Just bal -> Right bal
Nothing -> Left $ "Couldn't read balance from: " <> DT.unpack balTxt
<> " for project " <> DT.unpack projKey
removeTags :: Text -> Text
removeTags descr = gsub [re|(\s*[A-Za-z0-9_-]+:.*?(,|$))|] ("" :: Text) descr
stripExtraPunct :: Text -> Text
stripExtraPunct descr = gsub [re|(\.+)|] ("." :: Text) descr
-- Processes each description
regProcessor :: Monad m => ConduitT (MapRow Text) Text m ()
regProcessor = mapC (DM.lookup $ DT.pack "description") .| CL.catMaybes
.| mapC DTNE.fromText .| CL.catMaybes .| mapC DTNE.toText
-- TODO: use this as a sanity check
getWeeklyEst :: [Text] -> Either String Double
getWeeklyEst (_:[]) = Right 0.0
getWeeklyEst (_:lns) = case lastMay lns of
Just line -> case join $ lastMay <$> DT.split (==',') <$> lastMay lns of
Just txt ->
let numTxt = stripHour $ DT.dropAround (=='"') txt in
case readMay numTxt of
Just dv -> Right dv
Nothing -> Left $ "numTxt '" <> DT.unpack numTxt
<> "' not a Double while in getWeeklyEst on line:"
<> DT.unpack line
Nothing -> Left $ "empty string detected for weekly estimate"
Nothing -> Right 0.0
getWeeklyEst [] = Right 0.0
billEntry :: Text -> DM.Map Text Double -> DS.Set Text -> DM.Map Text Text -> Text
-> Either String (Maybe Text)
billEntry repDay bMap projSet dMap eKey = do
bAmnt <- bAmntEi
billLine <- pure $ acctIndent <> consumePfx <> (DT.replicate defSpaces " ")
<> tshow bAmnt <> " h"
projLine <- pure $ acctIndent <> projPfx'' <> (DT.replicate projSpaces " ") <> "-"
<> tshow bAmnt <> " h"
pure $ if bAmnt > 0 then Just $
"\n" <> (DT.intercalate "\n" [dateLine, billLine, projLine]) <> "\n"
else Nothing
where
bAmntEi = case DM.lookup eKey bMap of
Just bAmt -> Right bAmt
Nothing -> Left $ "No bill amount for: " <> DT.unpack eKey <> " in billEntry"
defSpaces = 25
descr = DM.findWithDefault "" eKey dMap
dateLine = repDay <> (if DT.length descr > 0 then " " <> descr else "")
(consumePfx, consumeLen) = getRecInfo
projPfx' = case DS.member eKey projSet of
True -> projPfx
False -> notProjPfx
projPfx'' = projPfx' <> ":" <> eKey
projSpaces = max 1 $ consumeLen - (DT.length projPfx'') - 1
getRecInfo :: (Text, Int)
getRecInfo = case DS.member eKey projSet of
True -> (billPfx, defSpaces + (DT.length billPfx))
False -> (unbillPfx, defSpaces + (DT.length unbillPfx))
stripHour :: Text -> Text
stripHour txt = DT.takeWhile (/=' ') txt
readMay :: Read a => Text -> Maybe a
readMay = TR.readMaybe . DT.unpack
tshow :: Show a => a -> Text
tshow = DT.pack . show
dQ :: Text -> Text
dQ txt = "\"" <> txt <> "\""
assertOrErr :: Bool -> String -> Either String ()
assertOrErr cond msg = if cond then Right () else Left msg
safeIx :: Text -> Int -> Maybe Char
safeIx txt ix =
if ix < DT.length txt then Just $ DT.index txt ix
else Nothing
getDateNow :: EitherIO (Integer, Int, Int) -- :: (year,month,day)
getDateNow = ulift $ getCurrentTime >>= return . toGregorian . utctDay
dateToTxt :: (Integer, Int, Int) -> Text
dateToTxt (year,month,day) =
tshow year <> "/" <> tshow month <> "/" <> tshow day
dateYear :: (Integer, Int, Int) -> Integer
dateYear (year,_,_) = year
today :: (Integer, Int, Int) -> Text
today (year,month,day) = DT.intercalate "/"
[tshow year, tshow month, tshow day]
dateRange :: (Integer, Int, Int) -> Text -> Text -> Either String (Text, Text)
dateRange dte fromDay untilDay = do
fromTxt <- processDate fromDay
untilTxt <- processDate untilDay
Right (fromTxt, untilTxt)
where
processDate :: Text -> Either String Text
processDate dTxt = dTxt'
where
dTxtLen = partCount dTxt
dTxt' = if dTxtLen == 2 then Right $ prependYear dTxt
else if dTxtLen == 3 then Right dTxt
else Left $ "invalid date format: " <> DT.unpack dTxt
partCount txt = length $ filter (\dt -> DT.length dt > 0) $ DT.split (=='/') txt
prependYear :: Text -> Text
prependYear moDay = (tshow $ dateYear dte) <> "/" <> moDay
getEnvList :: Text -> EitherIO [Text]
getEnvList varName = do
varMay <- ulift $ need varName
except $ case varMay of
Just eks -> Right $ filter (\t -> DT.length t > 0) $ DT.split (==' ') eks
Nothing -> Left $ DT.unpack varName <> " not set or exported"
eitherReduce :: Traversable t => (t a -> a) -> t (Either String a) -> Either String a
eitherReduce ffun es = (second ffun) . sequence $ es | null | https://raw.githubusercontent.com/bbarker/timekeeping-template/fb0969374be8495ef1a0bca22bf1180839aeb8f2/hledger-time-report.hs | haskell | nix --resolver lts-15.12
nix - packages pcre
no - nix - pure
package conduit
package containers
package csv - conduit
package non - empty - text
package optparse - generic
package pcre - heavy
package safe
package text
package time
package transformers
package turtle
package unexceptionalio - trans
extra - dep unexceptionalio-0.5.1
ghc - options -Wall
nix-packages pcre
no-nix-pure
package conduit
package containers
package csv-conduit
package non-empty-text
package optparse-generic
package pcre-heavy
package safe
package text
package time
package transformers
package turtle
package unexceptionalio-trans
extra-dep unexceptionalio-0.5.1
ghc-options -Wall
Use --verbose above for better error messages for library build failures
# LANGUAGE DeriveGeneric #
# LANGUAGE OverloadedStrings #
# LANGUAGE ScopedTypeVariables #
putStrLn $ "<< " <> DT.unpack projKey <> " >>" -- DEBUG
putStrLn $ "Balance for " <> DT.unpack projKey -- DEBUG
<> " is " <> show projBal -- DEBUG
Processes each description
TODO: use this as a sanity check
:: (year,month,day) | #!/usr/bin/env stack
-}
# LANGUAGE GeneralizedNewtypeDeriving #
for pcre - heavy
module Main where
import Prelude hiding (error)
import Conduit
import Control.Monad (forM)
import Control.Monad.Trans.Except (ExceptT(..), except, runExceptT)
import Data.Bifunctor
import qualified Data.Conduit.List as CL
import Data.CSV.Conduit
import Data.Maybe
import qualified Data.Map.Strict as DM
import qualified Data.NonEmptyText as DTNE
import Data.List (isSubsequenceOf)
import qualified Data.Set as DS
import qualified Data.Text as DT
import qualified Data.Text.Lazy as DTL
import qualified Data.Text.IO as DTIO
import Data.Time.Clock
import Data.Time.Calendar
import Options.Generic
import Safe (lastMay)
import qualified Text.Read as TR
import Text.Regex.PCRE.Heavy
import Turtle
import UnexceptionalIO.Trans (UIO, fromIO, run)
active_cac_entries :: Text
active_cac_entries = "ACTIVE_CAC_ENTRIES"
active_cac_projects :: Text
active_cac_projects = "ACTIVE_CAC_PROJECTS"
billPfx :: Text
billPfx = "Billed"
projPfx :: Text
projPfx = "project"
notProjPfx :: Text
notProjPfx = "unbilled"
unbillPfx :: Text
unbillPfx = "ReportNotBilled"
acctIndent :: Text
acctIndent = " "
notReportEntry :: Text
notReportEntry = " not:acct:Report"
data ReportOpts = ReportOpts {start :: Text, end :: Text}
deriving (Generic, Show)
instance ParseRecord ReportOpts
type EitherIO a = ExceptT String UIO a
main :: IO ()
main = (either putStrLn pure) =<< ((run . runExceptT) script)
eToStr :: (Show e, Bifunctor p) => p e a -> p String a
eToStr pea = first show pea
ulift :: IO a -> EitherIO a
ulift ioa = except =<< (eToStr <$> (runExceptT $ fromIO ioa))
printLn :: String -> EitherIO ()
printLn = ulift . putStrLn
script :: EitherIO ()
script = do
dateNow <- getDateNow
opts :: ReportOpts <- ulift $ getRecord "hledger time report"
repRange@(fromDay, untilDay) <- except $ dateRange dateNow (start opts) (end opts)
journalFileMay <- ulift $ need "LEDGER_FILE"
journalFile <- pure $ case journalFileMay of
Just jf -> DT.unpack jf
Nothing -> "report.journal"
entryKeys <- getEnvList active_cac_entries
projs <- getEnvList active_cac_projects
_ <- except $ entryNameCheck entryKeys
let entryKeySet = DS.fromList entryKeys
let projSet = DS.fromList projs
let unbilledKeySet = entryKeySet `DS.difference` projSet
_ <- except $ assertOrErr (projSet `DS.isProperSubsetOf` entryKeySet)
"Project set is not a subset of entry set"
estDescrMap <- DM.fromList <$>
((zip entryKeys) <$> (sequence $ (projectReport repRange) <$> entryKeys))
let estMap = DM.map fst estDescrMap
let descrMap = DM.map snd estDescrMap
projBals :: [Double] <- sequence $ (projectBalance untilDay) <$> entryKeys
let balMap = DM.fromList $ zip entryKeys projBals
let billMap = DM.map floor $ DM.restrictKeys balMap projSet
let unbillMap = DM.restrictKeys balMap unbilledKeySet
let reportValMap = DM.union (DM.map fromIntegral billMap) unbillMap
_ <- except $ sequence $ projs <&> (\ek -> do
valueCheck ek estMap billMap
)
linesOut :: [Text] <- pure $ catMaybes $ entryKeys <&> (\ek -> do
hours <- DM.lookup ek reportValMap
descr <- DM.lookup ek descrMap
if hours > 0 then Just $
(dQ ek) <> ","
<> (dQ $ tshow hours) <> ","
<> (dQ descr)
else Nothing
)
_ <- ulift $ forM linesOut DTIO.putStrLn
billEntriesMay <- except $ sequence $
(billEntry fromDay reportValMap projSet descrMap) <$> entryKeys
billEntries <- pure $ catMaybes $ billEntriesMay
ulift $ DTIO.appendFile journalFile $ "\n\n; Adding billing entry on "
<> dateToTxt dateNow <> "\n\n"
_ <- ulift $ forM billEntries (\entry -> DTIO.appendFile journalFile entry)
pure ()
where
valueCheck :: Text -> DM.Map Text Double -> DM.Map Text Int -> Either String ()
valueCheck eKey m1 m2 = do
est <- getEst
bill <- getBill
assertOrErr (bill < 0 || est <= bill) (msg est bill)
where
msg est bill = "weekly hours estimate " <> show est
<> " is not <= to bill " <> show bill <> " for " <> DT.unpack eKey
getEst = case DM.lookup eKey m1 of
Just b -> Right $ floor b
Nothing -> Left $ "couldn't lookup est for "
<> DT.unpack eKey <> " in valueNotGE: " <> show m1
getBill = case DM.lookup eKey m2 of
Just b -> Right b
Nothing -> Left $ "couldn't lookup bill for "
<> DT.unpack eKey <> " in valueNotGE: " <> show m2
absolveUnits :: f () -> ()
absolveUnits _ = ()
This does n't need to be IO , but am using for debugging
entryNameCheck :: [Text] -> Either String ()
entryNameCheck eNames = absolveUnits <$> (sequence $ checkPair <$> namePairs)
where
lStr = DT.unpack . DT.toLower
namePairs = [(lStr i, lStr j) | i <- eNames, j <- eNames]
errmsg ns = "!! " <> fst ns <> " is a substring of " <> snd ns
checkPair p = assertOrErr ((fst p == snd p) || (not $ isSubsequenceOf (fst p) (snd p))) (errmsg p)
debugCheck :: [Text] -> [(String, String)]
debugCheck eNames = namePairs
where
lStr = DT.unpack . DT.toLower
namePairs = [(lStr i,lStr j) | i <- eNames, j <- eNames, i /= j]
projectReport :: (Text, Text) -> Text -> EitherIO (Double, Text)
projectReport (fromDay, untilDay) projKey = do
let regCmd = "hledger print -b " <> fromDay <> " -e " <> untilDay <> notReportEntry
<> " | hledger register -f- " <> projKey <> " -O csv"
(_, regOut) <- ulift $ shellStrict regCmd empty
let regLines = DT.lines regOut
weeklyEst <- except $ getWeeklyEst regLines
projNotes :: [Text] <- ulift $ runConduitRes $ sourceLazy (DTL.fromStrict regOut)
.| intoCSV defCSVSettings .| regProcessor .| sinkList
let projNotesProcessed = DT.dropWhileEnd (=='.') <$> DT.strip <$> projNotes
let projNotesUniq = removeTags <$> (DS.toList . DS.fromList) projNotesProcessed
let projReport =
let projRep = (DT.intercalate ". " projNotesUniq) in
if DT.length projRep == 0 then "" else projRep <> "."
pure (weeklyEst, stripExtraPunct projReport)
projectBalance :: Text -> Text -> EitherIO Double
projectBalance untilDay projKey = do
balCmd <- pure $
"hledger print -e " <> untilDay
<> " | hledger -f- b -N --depth 2 --format \"%(total)\" " <> projKey
(_, balOut) <- ulift $ shellStrict balCmd empty
let balLines = DT.strip <$> DT.lines balOut
let subProjBals = readBal <$> balLines
projBal <- except $ (eitherReduce sum) subProjBals
when (projBal < 0) $ printLn $ (DT.unpack projKey)
<> " has negative balance " <> show projBal
pure projBal
where
readBal :: Text -> Either String Double
readBal balTxt = case readMay $ stripHour balTxt of
Just bal -> Right bal
Nothing -> Left $ "Couldn't read balance from: " <> DT.unpack balTxt
<> " for project " <> DT.unpack projKey
removeTags :: Text -> Text
removeTags descr = gsub [re|(\s*[A-Za-z0-9_-]+:.*?(,|$))|] ("" :: Text) descr
stripExtraPunct :: Text -> Text
stripExtraPunct descr = gsub [re|(\.+)|] ("." :: Text) descr
regProcessor :: Monad m => ConduitT (MapRow Text) Text m ()
regProcessor = mapC (DM.lookup $ DT.pack "description") .| CL.catMaybes
.| mapC DTNE.fromText .| CL.catMaybes .| mapC DTNE.toText
getWeeklyEst :: [Text] -> Either String Double
getWeeklyEst (_:[]) = Right 0.0
getWeeklyEst (_:lns) = case lastMay lns of
Just line -> case join $ lastMay <$> DT.split (==',') <$> lastMay lns of
Just txt ->
let numTxt = stripHour $ DT.dropAround (=='"') txt in
case readMay numTxt of
Just dv -> Right dv
Nothing -> Left $ "numTxt '" <> DT.unpack numTxt
<> "' not a Double while in getWeeklyEst on line:"
<> DT.unpack line
Nothing -> Left $ "empty string detected for weekly estimate"
Nothing -> Right 0.0
getWeeklyEst [] = Right 0.0
billEntry :: Text -> DM.Map Text Double -> DS.Set Text -> DM.Map Text Text -> Text
-> Either String (Maybe Text)
billEntry repDay bMap projSet dMap eKey = do
bAmnt <- bAmntEi
billLine <- pure $ acctIndent <> consumePfx <> (DT.replicate defSpaces " ")
<> tshow bAmnt <> " h"
projLine <- pure $ acctIndent <> projPfx'' <> (DT.replicate projSpaces " ") <> "-"
<> tshow bAmnt <> " h"
pure $ if bAmnt > 0 then Just $
"\n" <> (DT.intercalate "\n" [dateLine, billLine, projLine]) <> "\n"
else Nothing
where
bAmntEi = case DM.lookup eKey bMap of
Just bAmt -> Right bAmt
Nothing -> Left $ "No bill amount for: " <> DT.unpack eKey <> " in billEntry"
defSpaces = 25
descr = DM.findWithDefault "" eKey dMap
dateLine = repDay <> (if DT.length descr > 0 then " " <> descr else "")
(consumePfx, consumeLen) = getRecInfo
projPfx' = case DS.member eKey projSet of
True -> projPfx
False -> notProjPfx
projPfx'' = projPfx' <> ":" <> eKey
projSpaces = max 1 $ consumeLen - (DT.length projPfx'') - 1
getRecInfo :: (Text, Int)
getRecInfo = case DS.member eKey projSet of
True -> (billPfx, defSpaces + (DT.length billPfx))
False -> (unbillPfx, defSpaces + (DT.length unbillPfx))
stripHour :: Text -> Text
stripHour txt = DT.takeWhile (/=' ') txt
readMay :: Read a => Text -> Maybe a
readMay = TR.readMaybe . DT.unpack
tshow :: Show a => a -> Text
tshow = DT.pack . show
dQ :: Text -> Text
dQ txt = "\"" <> txt <> "\""
assertOrErr :: Bool -> String -> Either String ()
assertOrErr cond msg = if cond then Right () else Left msg
safeIx :: Text -> Int -> Maybe Char
safeIx txt ix =
if ix < DT.length txt then Just $ DT.index txt ix
else Nothing
getDateNow = ulift $ getCurrentTime >>= return . toGregorian . utctDay
dateToTxt :: (Integer, Int, Int) -> Text
dateToTxt (year,month,day) =
tshow year <> "/" <> tshow month <> "/" <> tshow day
dateYear :: (Integer, Int, Int) -> Integer
dateYear (year,_,_) = year
today :: (Integer, Int, Int) -> Text
today (year,month,day) = DT.intercalate "/"
[tshow year, tshow month, tshow day]
dateRange :: (Integer, Int, Int) -> Text -> Text -> Either String (Text, Text)
dateRange dte fromDay untilDay = do
fromTxt <- processDate fromDay
untilTxt <- processDate untilDay
Right (fromTxt, untilTxt)
where
processDate :: Text -> Either String Text
processDate dTxt = dTxt'
where
dTxtLen = partCount dTxt
dTxt' = if dTxtLen == 2 then Right $ prependYear dTxt
else if dTxtLen == 3 then Right dTxt
else Left $ "invalid date format: " <> DT.unpack dTxt
partCount txt = length $ filter (\dt -> DT.length dt > 0) $ DT.split (=='/') txt
prependYear :: Text -> Text
prependYear moDay = (tshow $ dateYear dte) <> "/" <> moDay
getEnvList :: Text -> EitherIO [Text]
getEnvList varName = do
varMay <- ulift $ need varName
except $ case varMay of
Just eks -> Right $ filter (\t -> DT.length t > 0) $ DT.split (==' ') eks
Nothing -> Left $ DT.unpack varName <> " not set or exported"
eitherReduce :: Traversable t => (t a -> a) -> t (Either String a) -> Either String a
eitherReduce ffun es = (second ffun) . sequence $ es |
879bc5c7a69cb0d260b07b3b858361d911f9749e15102d20642eeb86759724f8 | thelema/ocaml-community | pr5757.ml | Random.init 3;;
for i = 0 to 100_000 do
ignore (String.create (Random.int 1_000_000))
done;;
Printf.printf "hello world\n";;
| null | https://raw.githubusercontent.com/thelema/ocaml-community/ed0a2424bbf13d1b33292725e089f0d7ba94b540/testsuite/tests/regression/pr5757/pr5757.ml | ocaml | Random.init 3;;
for i = 0 to 100_000 do
ignore (String.create (Random.int 1_000_000))
done;;
Printf.printf "hello world\n";;
|
|
a54a93ccfc717bd2b2456dc8518775cefdb8dff346fe29d91a1e49032633d4ed | kmi/irs | service-spec.lisp | Mode : Lisp ; Package :
The Open University
(in-package "OCML")
(in-ontology exchange-rate-provider-ontology)
(def-class exchange-rate-provision (goal-specification-task)?task
((has-input-role :value has-source-currency
:value has-target-currency
)
(has-output-role :value has-exchange-rate)
(has-source-currency :type currency :cardinality 1)
(has-target-currency :type currency :cardinality 1)
(has-exchange-rate :type positive-number)
(has-precondition
:value (kappa (?psm)
(and (currency (role-value ?psm has-source-currency))
(currency (role-value ?psm has-target-currency)))))
(has-goal-expression
:value (kappa (?psm ?sol)
(positive-number ?sol)))))
(cl-user::def-irs-soap-bindings exchange-rate-provider-ontology ;;this is the ontology name
exchange-rate-provision ;;this is the task name
((has-source-currency "xsd:sexpr")
(has-target-currency "xsd:sexpr")
)
"xsd:float"
)
(def-class exchange-rate-provider (primitive-method) ?psm
((has-input-role :value has-source-currency
:value has-target-currency
)
(has-output-role :value has-exchange-rate)
(has-source-currency :type currency :cardinality 1)
(has-target-currency :type currency :cardinality 1)
(has-exchange-rate :type positive-number)
(has-precondition
:value (kappa (?psm)
(and (currency (role-value ?psm has-source-currency))
(currency (role-value ?psm has-target-currency)))))
(has-postcondition
:value (kappa (?psm ?sol)
(positive-number ?sol))))
:own-slots ((tackles-task-type exchange-rate-provision)))
| null | https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/publisher/services/soap-ex-rate/service-spec.lisp | lisp | Package :
this is the ontology name
this is the task name |
The Open University
(in-package "OCML")
(in-ontology exchange-rate-provider-ontology)
(def-class exchange-rate-provision (goal-specification-task)?task
((has-input-role :value has-source-currency
:value has-target-currency
)
(has-output-role :value has-exchange-rate)
(has-source-currency :type currency :cardinality 1)
(has-target-currency :type currency :cardinality 1)
(has-exchange-rate :type positive-number)
(has-precondition
:value (kappa (?psm)
(and (currency (role-value ?psm has-source-currency))
(currency (role-value ?psm has-target-currency)))))
(has-goal-expression
:value (kappa (?psm ?sol)
(positive-number ?sol)))))
((has-source-currency "xsd:sexpr")
(has-target-currency "xsd:sexpr")
)
"xsd:float"
)
(def-class exchange-rate-provider (primitive-method) ?psm
((has-input-role :value has-source-currency
:value has-target-currency
)
(has-output-role :value has-exchange-rate)
(has-source-currency :type currency :cardinality 1)
(has-target-currency :type currency :cardinality 1)
(has-exchange-rate :type positive-number)
(has-precondition
:value (kappa (?psm)
(and (currency (role-value ?psm has-source-currency))
(currency (role-value ?psm has-target-currency)))))
(has-postcondition
:value (kappa (?psm ?sol)
(positive-number ?sol))))
:own-slots ((tackles-task-type exchange-rate-provision)))
|
8d4c03031d3d800dbd82a5111bed8eaca970f2b92e14b4c6acb4ea48c485ba6e | nikita-volkov/rerebase | Types.hs | module GHC.IO.Handle.Types
(
module Rebase.GHC.IO.Handle.Types
)
where
import Rebase.GHC.IO.Handle.Types
| null | https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/GHC/IO/Handle/Types.hs | haskell | module GHC.IO.Handle.Types
(
module Rebase.GHC.IO.Handle.Types
)
where
import Rebase.GHC.IO.Handle.Types
|
|
ca7105f04ce341b31d208ad58a5606e434b4f0193a93595cfeb6282ff0c4b322 | onedata/op-worker | transfer_links.erl | %%%-------------------------------------------------------------------
@author
( C ) 2018 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%%--------------------------------------------------------------------
%%% @doc
%%% Util functions for operating on transfer links trees.
%%% @end
%%%-------------------------------------------------------------------
-module(transfer_links).
-author("Jakub Kudzia").
-include("modules/datastore/datastore_models.hrl").
-include("modules/datastore/datastore_runner.hrl").
-include("modules/datastore/transfer.hrl").
-include_lib("cluster_worker/include/modules/datastore/datastore_links.hrl").
-include_lib("ctool/include/logging.hrl").
%% API
% link utils functions
-export([
add_waiting/1, delete_waiting/1,
add_ongoing/1, delete_ongoing/1,
add_ended/1, delete_ended/1,
move_from_ongoing_to_ended/1,
move_to_ended_if_not_migration/1
]).
-export([list/5]).
-export([link_key/2]).
-type link_key() :: binary().
? ( WAITING|ONGOING|ENDED)_TRANSFERS_KEY
-type offset() :: integer().
-type list_limit() :: transfer:list_limit().
-export_type([link_key/0]).
-define(CTX, (transfer:get_ctx())).
-define(LINK_NAME_ID_PART_LENGTH, 6).
%%%===================================================================
%%% API
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Adds given transfer to waiting transfer links tree and to
%% ongoing transfers for file (transferred_file doc).
%% @end
%%--------------------------------------------------------------------
-spec add_waiting(transfer:doc()) -> ok.
add_waiting(#document{key = TransferId, value = Transfer}) ->
SpaceId = Transfer#transfer.space_id,
ScheduleTime = Transfer#transfer.schedule_time,
case Transfer#transfer.file_uuid of
undefined ->
ok;
FileUuid ->
FileGuid = file_id:pack_guid(FileUuid, SpaceId),
transferred_file:report_transfer_start(FileGuid, TransferId, ScheduleTime)
end,
ok = add_link(?WAITING_TRANSFERS_KEY, TransferId, SpaceId, ScheduleTime).
-spec add_ongoing(transfer:doc()) -> ok.
add_ongoing(#document{key = TransferId, value = Transfer}) ->
SpaceId = Transfer#transfer.space_id,
ScheduleTime = Transfer#transfer.schedule_time,
ok = add_link(?ONGOING_TRANSFERS_KEY, TransferId, SpaceId, ScheduleTime).
%%--------------------------------------------------------------------
%% @doc
%% Adds given transfer to ended transfer links tree and removes it from
%% ongoing transfers for file (transferred_file doc).
%% @end
%%--------------------------------------------------------------------
-spec add_ended(transfer:doc()) -> ok.
add_ended(#document{key = TransferId, value = Transfer}) ->
SpaceId = Transfer#transfer.space_id,
ScheduleTime = Transfer#transfer.schedule_time,
FinishTime = Transfer#transfer.finish_time,
case Transfer#transfer.file_uuid of
undefined ->
ok;
FileUuid ->
FileGuid = file_id:pack_guid(FileUuid, SpaceId),
transferred_file:report_transfer_finish(FileGuid, TransferId, ScheduleTime, FinishTime)
end,
ok = add_link(?ENDED_TRANSFERS_KEY, TransferId, SpaceId, FinishTime).
-spec delete_waiting(transfer:doc()) -> ok.
delete_waiting(#document{key = TransferId, value = Transfer}) ->
SpaceId = Transfer#transfer.space_id,
ScheduleTime = Transfer#transfer.schedule_time,
ok = delete_links(?WAITING_TRANSFERS_KEY, TransferId, SpaceId, ScheduleTime).
-spec delete_ongoing(transfer:doc()) -> ok.
delete_ongoing(#document{key = TransferId, value = Transfer}) ->
SpaceId = Transfer#transfer.space_id,
ScheduleTime = Transfer#transfer.schedule_time,
ok = delete_links(?ONGOING_TRANSFERS_KEY, TransferId, SpaceId, ScheduleTime).
-spec delete_ended(transfer:doc()) -> ok.
delete_ended(#document{key = TransferId, value = Transfer}) ->
SpaceId = Transfer#transfer.space_id,
FinishTime = Transfer#transfer.finish_time,
ok = delete_links(?ENDED_TRANSFERS_KEY, TransferId, SpaceId, FinishTime).
-spec move_from_ongoing_to_ended(transfer:doc()) -> ok.
move_from_ongoing_to_ended(Doc) ->
add_ended(Doc),
delete_ongoing(Doc).
%%--------------------------------------------------------------------
%% @doc
%% Moves the transfer link from ongoing to ended links tree if transfer was
%% not migration.
%% @end
%%--------------------------------------------------------------------
-spec move_to_ended_if_not_migration(transfer:doc()) -> ok.
move_to_ended_if_not_migration(Doc = #document{value = Transfer}) ->
case transfer:is_migration(Transfer) of
true -> ok;
false -> move_from_ongoing_to_ended(Doc)
end.
-spec list(SpaceId :: od_space:id(), virtual_list_id(),
transfer:id() | undefined, offset(), list_limit()) -> [transfer:id()].
list(SpaceId, ListDocId, StartId, Offset, Limit) ->
Opts = #{offset => Offset},
Opts2 = case StartId of
undefined -> Opts;
_ -> Opts#{prev_link_name => StartId}
end,
Opts3 = case Limit of
all -> Opts2;
_ -> Opts2#{size => Limit}
end,
{ok, Transfers} = for_each_link(ListDocId, fun(_LinkName, TransferId, Acc) ->
[TransferId | Acc]
end, [], SpaceId, Opts3),
lists:reverse(Transfers).
-spec link_key(transfer:id(), non_neg_integer()) -> link_key().
link_key(TransferId, Timestamp) ->
TimestampPart = (integer_to_binary(?EPOCH_INFINITY - Timestamp)),
IdPart = binary:part(TransferId, 0, ?LINK_NAME_ID_PART_LENGTH),
<<TimestampPart/binary, IdPart/binary>>.
%%%===================================================================
Internal functions
%%%===================================================================
%%-------------------------------------------------------------------
@private
%% @doc
%% Returns links tree root for given space.
%% @end
%%-------------------------------------------------------------------
-spec link_root(binary(), od_space:id()) -> binary().
link_root(Prefix, SpaceId) ->
<<Prefix/binary, "_", SpaceId/binary>>.
%%--------------------------------------------------------------------
%% @doc
%% Adds link to transfer. Links are added to link tree associated with
%% given space.
Real link source_id will be obtained from link_root/2 function .
%% @end
%%--------------------------------------------------------------------
-spec add_link(SourceId :: virtual_list_id(), TransferId :: transfer:id(),
od_space:id(), transfer:timestamp()) -> ok.
add_link(SourceId, TransferId, SpaceId, Timestamp) ->
TreeId = oneprovider:get_id(),
Ctx = ?CTX#{scope => SpaceId},
Key = link_key(TransferId, Timestamp),
LinkRoot = link_root(SourceId, SpaceId),
case datastore_model:add_links(Ctx, LinkRoot, TreeId, {Key, TransferId}) of
{ok, _} ->
ok;
{error, already_exists} ->
ok
end.
%%--------------------------------------------------------------------
%% @doc
%% Removes link/links to transfer.
Real link source_id will be obtained from link_root/2 function .
%% @end
%%--------------------------------------------------------------------
-spec delete_links(SourceId :: virtual_list_id(), TransferId :: transfer:id(),
od_space:id(), transfer:timestamp()) -> ok.
delete_links(SourceId, TransferId, SpaceId, Timestamp) ->
LinkRoot = link_root(SourceId, SpaceId),
Key = link_key(TransferId, Timestamp),
case datastore_model:get_links(?CTX, LinkRoot, all, Key) of
{error, not_found} ->
ok;
{ok, Links} ->
lists:foreach(fun(#link{tree_id = ProviderId, name = LinkName}) ->
case oneprovider:is_self(ProviderId) of
true ->
ok = datastore_model:delete_links(
?CTX#{scope => SpaceId}, LinkRoot,
ProviderId, LinkName
);
false ->
ok = datastore_model:mark_links_deleted(
?CTX#{scope => SpaceId}, LinkRoot,
ProviderId, LinkName
)
end
end, Links)
end.
%%--------------------------------------------------------------------
@private
%% @doc
%% Executes callback for each transfer.
%% @end
%%--------------------------------------------------------------------
-spec for_each_link(
virtual_list_id(),
Callback :: fun((link_key(), transfer:id(), Acc0 :: term()) -> Acc :: term()),
Acc0 :: term(), od_space:id(), datastore_model:fold_opts()) ->
{ok, Acc :: term()} | {error, term()}.
for_each_link(ListDocId, Callback, Acc0, SpaceId, Options) ->
datastore_model:fold_links(?CTX, link_root(ListDocId, SpaceId), all, fun
(#link{name = Name, target = Target}, Acc) ->
{ok, Callback(Name, Target, Acc)}
end, Acc0, Options).
| null | https://raw.githubusercontent.com/onedata/op-worker/5cb17b2fbb812138b6c2750d0257a91ec9d97c6c/src/modules/transfer/transfer_links.erl | erlang | -------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Util functions for operating on transfer links trees.
@end
-------------------------------------------------------------------
API
link utils functions
===================================================================
API
===================================================================
--------------------------------------------------------------------
@doc
Adds given transfer to waiting transfer links tree and to
ongoing transfers for file (transferred_file doc).
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Adds given transfer to ended transfer links tree and removes it from
ongoing transfers for file (transferred_file doc).
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Moves the transfer link from ongoing to ended links tree if transfer was
not migration.
@end
--------------------------------------------------------------------
===================================================================
===================================================================
-------------------------------------------------------------------
@doc
Returns links tree root for given space.
@end
-------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Adds link to transfer. Links are added to link tree associated with
given space.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Removes link/links to transfer.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Executes callback for each transfer.
@end
-------------------------------------------------------------------- | @author
( C ) 2018 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
-module(transfer_links).
-author("Jakub Kudzia").
-include("modules/datastore/datastore_models.hrl").
-include("modules/datastore/datastore_runner.hrl").
-include("modules/datastore/transfer.hrl").
-include_lib("cluster_worker/include/modules/datastore/datastore_links.hrl").
-include_lib("ctool/include/logging.hrl").
-export([
add_waiting/1, delete_waiting/1,
add_ongoing/1, delete_ongoing/1,
add_ended/1, delete_ended/1,
move_from_ongoing_to_ended/1,
move_to_ended_if_not_migration/1
]).
-export([list/5]).
-export([link_key/2]).
-type link_key() :: binary().
? ( WAITING|ONGOING|ENDED)_TRANSFERS_KEY
-type offset() :: integer().
-type list_limit() :: transfer:list_limit().
-export_type([link_key/0]).
-define(CTX, (transfer:get_ctx())).
-define(LINK_NAME_ID_PART_LENGTH, 6).
-spec add_waiting(transfer:doc()) -> ok.
add_waiting(#document{key = TransferId, value = Transfer}) ->
SpaceId = Transfer#transfer.space_id,
ScheduleTime = Transfer#transfer.schedule_time,
case Transfer#transfer.file_uuid of
undefined ->
ok;
FileUuid ->
FileGuid = file_id:pack_guid(FileUuid, SpaceId),
transferred_file:report_transfer_start(FileGuid, TransferId, ScheduleTime)
end,
ok = add_link(?WAITING_TRANSFERS_KEY, TransferId, SpaceId, ScheduleTime).
-spec add_ongoing(transfer:doc()) -> ok.
add_ongoing(#document{key = TransferId, value = Transfer}) ->
SpaceId = Transfer#transfer.space_id,
ScheduleTime = Transfer#transfer.schedule_time,
ok = add_link(?ONGOING_TRANSFERS_KEY, TransferId, SpaceId, ScheduleTime).
-spec add_ended(transfer:doc()) -> ok.
add_ended(#document{key = TransferId, value = Transfer}) ->
SpaceId = Transfer#transfer.space_id,
ScheduleTime = Transfer#transfer.schedule_time,
FinishTime = Transfer#transfer.finish_time,
case Transfer#transfer.file_uuid of
undefined ->
ok;
FileUuid ->
FileGuid = file_id:pack_guid(FileUuid, SpaceId),
transferred_file:report_transfer_finish(FileGuid, TransferId, ScheduleTime, FinishTime)
end,
ok = add_link(?ENDED_TRANSFERS_KEY, TransferId, SpaceId, FinishTime).
-spec delete_waiting(transfer:doc()) -> ok.
delete_waiting(#document{key = TransferId, value = Transfer}) ->
SpaceId = Transfer#transfer.space_id,
ScheduleTime = Transfer#transfer.schedule_time,
ok = delete_links(?WAITING_TRANSFERS_KEY, TransferId, SpaceId, ScheduleTime).
-spec delete_ongoing(transfer:doc()) -> ok.
delete_ongoing(#document{key = TransferId, value = Transfer}) ->
SpaceId = Transfer#transfer.space_id,
ScheduleTime = Transfer#transfer.schedule_time,
ok = delete_links(?ONGOING_TRANSFERS_KEY, TransferId, SpaceId, ScheduleTime).
-spec delete_ended(transfer:doc()) -> ok.
delete_ended(#document{key = TransferId, value = Transfer}) ->
SpaceId = Transfer#transfer.space_id,
FinishTime = Transfer#transfer.finish_time,
ok = delete_links(?ENDED_TRANSFERS_KEY, TransferId, SpaceId, FinishTime).
-spec move_from_ongoing_to_ended(transfer:doc()) -> ok.
move_from_ongoing_to_ended(Doc) ->
add_ended(Doc),
delete_ongoing(Doc).
-spec move_to_ended_if_not_migration(transfer:doc()) -> ok.
move_to_ended_if_not_migration(Doc = #document{value = Transfer}) ->
case transfer:is_migration(Transfer) of
true -> ok;
false -> move_from_ongoing_to_ended(Doc)
end.
-spec list(SpaceId :: od_space:id(), virtual_list_id(),
transfer:id() | undefined, offset(), list_limit()) -> [transfer:id()].
list(SpaceId, ListDocId, StartId, Offset, Limit) ->
Opts = #{offset => Offset},
Opts2 = case StartId of
undefined -> Opts;
_ -> Opts#{prev_link_name => StartId}
end,
Opts3 = case Limit of
all -> Opts2;
_ -> Opts2#{size => Limit}
end,
{ok, Transfers} = for_each_link(ListDocId, fun(_LinkName, TransferId, Acc) ->
[TransferId | Acc]
end, [], SpaceId, Opts3),
lists:reverse(Transfers).
-spec link_key(transfer:id(), non_neg_integer()) -> link_key().
link_key(TransferId, Timestamp) ->
TimestampPart = (integer_to_binary(?EPOCH_INFINITY - Timestamp)),
IdPart = binary:part(TransferId, 0, ?LINK_NAME_ID_PART_LENGTH),
<<TimestampPart/binary, IdPart/binary>>.
Internal functions
@private
-spec link_root(binary(), od_space:id()) -> binary().
link_root(Prefix, SpaceId) ->
<<Prefix/binary, "_", SpaceId/binary>>.
Real link source_id will be obtained from link_root/2 function .
-spec add_link(SourceId :: virtual_list_id(), TransferId :: transfer:id(),
od_space:id(), transfer:timestamp()) -> ok.
add_link(SourceId, TransferId, SpaceId, Timestamp) ->
TreeId = oneprovider:get_id(),
Ctx = ?CTX#{scope => SpaceId},
Key = link_key(TransferId, Timestamp),
LinkRoot = link_root(SourceId, SpaceId),
case datastore_model:add_links(Ctx, LinkRoot, TreeId, {Key, TransferId}) of
{ok, _} ->
ok;
{error, already_exists} ->
ok
end.
Real link source_id will be obtained from link_root/2 function .
-spec delete_links(SourceId :: virtual_list_id(), TransferId :: transfer:id(),
od_space:id(), transfer:timestamp()) -> ok.
delete_links(SourceId, TransferId, SpaceId, Timestamp) ->
LinkRoot = link_root(SourceId, SpaceId),
Key = link_key(TransferId, Timestamp),
case datastore_model:get_links(?CTX, LinkRoot, all, Key) of
{error, not_found} ->
ok;
{ok, Links} ->
lists:foreach(fun(#link{tree_id = ProviderId, name = LinkName}) ->
case oneprovider:is_self(ProviderId) of
true ->
ok = datastore_model:delete_links(
?CTX#{scope => SpaceId}, LinkRoot,
ProviderId, LinkName
);
false ->
ok = datastore_model:mark_links_deleted(
?CTX#{scope => SpaceId}, LinkRoot,
ProviderId, LinkName
)
end
end, Links)
end.
@private
-spec for_each_link(
virtual_list_id(),
Callback :: fun((link_key(), transfer:id(), Acc0 :: term()) -> Acc :: term()),
Acc0 :: term(), od_space:id(), datastore_model:fold_opts()) ->
{ok, Acc :: term()} | {error, term()}.
for_each_link(ListDocId, Callback, Acc0, SpaceId, Options) ->
datastore_model:fold_links(?CTX, link_root(ListDocId, SpaceId), all, fun
(#link{name = Name, target = Target}, Acc) ->
{ok, Callback(Name, Target, Acc)}
end, Acc0, Options).
|
97664cfa8a91f700922ed6065fc73b526484207bd6c9fc710135f9f4381e6933 | bsaleil/lc | conform.scm.scm | ;;------------------------------------------------------------------------------
Macros
(##define-macro (def-macro form . body)
`(##define-macro ,form (let () ,@body)))
(def-macro (FLOATvector-const . lst) `',(list->vector lst))
(def-macro (FLOATvector? x) `(vector? ,x))
(def-macro (FLOATvector . lst) `(vector ,@lst))
(def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init))
(def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i))
(def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x))
(def-macro (FLOATvector-length v) `(vector-length ,v))
(def-macro (nuc-const . lst)
`',(list->vector lst))
(def-macro (FLOAT+ . lst) `(+ ,@lst))
(def-macro (FLOAT- . lst) `(- ,@lst))
(def-macro (FLOAT* . lst) `(* ,@lst))
(def-macro (FLOAT/ . lst) `(/ ,@lst))
(def-macro (FLOAT= . lst) `(= ,@lst))
(def-macro (FLOAT< . lst) `(< ,@lst))
(def-macro (FLOAT<= . lst) `(<= ,@lst))
(def-macro (FLOAT> . lst) `(> ,@lst))
(def-macro (FLOAT>= . lst) `(>= ,@lst))
(def-macro (FLOATnegative? . lst) `(negative? ,@lst))
(def-macro (FLOATpositive? . lst) `(positive? ,@lst))
(def-macro (FLOATzero? . lst) `(zero? ,@lst))
(def-macro (FLOATabs . lst) `(abs ,@lst))
(def-macro (FLOATsin . lst) `(sin ,@lst))
(def-macro (FLOATcos . lst) `(cos ,@lst))
(def-macro (FLOATatan . lst) `(atan ,@lst))
(def-macro (FLOATsqrt . lst) `(sqrt ,@lst))
(def-macro (FLOATmin . lst) `(min ,@lst))
(def-macro (FLOATmax . lst) `(max ,@lst))
(def-macro (FLOATround . lst) `(round ,@lst))
(def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst))
(def-macro (GENERIC+ . lst) `(+ ,@lst))
(def-macro (GENERIC- . lst) `(- ,@lst))
(def-macro (GENERIC* . lst) `(* ,@lst))
(def-macro (GENERIC/ . lst) `(/ ,@lst))
(def-macro (GENERICquotient . lst) `(quotient ,@lst))
(def-macro (GENERICremainder . lst) `(remainder ,@lst))
(def-macro (GENERICmodulo . lst) `(modulo ,@lst))
(def-macro (GENERIC= . lst) `(= ,@lst))
(def-macro (GENERIC< . lst) `(< ,@lst))
(def-macro (GENERIC<= . lst) `(<= ,@lst))
(def-macro (GENERIC> . lst) `(> ,@lst))
(def-macro (GENERIC>= . lst) `(>= ,@lst))
(def-macro (GENERICexpt . lst) `(expt ,@lst))
;;------------------------------------------------------------------------------
Functions used by LC to get time info
(def-macro (##lc-time expr)
(let ((sym (gensym)))
`(let ((r (##lc-exec-stats (lambda () ,expr))))
(println "CPU time: "
(+ (cdr (assoc "User time" (cdr r)))
(cdr (assoc "Sys time" (cdr r)))))
(map (lambda (el) (println (car el) ": " (cdr el))) (cdr r))
r)))
(define (##lc-exec-stats thunk)
(let* ((at-start (gambit$$##process-statistics))
(result (thunk))
(at-end (gambit$$##process-statistics)))
(define (get-info msg idx)
(cons msg
(- (gambit$$##f64vector-ref at-end idx)
(gambit$$##f64vector-ref at-start idx))))
(list
result
(get-info "User time" 0)
(get-info "Sys time" 1)
(get-info "Real time" 2)
(get-info "GC user time" 3)
(get-info "GC sys time" 4)
(get-info "GC real time" 5)
(get-info "Nb gcs" 6))))
;;------------------------------------------------------------------------------
(define ###TIME_BEFORE### 0)
(define ###TIME_AFTER### 0)
(define (run-bench name count ok? run)
(let loop ((i count) (result '(undefined)))
(if (< 0 i)
(loop (- i 1) (run))
result)))
(define (run-benchmark name count ok? run-maker . args)
(let ((run (apply run-maker args)))
(let ((result (car (##lc-time (run-bench name count ok? run)))))
(if (not (ok? result))
(begin
(display "*** wrong result ***")
(newline)
(display "*** got: ")
(write result)
(newline))))))
; Gabriel benchmarks
(define boyer-iters 20)
(define browse-iters 600)
(define cpstak-iters 1000)
(define ctak-iters 100)
(define dderiv-iters 2000000)
(define deriv-iters 2000000)
(define destruc-iters 500)
(define diviter-iters 1000000)
(define divrec-iters 1000000)
(define puzzle-iters 100)
(define tak-iters 2000)
(define takl-iters 300)
(define trav1-iters 100)
(define trav2-iters 20)
(define triangl-iters 10)
and benchmarks
(define ack-iters 10)
(define array1-iters 1)
(define cat-iters 1)
(define string-iters 10)
(define sum1-iters 10)
(define sumloop-iters 10)
(define tail-iters 1)
(define wc-iters 1)
; C benchmarks
(define fft-iters 2000)
(define fib-iters 5)
(define fibfp-iters 2)
(define mbrot-iters 100)
(define nucleic-iters 5)
(define pnpoly-iters 100000)
(define sum-iters 20000)
(define sumfp-iters 20000)
(define tfib-iters 20)
; Other benchmarks
(define conform-iters 40)
(define dynamic-iters 20)
(define earley-iters 200)
(define fibc-iters 500)
(define graphs-iters 300)
(define lattice-iters 1)
(define matrix-iters 400)
(define maze-iters 4000)
(define mazefun-iters 1000)
(define nqueens-iters 2000)
(define paraffins-iters 1000)
(define peval-iters 200)
(define pi-iters 2)
(define primes-iters 100000)
(define ray-iters 5)
(define scheme-iters 20000)
(define simplex-iters 100000)
(define slatex-iters 20)
(define perm9-iters 10)
(define nboyer-iters 100)
(define sboyer-iters 100)
(define gcbench-iters 1)
(define compiler-iters 300)
CONFORM -- Type checker , written by .
;;; Functional and unstable
(define (sort-list obj pred)
(define (loop l)
(if (and (pair? l) (pair? (cdr l)))
(split-list l '() '())
l))
(define (split-list l one two)
(if (pair? l)
(split-list (cdr l) two (cons (car l) one))
(merge (loop one) (loop two))))
(define (merge one two)
(cond ((null? one) two)
((pred (car two) (car one))
(cons (car two)
(merge (cdr two) one)))
(else
(cons (car one)
(merge (cdr one) two)))))
(loop obj))
;; SET OPERATIONS
; (representation as lists with distinct elements)
(define (adjoin element set)
(if (memq element set) set (cons element set)))
(define (eliminate element set)
(cond ((null? set) set)
((eq? element (car set)) (cdr set))
(else (cons (car set) (eliminate element (cdr set))))))
(define (intersect list1 list2)
(let loop ((l list1))
(cond ((null? l) '())
((memq (car l) list2) (cons (car l) (loop (cdr l))))
(else (loop (cdr l))))))
(define (union list1 list2)
(if (null? list1)
list2
(union (cdr list1)
(adjoin (car list1) list2))))
GRAPH NODES
(define make-internal-node vector)
(define (internal-node-name node) (vector-ref node 0))
(define (internal-node-green-edges node) (vector-ref node 1))
(define (internal-node-red-edges node) (vector-ref node 2))
(define (internal-node-blue-edges node) (vector-ref node 3))
(define (set-internal-node-name! node name) (vector-set! node 0 name))
(define (set-internal-node-green-edges! node edges) (vector-set! node 1 edges))
(define (set-internal-node-red-edges! node edges) (vector-set! node 2 edges))
(define (set-internal-node-blue-edges! node edges) (vector-set! node 3 edges))
(define (make-node name . blue-edges) ; User's constructor
(let ((name (if (symbol? name) (symbol->string name) name))
(blue-edges (if (null? blue-edges) 'NOT-A-NODE-YET (car blue-edges))))
(make-internal-node name '() '() blue-edges)))
(define (copy-node node)
(make-internal-node (name node) '() '() (blue-edges node)))
; Selectors
(define name internal-node-name)
(define (make-edge-getter selector)
(lambda (node)
(if (or (none-node? node) (any-node? node))
(fatal-error "Can't get edges from the ANY or NONE nodes")
(selector node))))
(define red-edges (make-edge-getter internal-node-red-edges))
(define green-edges (make-edge-getter internal-node-green-edges))
(define blue-edges (make-edge-getter internal-node-blue-edges))
; Mutators
(define (make-edge-setter mutator!)
(lambda (node value)
(cond ((any-node? node) (fatal-error "Can't set edges from the ANY node"))
((none-node? node) 'OK)
(else (mutator! node value)))))
(define set-red-edges! (make-edge-setter set-internal-node-red-edges!))
(define set-green-edges! (make-edge-setter set-internal-node-green-edges!))
(define set-blue-edges! (make-edge-setter set-internal-node-blue-edges!))
;; BLUE EDGES
(define make-blue-edge vector)
(define (blue-edge-operation edge) (vector-ref edge 0))
(define (blue-edge-arg-node edge) (vector-ref edge 1))
(define (blue-edge-res-node edge) (vector-ref edge 2))
(define (set-blue-edge-operation! edge value) (vector-set! edge 0 value))
(define (set-blue-edge-arg-node! edge value) (vector-set! edge 1 value))
(define (set-blue-edge-res-node! edge value) (vector-set! edge 2 value))
; Selectors
(define operation blue-edge-operation)
(define arg-node blue-edge-arg-node)
(define res-node blue-edge-res-node)
; Mutators
(define set-arg-node! set-blue-edge-arg-node!)
(define set-res-node! set-blue-edge-res-node!)
; Higher level operations on blue edges
(define (lookup-op op node)
(let loop ((edges (blue-edges node)))
(cond ((null? edges) '())
((eq? op (operation (car edges))) (car edges))
(else (loop (cdr edges))))))
(define (has-op? op node)
(not (null? (lookup-op op node))))
;; GRAPHS
(define make-internal-graph vector)
(define (internal-graph-nodes graph) (vector-ref graph 0))
(define (internal-graph-already-met graph) (vector-ref graph 1))
(define (internal-graph-already-joined graph) (vector-ref graph 2))
(define (set-internal-graph-nodes! graph nodes) (vector-set! graph 0 nodes))
Constructor
(define (make-graph . nodes)
(make-internal-graph nodes (make-empty-table) (make-empty-table)))
; Selectors
(define graph-nodes internal-graph-nodes)
(define already-met internal-graph-already-met)
(define already-joined internal-graph-already-joined)
; Higher level functions on graphs
(define (add-graph-nodes! graph nodes)
(set-internal-graph-nodes! graph (cons nodes (graph-nodes graph))))
(define (copy-graph g)
(define (copy-list l) (vector->list (list->vector l)))
(make-internal-graph
(copy-list (graph-nodes g))
(already-met g)
(already-joined g)))
(define (clean-graph g)
(define (clean-node node)
(if (not (or (any-node? node) (none-node? node)))
(begin
(set-green-edges! node '())
(set-red-edges! node '()))))
(for-each clean-node (graph-nodes g))
g)
(define (canonicalize-graph graph classes)
(define (fix node)
(define (fix-set object selector mutator)
(mutator object
(map (lambda (node)
(find-canonical-representative node classes))
(selector object))))
(if (not (or (none-node? node) (any-node? node)))
(begin
(fix-set node green-edges set-green-edges!)
(fix-set node red-edges set-red-edges!)
(for-each
(lambda (blue-edge)
(set-arg-node! blue-edge
(find-canonical-representative (arg-node blue-edge) classes))
(set-res-node! blue-edge
(find-canonical-representative (res-node blue-edge) classes)))
(blue-edges node))))
node)
(define (fix-table table)
(define (canonical? node) (eq? node (find-canonical-representative node classes)))
(define (filter-and-fix predicate-fn update-fn list)
(let loop ((list list))
(cond ((null? list) '())
((predicate-fn (car list))
(cons (update-fn (car list)) (loop (cdr list))))
(else (loop (cdr list))))))
(define (fix-line line)
(filter-and-fix
(lambda (entry) (canonical? (car entry)))
(lambda (entry) (cons (car entry)
(find-canonical-representative (cdr entry) classes)))
line))
(if (null? table)
'()
(cons (car table)
(filter-and-fix
(lambda (entry) (canonical? (car entry)))
(lambda (entry) (cons (car entry) (fix-line (cdr entry))))
(cdr table)))))
(make-internal-graph
(map (lambda (class) (fix (car class))) classes)
(fix-table (already-met graph))
(fix-table (already-joined graph))))
;; USEFUL NODES
(define none-node (make-node 'none #t))
(define (none-node? node) (eq? node none-node))
(define any-node (make-node 'any '()))
(define (any-node? node) (eq? node any-node))
;; COLORED EDGE TESTS
(define (green-edge? from-node to-node)
(cond ((any-node? from-node) #f)
((none-node? from-node) #t)
((memq to-node (green-edges from-node)) #t)
(else #f)))
(define (red-edge? from-node to-node)
(cond ((any-node? from-node) #f)
((none-node? from-node) #t)
((memq to-node (red-edges from-node)) #t)
(else #f)))
;; SIGNATURE
; Return signature (i.e. <arg, res>) given an operation and a node
(define sig
(let ((none-comma-any (cons none-node any-node)))
(lambda (op node) ; Returns (arg, res)
(let ((the-edge (lookup-op op node)))
(if (not (null? the-edge))
(cons (arg-node the-edge) (res-node the-edge))
none-comma-any)))))
; Selectors from signature
(define (arg pair) (car pair))
(define (res pair) (cdr pair))
;; CONFORMITY
(define (conforms? t1 t2)
(define nodes-with-red-edges-out '())
(define (add-red-edge! from-node to-node)
(set-red-edges! from-node (adjoin to-node (red-edges from-node)))
(set! nodes-with-red-edges-out
(adjoin from-node nodes-with-red-edges-out)))
(define (greenify-red-edges! from-node)
(set-green-edges! from-node
(append (red-edges from-node) (green-edges from-node)))
(set-red-edges! from-node '()))
(define (delete-red-edges! from-node)
(set-red-edges! from-node '()))
(define (does-conform t1 t2)
(cond ((or (none-node? t1) (any-node? t2)) #t)
((or (any-node? t1) (none-node? t2)) #f)
((green-edge? t1 t2) #t)
((red-edge? t1 t2) #t)
(else
(add-red-edge! t1 t2)
(let loop ((blues (blue-edges t2)))
(if (null? blues)
#t
(let* ((current-edge (car blues))
(phi (operation current-edge)))
(and (has-op? phi t1)
(does-conform
(res (sig phi t1))
(res (sig phi t2)))
(does-conform
(arg (sig phi t2))
(arg (sig phi t1)))
(loop (cdr blues)))))))))
(let ((result (does-conform t1 t2)))
(for-each (if result greenify-red-edges! delete-red-edges!)
nodes-with-red-edges-out)
result))
(define (equivalent? a b)
(and (conforms? a b) (conforms? b a)))
;; EQUIVALENCE CLASSIFICATION
; Given a list of nodes, return a list of equivalence classes
(define (classify nodes)
(let node-loop ((classes '())
(nodes nodes))
(if (null? nodes)
(map (lambda (class)
(sort-list class
(lambda (node1 node2)
(< (string-length (name node1))
(string-length (name node2))))))
classes)
(let ((this-node (car nodes)))
(define (add-node classes)
(cond ((null? classes) (list (list this-node)))
((equivalent? this-node (caar classes))
(cons (cons this-node (car classes))
(cdr classes)))
(else (cons (car classes)
(add-node (cdr classes))))))
(node-loop (add-node classes)
(cdr nodes))))))
; Given a node N and a classified set of nodes,
; find the canonical member corresponding to N
(define (find-canonical-representative element classification)
(let loop ((classes classification))
(cond ((null? classes) (fatal-error "Can't classify" element))
((memq element (car classes)) (car (car classes)))
(else (loop (cdr classes))))))
Reduce a graph by taking only one member of each equivalence
; class and canonicalizing all outbound pointers
(define (reduce graph)
(let ((classes (classify (graph-nodes graph))))
(canonicalize-graph graph classes)))
TWO DIMENSIONAL TABLES
(define (make-empty-table) (list 'TABLE))
(define (lookup table x y)
(let ((one (assq x (cdr table))))
(if one
(let ((two (assq y (cdr one))))
(if two (cdr two) #f))
#f)))
(define (insert! table x y value)
(define (make-singleton-table x y)
(list (cons x y)))
(let ((one (assq x (cdr table))))
(if one
(set-cdr! one (cons (cons y value) (cdr one)))
(set-cdr! table (cons (cons x (make-singleton-table y value))
(cdr table))))))
MEET / JOIN
These update the graph when computing the node for
(define (blue-edge-operate arg-fn res-fn graph op sig1 sig2)
(make-blue-edge op
(arg-fn graph (arg sig1) (arg sig2))
(res-fn graph (res sig1) (res sig2))))
(define (meet graph node1 node2)
(cond ((eq? node1 node2) node1)
((or (any-node? node1) (any-node? node2)) any-node) ; canonicalize
((none-node? node1) node2)
((none-node? node2) node1)
((lookup (already-met graph) node1 node2)) ; return it if found
((conforms? node1 node2) node2)
((conforms? node2 node1) node1)
(else
(let ((result
(make-node (string-append "(" (name node1) " ^ " (name node2) ")"))))
(add-graph-nodes! graph result)
(insert! (already-met graph) node1 node2 result)
(set-blue-edges! result
(map
(lambda (op)
(blue-edge-operate join meet graph op (sig op node1) (sig op node2)))
(intersect (map operation (blue-edges node1))
(map operation (blue-edges node2)))))
result))))
(define (join graph node1 node2)
(cond ((eq? node1 node2) node1)
((any-node? node1) node2)
((any-node? node2) node1)
((or (none-node? node1) (none-node? node2)) none-node) ; canonicalize
((lookup (already-joined graph) node1 node2)) ; return it if found
((conforms? node1 node2) node1)
((conforms? node2 node1) node2)
(else
(let ((result
(make-node (string-append "(" (name node1) " v " (name node2) ")"))))
(add-graph-nodes! graph result)
(insert! (already-joined graph) node1 node2 result)
(set-blue-edges! result
(map
(lambda (op)
(blue-edge-operate meet join graph op (sig op node1) (sig op node2)))
(union (map operation (blue-edges node1))
(map operation (blue-edges node2)))))
result))))
MAKE A LATTICE FROM A GRAPH
(define (make-lattice g print?)
(define (step g)
(let* ((copy (copy-graph g))
(nodes (graph-nodes copy)))
(for-each (lambda (first)
(for-each (lambda (second)
(meet copy first second) (join copy first second))
nodes))
nodes)
copy))
(define (loop g count)
(if print? (display count))
(let ((lattice (step g)))
(if print? (begin (display " -> ") (display (length (graph-nodes lattice)))))
(let* ((new-g (reduce lattice))
(new-count (length (graph-nodes new-g))))
(if (= new-count count)
(begin
(if print? (newline))
new-g)
(begin
(if print? (begin (display " -> ") (display new-count) (newline)))
(loop new-g new-count))))))
(let ((graph
(apply make-graph
(adjoin any-node (adjoin none-node (graph-nodes (clean-graph g)))))))
(loop graph (length (graph-nodes graph)))))
;; DEBUG and TEST
(define a '())
(define b '())
(define c '())
(define d '())
(define (setup)
(set! a (make-node 'a))
(set! b (make-node 'b))
(set-blue-edges! a (list (make-blue-edge 'phi any-node b)))
(set-blue-edges! b (list (make-blue-edge 'phi any-node a)
(make-blue-edge 'theta any-node b)))
(set! c (make-node "c"))
(set! d (make-node "d"))
(set-blue-edges! c (list (make-blue-edge 'theta any-node b)))
(set-blue-edges! d (list (make-blue-edge 'phi any-node c)
(make-blue-edge 'theta any-node d)))
'(made a b c d))
(define (test)
(setup)
(map name
(graph-nodes (make-lattice (make-graph a b c d any-node none-node) #f))))
(define (main . args)
(run-benchmark
"conform"
conform-iters
(lambda (result)
(equal? (map (lambda (s)
(list->string (map char-downcase (string->list s))))
result)
'("(((b v d) ^ a) v c)"
"(c ^ d)"
"(b v (a ^ d))"
"((a v d) ^ b)"
"(b v d)"
"(b ^ (a v c))"
"(a v (c ^ d))"
"((b v d) ^ a)"
"(c v (a v d))"
"(a v c)"
"(d v (b ^ (a v c)))"
"(d ^ (a v c))"
"((a ^ d) v c)"
"((a ^ b) v d)"
"(((a v d) ^ b) v (a ^ d))"
"(b ^ d)"
"(b v (a v d))"
"(a ^ c)"
"(b ^ (c v d))"
"(a ^ b)"
"(a v b)"
"((a ^ d) ^ b)"
"(a ^ d)"
"(a v d)"
"d"
"(c v d)"
"a"
"b"
"c"
"any"
"none")))
(lambda () (lambda () (test)))))
(main)
| null | https://raw.githubusercontent.com/bsaleil/lc/ee7867fd2bdbbe88924300e10b14ea717ee6434b/tools/benchtimes/resultbak/m5rponly/conform.scm.scm | scheme | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Gabriel benchmarks
C benchmarks
Other benchmarks
Functional and unstable
SET OPERATIONS
(representation as lists with distinct elements)
User's constructor
Selectors
Mutators
BLUE EDGES
Selectors
Mutators
Higher level operations on blue edges
GRAPHS
Selectors
Higher level functions on graphs
USEFUL NODES
COLORED EDGE TESTS
SIGNATURE
Return signature (i.e. <arg, res>) given an operation and a node
Returns (arg, res)
Selectors from signature
CONFORMITY
EQUIVALENCE CLASSIFICATION
Given a list of nodes, return a list of equivalence classes
Given a node N and a classified set of nodes,
find the canonical member corresponding to N
class and canonicalizing all outbound pointers
canonicalize
return it if found
canonicalize
return it if found
DEBUG and TEST | Macros
(##define-macro (def-macro form . body)
`(##define-macro ,form (let () ,@body)))
(def-macro (FLOATvector-const . lst) `',(list->vector lst))
(def-macro (FLOATvector? x) `(vector? ,x))
(def-macro (FLOATvector . lst) `(vector ,@lst))
(def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init))
(def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i))
(def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x))
(def-macro (FLOATvector-length v) `(vector-length ,v))
(def-macro (nuc-const . lst)
`',(list->vector lst))
(def-macro (FLOAT+ . lst) `(+ ,@lst))
(def-macro (FLOAT- . lst) `(- ,@lst))
(def-macro (FLOAT* . lst) `(* ,@lst))
(def-macro (FLOAT/ . lst) `(/ ,@lst))
(def-macro (FLOAT= . lst) `(= ,@lst))
(def-macro (FLOAT< . lst) `(< ,@lst))
(def-macro (FLOAT<= . lst) `(<= ,@lst))
(def-macro (FLOAT> . lst) `(> ,@lst))
(def-macro (FLOAT>= . lst) `(>= ,@lst))
(def-macro (FLOATnegative? . lst) `(negative? ,@lst))
(def-macro (FLOATpositive? . lst) `(positive? ,@lst))
(def-macro (FLOATzero? . lst) `(zero? ,@lst))
(def-macro (FLOATabs . lst) `(abs ,@lst))
(def-macro (FLOATsin . lst) `(sin ,@lst))
(def-macro (FLOATcos . lst) `(cos ,@lst))
(def-macro (FLOATatan . lst) `(atan ,@lst))
(def-macro (FLOATsqrt . lst) `(sqrt ,@lst))
(def-macro (FLOATmin . lst) `(min ,@lst))
(def-macro (FLOATmax . lst) `(max ,@lst))
(def-macro (FLOATround . lst) `(round ,@lst))
(def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst))
(def-macro (GENERIC+ . lst) `(+ ,@lst))
(def-macro (GENERIC- . lst) `(- ,@lst))
(def-macro (GENERIC* . lst) `(* ,@lst))
(def-macro (GENERIC/ . lst) `(/ ,@lst))
(def-macro (GENERICquotient . lst) `(quotient ,@lst))
(def-macro (GENERICremainder . lst) `(remainder ,@lst))
(def-macro (GENERICmodulo . lst) `(modulo ,@lst))
(def-macro (GENERIC= . lst) `(= ,@lst))
(def-macro (GENERIC< . lst) `(< ,@lst))
(def-macro (GENERIC<= . lst) `(<= ,@lst))
(def-macro (GENERIC> . lst) `(> ,@lst))
(def-macro (GENERIC>= . lst) `(>= ,@lst))
(def-macro (GENERICexpt . lst) `(expt ,@lst))
Functions used by LC to get time info
(def-macro (##lc-time expr)
(let ((sym (gensym)))
`(let ((r (##lc-exec-stats (lambda () ,expr))))
(println "CPU time: "
(+ (cdr (assoc "User time" (cdr r)))
(cdr (assoc "Sys time" (cdr r)))))
(map (lambda (el) (println (car el) ": " (cdr el))) (cdr r))
r)))
(define (##lc-exec-stats thunk)
(let* ((at-start (gambit$$##process-statistics))
(result (thunk))
(at-end (gambit$$##process-statistics)))
(define (get-info msg idx)
(cons msg
(- (gambit$$##f64vector-ref at-end idx)
(gambit$$##f64vector-ref at-start idx))))
(list
result
(get-info "User time" 0)
(get-info "Sys time" 1)
(get-info "Real time" 2)
(get-info "GC user time" 3)
(get-info "GC sys time" 4)
(get-info "GC real time" 5)
(get-info "Nb gcs" 6))))
(define ###TIME_BEFORE### 0)
(define ###TIME_AFTER### 0)
(define (run-bench name count ok? run)
(let loop ((i count) (result '(undefined)))
(if (< 0 i)
(loop (- i 1) (run))
result)))
(define (run-benchmark name count ok? run-maker . args)
(let ((run (apply run-maker args)))
(let ((result (car (##lc-time (run-bench name count ok? run)))))
(if (not (ok? result))
(begin
(display "*** wrong result ***")
(newline)
(display "*** got: ")
(write result)
(newline))))))
(define boyer-iters 20)
(define browse-iters 600)
(define cpstak-iters 1000)
(define ctak-iters 100)
(define dderiv-iters 2000000)
(define deriv-iters 2000000)
(define destruc-iters 500)
(define diviter-iters 1000000)
(define divrec-iters 1000000)
(define puzzle-iters 100)
(define tak-iters 2000)
(define takl-iters 300)
(define trav1-iters 100)
(define trav2-iters 20)
(define triangl-iters 10)
and benchmarks
(define ack-iters 10)
(define array1-iters 1)
(define cat-iters 1)
(define string-iters 10)
(define sum1-iters 10)
(define sumloop-iters 10)
(define tail-iters 1)
(define wc-iters 1)
(define fft-iters 2000)
(define fib-iters 5)
(define fibfp-iters 2)
(define mbrot-iters 100)
(define nucleic-iters 5)
(define pnpoly-iters 100000)
(define sum-iters 20000)
(define sumfp-iters 20000)
(define tfib-iters 20)
(define conform-iters 40)
(define dynamic-iters 20)
(define earley-iters 200)
(define fibc-iters 500)
(define graphs-iters 300)
(define lattice-iters 1)
(define matrix-iters 400)
(define maze-iters 4000)
(define mazefun-iters 1000)
(define nqueens-iters 2000)
(define paraffins-iters 1000)
(define peval-iters 200)
(define pi-iters 2)
(define primes-iters 100000)
(define ray-iters 5)
(define scheme-iters 20000)
(define simplex-iters 100000)
(define slatex-iters 20)
(define perm9-iters 10)
(define nboyer-iters 100)
(define sboyer-iters 100)
(define gcbench-iters 1)
(define compiler-iters 300)
CONFORM -- Type checker , written by .
(define (sort-list obj pred)
(define (loop l)
(if (and (pair? l) (pair? (cdr l)))
(split-list l '() '())
l))
(define (split-list l one two)
(if (pair? l)
(split-list (cdr l) two (cons (car l) one))
(merge (loop one) (loop two))))
(define (merge one two)
(cond ((null? one) two)
((pred (car two) (car one))
(cons (car two)
(merge (cdr two) one)))
(else
(cons (car one)
(merge (cdr one) two)))))
(loop obj))
(define (adjoin element set)
(if (memq element set) set (cons element set)))
(define (eliminate element set)
(cond ((null? set) set)
((eq? element (car set)) (cdr set))
(else (cons (car set) (eliminate element (cdr set))))))
(define (intersect list1 list2)
(let loop ((l list1))
(cond ((null? l) '())
((memq (car l) list2) (cons (car l) (loop (cdr l))))
(else (loop (cdr l))))))
(define (union list1 list2)
(if (null? list1)
list2
(union (cdr list1)
(adjoin (car list1) list2))))
GRAPH NODES
(define make-internal-node vector)
(define (internal-node-name node) (vector-ref node 0))
(define (internal-node-green-edges node) (vector-ref node 1))
(define (internal-node-red-edges node) (vector-ref node 2))
(define (internal-node-blue-edges node) (vector-ref node 3))
(define (set-internal-node-name! node name) (vector-set! node 0 name))
(define (set-internal-node-green-edges! node edges) (vector-set! node 1 edges))
(define (set-internal-node-red-edges! node edges) (vector-set! node 2 edges))
(define (set-internal-node-blue-edges! node edges) (vector-set! node 3 edges))
(let ((name (if (symbol? name) (symbol->string name) name))
(blue-edges (if (null? blue-edges) 'NOT-A-NODE-YET (car blue-edges))))
(make-internal-node name '() '() blue-edges)))
(define (copy-node node)
(make-internal-node (name node) '() '() (blue-edges node)))
(define name internal-node-name)
(define (make-edge-getter selector)
(lambda (node)
(if (or (none-node? node) (any-node? node))
(fatal-error "Can't get edges from the ANY or NONE nodes")
(selector node))))
(define red-edges (make-edge-getter internal-node-red-edges))
(define green-edges (make-edge-getter internal-node-green-edges))
(define blue-edges (make-edge-getter internal-node-blue-edges))
(define (make-edge-setter mutator!)
(lambda (node value)
(cond ((any-node? node) (fatal-error "Can't set edges from the ANY node"))
((none-node? node) 'OK)
(else (mutator! node value)))))
(define set-red-edges! (make-edge-setter set-internal-node-red-edges!))
(define set-green-edges! (make-edge-setter set-internal-node-green-edges!))
(define set-blue-edges! (make-edge-setter set-internal-node-blue-edges!))
(define make-blue-edge vector)
(define (blue-edge-operation edge) (vector-ref edge 0))
(define (blue-edge-arg-node edge) (vector-ref edge 1))
(define (blue-edge-res-node edge) (vector-ref edge 2))
(define (set-blue-edge-operation! edge value) (vector-set! edge 0 value))
(define (set-blue-edge-arg-node! edge value) (vector-set! edge 1 value))
(define (set-blue-edge-res-node! edge value) (vector-set! edge 2 value))
(define operation blue-edge-operation)
(define arg-node blue-edge-arg-node)
(define res-node blue-edge-res-node)
(define set-arg-node! set-blue-edge-arg-node!)
(define set-res-node! set-blue-edge-res-node!)
(define (lookup-op op node)
(let loop ((edges (blue-edges node)))
(cond ((null? edges) '())
((eq? op (operation (car edges))) (car edges))
(else (loop (cdr edges))))))
(define (has-op? op node)
(not (null? (lookup-op op node))))
(define make-internal-graph vector)
(define (internal-graph-nodes graph) (vector-ref graph 0))
(define (internal-graph-already-met graph) (vector-ref graph 1))
(define (internal-graph-already-joined graph) (vector-ref graph 2))
(define (set-internal-graph-nodes! graph nodes) (vector-set! graph 0 nodes))
Constructor
(define (make-graph . nodes)
(make-internal-graph nodes (make-empty-table) (make-empty-table)))
(define graph-nodes internal-graph-nodes)
(define already-met internal-graph-already-met)
(define already-joined internal-graph-already-joined)
(define (add-graph-nodes! graph nodes)
(set-internal-graph-nodes! graph (cons nodes (graph-nodes graph))))
(define (copy-graph g)
(define (copy-list l) (vector->list (list->vector l)))
(make-internal-graph
(copy-list (graph-nodes g))
(already-met g)
(already-joined g)))
(define (clean-graph g)
(define (clean-node node)
(if (not (or (any-node? node) (none-node? node)))
(begin
(set-green-edges! node '())
(set-red-edges! node '()))))
(for-each clean-node (graph-nodes g))
g)
(define (canonicalize-graph graph classes)
(define (fix node)
(define (fix-set object selector mutator)
(mutator object
(map (lambda (node)
(find-canonical-representative node classes))
(selector object))))
(if (not (or (none-node? node) (any-node? node)))
(begin
(fix-set node green-edges set-green-edges!)
(fix-set node red-edges set-red-edges!)
(for-each
(lambda (blue-edge)
(set-arg-node! blue-edge
(find-canonical-representative (arg-node blue-edge) classes))
(set-res-node! blue-edge
(find-canonical-representative (res-node blue-edge) classes)))
(blue-edges node))))
node)
(define (fix-table table)
(define (canonical? node) (eq? node (find-canonical-representative node classes)))
(define (filter-and-fix predicate-fn update-fn list)
(let loop ((list list))
(cond ((null? list) '())
((predicate-fn (car list))
(cons (update-fn (car list)) (loop (cdr list))))
(else (loop (cdr list))))))
(define (fix-line line)
(filter-and-fix
(lambda (entry) (canonical? (car entry)))
(lambda (entry) (cons (car entry)
(find-canonical-representative (cdr entry) classes)))
line))
(if (null? table)
'()
(cons (car table)
(filter-and-fix
(lambda (entry) (canonical? (car entry)))
(lambda (entry) (cons (car entry) (fix-line (cdr entry))))
(cdr table)))))
(make-internal-graph
(map (lambda (class) (fix (car class))) classes)
(fix-table (already-met graph))
(fix-table (already-joined graph))))
(define none-node (make-node 'none #t))
(define (none-node? node) (eq? node none-node))
(define any-node (make-node 'any '()))
(define (any-node? node) (eq? node any-node))
(define (green-edge? from-node to-node)
(cond ((any-node? from-node) #f)
((none-node? from-node) #t)
((memq to-node (green-edges from-node)) #t)
(else #f)))
(define (red-edge? from-node to-node)
(cond ((any-node? from-node) #f)
((none-node? from-node) #t)
((memq to-node (red-edges from-node)) #t)
(else #f)))
(define sig
(let ((none-comma-any (cons none-node any-node)))
(let ((the-edge (lookup-op op node)))
(if (not (null? the-edge))
(cons (arg-node the-edge) (res-node the-edge))
none-comma-any)))))
(define (arg pair) (car pair))
(define (res pair) (cdr pair))
(define (conforms? t1 t2)
(define nodes-with-red-edges-out '())
(define (add-red-edge! from-node to-node)
(set-red-edges! from-node (adjoin to-node (red-edges from-node)))
(set! nodes-with-red-edges-out
(adjoin from-node nodes-with-red-edges-out)))
(define (greenify-red-edges! from-node)
(set-green-edges! from-node
(append (red-edges from-node) (green-edges from-node)))
(set-red-edges! from-node '()))
(define (delete-red-edges! from-node)
(set-red-edges! from-node '()))
(define (does-conform t1 t2)
(cond ((or (none-node? t1) (any-node? t2)) #t)
((or (any-node? t1) (none-node? t2)) #f)
((green-edge? t1 t2) #t)
((red-edge? t1 t2) #t)
(else
(add-red-edge! t1 t2)
(let loop ((blues (blue-edges t2)))
(if (null? blues)
#t
(let* ((current-edge (car blues))
(phi (operation current-edge)))
(and (has-op? phi t1)
(does-conform
(res (sig phi t1))
(res (sig phi t2)))
(does-conform
(arg (sig phi t2))
(arg (sig phi t1)))
(loop (cdr blues)))))))))
(let ((result (does-conform t1 t2)))
(for-each (if result greenify-red-edges! delete-red-edges!)
nodes-with-red-edges-out)
result))
(define (equivalent? a b)
(and (conforms? a b) (conforms? b a)))
(define (classify nodes)
(let node-loop ((classes '())
(nodes nodes))
(if (null? nodes)
(map (lambda (class)
(sort-list class
(lambda (node1 node2)
(< (string-length (name node1))
(string-length (name node2))))))
classes)
(let ((this-node (car nodes)))
(define (add-node classes)
(cond ((null? classes) (list (list this-node)))
((equivalent? this-node (caar classes))
(cons (cons this-node (car classes))
(cdr classes)))
(else (cons (car classes)
(add-node (cdr classes))))))
(node-loop (add-node classes)
(cdr nodes))))))
(define (find-canonical-representative element classification)
(let loop ((classes classification))
(cond ((null? classes) (fatal-error "Can't classify" element))
((memq element (car classes)) (car (car classes)))
(else (loop (cdr classes))))))
Reduce a graph by taking only one member of each equivalence
(define (reduce graph)
(let ((classes (classify (graph-nodes graph))))
(canonicalize-graph graph classes)))
TWO DIMENSIONAL TABLES
(define (make-empty-table) (list 'TABLE))
(define (lookup table x y)
(let ((one (assq x (cdr table))))
(if one
(let ((two (assq y (cdr one))))
(if two (cdr two) #f))
#f)))
(define (insert! table x y value)
(define (make-singleton-table x y)
(list (cons x y)))
(let ((one (assq x (cdr table))))
(if one
(set-cdr! one (cons (cons y value) (cdr one)))
(set-cdr! table (cons (cons x (make-singleton-table y value))
(cdr table))))))
MEET / JOIN
These update the graph when computing the node for
(define (blue-edge-operate arg-fn res-fn graph op sig1 sig2)
(make-blue-edge op
(arg-fn graph (arg sig1) (arg sig2))
(res-fn graph (res sig1) (res sig2))))
(define (meet graph node1 node2)
(cond ((eq? node1 node2) node1)
((none-node? node1) node2)
((none-node? node2) node1)
((conforms? node1 node2) node2)
((conforms? node2 node1) node1)
(else
(let ((result
(make-node (string-append "(" (name node1) " ^ " (name node2) ")"))))
(add-graph-nodes! graph result)
(insert! (already-met graph) node1 node2 result)
(set-blue-edges! result
(map
(lambda (op)
(blue-edge-operate join meet graph op (sig op node1) (sig op node2)))
(intersect (map operation (blue-edges node1))
(map operation (blue-edges node2)))))
result))))
(define (join graph node1 node2)
(cond ((eq? node1 node2) node1)
((any-node? node1) node2)
((any-node? node2) node1)
((conforms? node1 node2) node1)
((conforms? node2 node1) node2)
(else
(let ((result
(make-node (string-append "(" (name node1) " v " (name node2) ")"))))
(add-graph-nodes! graph result)
(insert! (already-joined graph) node1 node2 result)
(set-blue-edges! result
(map
(lambda (op)
(blue-edge-operate meet join graph op (sig op node1) (sig op node2)))
(union (map operation (blue-edges node1))
(map operation (blue-edges node2)))))
result))))
MAKE A LATTICE FROM A GRAPH
(define (make-lattice g print?)
(define (step g)
(let* ((copy (copy-graph g))
(nodes (graph-nodes copy)))
(for-each (lambda (first)
(for-each (lambda (second)
(meet copy first second) (join copy first second))
nodes))
nodes)
copy))
(define (loop g count)
(if print? (display count))
(let ((lattice (step g)))
(if print? (begin (display " -> ") (display (length (graph-nodes lattice)))))
(let* ((new-g (reduce lattice))
(new-count (length (graph-nodes new-g))))
(if (= new-count count)
(begin
(if print? (newline))
new-g)
(begin
(if print? (begin (display " -> ") (display new-count) (newline)))
(loop new-g new-count))))))
(let ((graph
(apply make-graph
(adjoin any-node (adjoin none-node (graph-nodes (clean-graph g)))))))
(loop graph (length (graph-nodes graph)))))
(define a '())
(define b '())
(define c '())
(define d '())
(define (setup)
(set! a (make-node 'a))
(set! b (make-node 'b))
(set-blue-edges! a (list (make-blue-edge 'phi any-node b)))
(set-blue-edges! b (list (make-blue-edge 'phi any-node a)
(make-blue-edge 'theta any-node b)))
(set! c (make-node "c"))
(set! d (make-node "d"))
(set-blue-edges! c (list (make-blue-edge 'theta any-node b)))
(set-blue-edges! d (list (make-blue-edge 'phi any-node c)
(make-blue-edge 'theta any-node d)))
'(made a b c d))
(define (test)
(setup)
(map name
(graph-nodes (make-lattice (make-graph a b c d any-node none-node) #f))))
(define (main . args)
(run-benchmark
"conform"
conform-iters
(lambda (result)
(equal? (map (lambda (s)
(list->string (map char-downcase (string->list s))))
result)
'("(((b v d) ^ a) v c)"
"(c ^ d)"
"(b v (a ^ d))"
"((a v d) ^ b)"
"(b v d)"
"(b ^ (a v c))"
"(a v (c ^ d))"
"((b v d) ^ a)"
"(c v (a v d))"
"(a v c)"
"(d v (b ^ (a v c)))"
"(d ^ (a v c))"
"((a ^ d) v c)"
"((a ^ b) v d)"
"(((a v d) ^ b) v (a ^ d))"
"(b ^ d)"
"(b v (a v d))"
"(a ^ c)"
"(b ^ (c v d))"
"(a ^ b)"
"(a v b)"
"((a ^ d) ^ b)"
"(a ^ d)"
"(a v d)"
"d"
"(c v d)"
"a"
"b"
"c"
"any"
"none")))
(lambda () (lambda () (test)))))
(main)
|
e30827e696755fc2f11ad3fc9a3980081ec1148cec46b238f6451eb0b6b8438c | Leofltt/Kairos | FlashCrash.hs | FLASHCRASH - June 4 2022
-- @leofltt
-- setup model:cycles
addI "mck" $ models csd1 1
addI "mcs" $ models csd1 2
addI "mcp" $ models csd1 3
addI "mcc" $ models csd1 4
addI "mct" $ models csd1 5
addI "mcb" $ models csd1 6
-- a comfy bpm
cT 131
s ( 2 )
pats : s1 , s2 , s3 , s4
pitch "mcs" (toPfs [60, 65, 61, 59]) nv
addC "mcs" "s3" =<< patternWithDensity 12 12 55
b ( 6 )
-- pats: b1
addC "mcb" "b1" $ textToTP 8 "hi"
pan "mcb" (toPfs [65]) k
pitch "mcb" (toPfs [60, 60, 60, 61, 59, 60, 60, 59]) $ rnd
cPat "uno" "rimshock"
p "rimshock"
pan "rimshock" [Pd 0.3, Pd 0.5, Pd 0.7] rnd
vol "rimshock" [Pd 0.8] k
vol "rimshock" [Pd 0.8] k
rev "rimshock" [Pd 0.2] k
rev "rimshock" [Pd 0.2] k
addC "chroger" "r" $ shine 8 "~~~~~~*~"
pan "chroger" (toPfs [0.3, 0.15, 0.5, 0.8, 0.6]) rnd
cPat "downB" "chroger"
p "chroger"
addC "chdb" "db1" $ shine 4 "~~~~~**~~~~~~**~"
rev "chdb" (toPfs [0, 0.4, 0.7]) rnd
pan "chdb" (toPfs [0.3, 0.6, 0.5]) rnd
cPat "upFour" "ohmlfx"
p "ohmlfx"
pan "mcc" [Pd 65] k
cPat "sixteenN" "mcc"
| null | https://raw.githubusercontent.com/Leofltt/Kairos/0ffaba6f043b5774626a26f924256857de533d4b/Performances/FlashCrash.hs | haskell | @leofltt
setup model:cycles
a comfy bpm
pats: b1 | FLASHCRASH - June 4 2022
addI "mck" $ models csd1 1
addI "mcs" $ models csd1 2
addI "mcp" $ models csd1 3
addI "mcc" $ models csd1 4
addI "mct" $ models csd1 5
addI "mcb" $ models csd1 6
cT 131
s ( 2 )
pats : s1 , s2 , s3 , s4
pitch "mcs" (toPfs [60, 65, 61, 59]) nv
addC "mcs" "s3" =<< patternWithDensity 12 12 55
b ( 6 )
addC "mcb" "b1" $ textToTP 8 "hi"
pan "mcb" (toPfs [65]) k
pitch "mcb" (toPfs [60, 60, 60, 61, 59, 60, 60, 59]) $ rnd
cPat "uno" "rimshock"
p "rimshock"
pan "rimshock" [Pd 0.3, Pd 0.5, Pd 0.7] rnd
vol "rimshock" [Pd 0.8] k
vol "rimshock" [Pd 0.8] k
rev "rimshock" [Pd 0.2] k
rev "rimshock" [Pd 0.2] k
addC "chroger" "r" $ shine 8 "~~~~~~*~"
pan "chroger" (toPfs [0.3, 0.15, 0.5, 0.8, 0.6]) rnd
cPat "downB" "chroger"
p "chroger"
addC "chdb" "db1" $ shine 4 "~~~~~**~~~~~~**~"
rev "chdb" (toPfs [0, 0.4, 0.7]) rnd
pan "chdb" (toPfs [0.3, 0.6, 0.5]) rnd
cPat "upFour" "ohmlfx"
p "ohmlfx"
pan "mcc" [Pd 65] k
cPat "sixteenN" "mcc"
|
82ba2f603710e6aebc21faa9d54c91e2578f991de236a8e8c833ebc59741ef35 | robert-strandh/Second-Climacs | command-table.lisp | (cl:in-package #:second-climacs-clim-view-fundamental)
(clim:define-command-table fundamental-table
:inherit-from
(clim-base:global-table
clim-base:ascii-insert-table
clim-base:delete-table
clim-base:motion-table))
| null | https://raw.githubusercontent.com/robert-strandh/Second-Climacs/e49ff97abb07a76a05f7a4467b0e79168cfce057/Code/GUI/McCLIM-ESA/View/Fundamental/command-table.lisp | lisp | (cl:in-package #:second-climacs-clim-view-fundamental)
(clim:define-command-table fundamental-table
:inherit-from
(clim-base:global-table
clim-base:ascii-insert-table
clim-base:delete-table
clim-base:motion-table))
|
|
a4ca97bf96a90bd763812e6c3bc643caa7e3fb5ad8ae0dc6bc6e3c78bb30f506 | jdan/ocaml-web-framework | template_test.ml | open Template
let go () =
assert ("<div>Hello, world!</div>" = div ["Hello, world!"]);
assert ("<div>Hello, <strong>world!</strong></div>" =
div [
"Hello, " ;
strong ["world!"] ;
]);
assert ("<h1 id=\"title\" class=\"huge\">Title</h1>" =
h1
~attrs:[("id", "title"); ("class", "huge")]
["Title"]);
| null | https://raw.githubusercontent.com/jdan/ocaml-web-framework/bfa2f240a9aecc4edbf02ab87a73cfd20da482a4/test/template_test.ml | ocaml | open Template
let go () =
assert ("<div>Hello, world!</div>" = div ["Hello, world!"]);
assert ("<div>Hello, <strong>world!</strong></div>" =
div [
"Hello, " ;
strong ["world!"] ;
]);
assert ("<h1 id=\"title\" class=\"huge\">Title</h1>" =
h1
~attrs:[("id", "title"); ("class", "huge")]
["Title"]);
|
|
8ef486eed1e30a2ac1ef18204c2b7746f9801dad9aacc4cfb263a7f6aae07580 | tweag/funflow2 | Lib.hs | -- Any extra library functions, etc. can go here.
module Lib where
| null | https://raw.githubusercontent.com/tweag/funflow2/642cbb6a1eb3c03b31fe32d22886e4eba4b877cc/cookiecutter-funflow/%7B%7Bcookiecutter.project_name%7D%7D/src/Lib.hs | haskell | Any extra library functions, etc. can go here. | module Lib where
|
906cc74a1fbca62f4c911bb8f99904da75640d0ad932e527e998f20ce9cee75b | rhaberkorn/ermacs | edit_extended.erl | -module(edit_extended).
-include("edit.hrl").
-compile(export_all).
-compile({parse_transform, edit_transform}).
extended_command(State, Mod, Func, Args) ->
{Params, _Doc} = find_cmd_info(Mod, Func),
NewState = execute(State, Mod, Func, Args, Params),
NewState#state{lastcmd={Mod, Func, Args}}.
execute(State, Mod, Func, Args, []) ->
case catch apply(Mod, Func, [State | Args]) of
S when is_record(S, state) ->
S;
{'EXIT', Rsn} ->
io:format("** Crash: ~p~n", [Rsn]),
edit_util:popup_message(State, '*Error*', "** Crash: ~p", [Rsn]);
Other ->
State
end;
execute(State, Mod, Func, Args, Params)
when State#state.pending_cmd /= undefined ->
edit_util:status_msg(State, "Minibuffer busy!");
execute(State, Mod, Func, Args, Params) ->
Cont = make_execute_continuation(Mod, Func, Args, Params),
{Type, Prompt} = hd(Params),
edit_var:set(extended_arg_type, Type),
edit_complete:completion_init(Type),
default_init(State, Type),
State1 = activate_continuation(State, Cont, Prompt ++ " "),
State2 = edit_util:select_window(State1,
fun(W) ->
W#window.minibuffer
end),
case State#state.pending_win of
undefined ->
State2#state{pending_win=(State#state.curwin)#window.id};
_ ->
State2
end.
default_init(State, file) ->
edit_buf:set_text(minibuffer, edit_util:pwd(State));
default_init(State, _) ->
ok.
make_execute_continuation(Mod, Func, Args, Params) ->
fun(State, NewArg) ->
State1 = if length(Params) == 1 ->
%% last argument, we're done!
deactivate_continuation(State);
true ->
State
end,
execute(State1, Mod, Func, Args ++ [NewArg], tl(Params))
end.
activate_continuation(State, C, Prompt) ->
State1 = State#state{pending_cmd=C},
Enabler = fun(Win) -> Win#window{active=true, prefix=Prompt} end,
edit_util:update_minibuffer_window(State1, Enabler).
deactivate_continuation(State) ->
edit_buf:set_text(minibuffer, ""),
State1 = State#state{pending_cmd=undefined},
Disabler = fun(Win) -> Win#window{active=false, prefix=""}
end,
%% disable minibuffer
State2 = edit_util:update_minibuffer_window(State1, Disabler),
%% reselect the window that the command is being done in
State3 =
edit_util:select_window(State2,
fun(W) ->
W#window.id == State2#state.pending_win
end),
State4 = State3#state{pending_win=undefined}.
find_cmd_info(Mod, Func) ->
case catch Mod:command_info() of
{'EXIT', _} ->
{[], ""};
L when is_list(L) ->
case lists:keysearch(Func, 1, L) of
{value, {_, Params, Doc}} ->
{Params, Doc};
_ ->
{[], ""}
end
end.
%% Callbacks from key bindings
take_argument(State) when State#state.pending_cmd /= undefined ->
Text = edit_buf:get_text(minibuffer),
edit_history:add(history_var_name(), Text),
Cont = State#state.pending_cmd,
Cont(State, Text).
abort(State) ->
io:format("Aborted!~n"),
State1 = deactivate_continuation(State).
%% M-x
-command({execute_extended_command,
[{mod_func, "M-x"}],
"Like M-x in emacs."}).
execute_extended_command(State, MF) ->
case string:tokens(MF, " :") of
[ModStr, FunStr] ->
Mod = list_to_atom(ModStr),
Fun = list_to_atom(FunStr),
edit:invoke_extended_async(Mod, Fun, []),
State;
_ ->
edit_util:status_msg(State, "Bad string; must be \"Mod:Fun\"")
end.
%% History
history_move(State, Dir) ->
edit_history:move(State, history_var_name(), history_region_fun(), Dir).
-command({history_search, [{history_regexp, "History regexp:"}]}).
%% FIXME: This function fails when it tries to activate the minibuffer to
%% search regexp, but the minibuffer is already active.
history_search(State, RE) ->
edit_history:search(State, history_var_name(), history_region_fun(), RE).
history_var_name() ->
TypeString = atom_to_list(edit_var:lookup(extended_arg_type)),
list_to_atom("extended_history:" ++ TypeString).
history_region_fun() ->
fun(Buf) -> {1, edit_buf:point_max(Buf)} end.
| null | https://raw.githubusercontent.com/rhaberkorn/ermacs/35c8f9b83ae85e25c646882be6ea6d340a88b05b/src/edit_extended.erl | erlang | last argument, we're done!
disable minibuffer
reselect the window that the command is being done in
Callbacks from key bindings
M-x
History
FIXME: This function fails when it tries to activate the minibuffer to
search regexp, but the minibuffer is already active. | -module(edit_extended).
-include("edit.hrl").
-compile(export_all).
-compile({parse_transform, edit_transform}).
extended_command(State, Mod, Func, Args) ->
{Params, _Doc} = find_cmd_info(Mod, Func),
NewState = execute(State, Mod, Func, Args, Params),
NewState#state{lastcmd={Mod, Func, Args}}.
execute(State, Mod, Func, Args, []) ->
case catch apply(Mod, Func, [State | Args]) of
S when is_record(S, state) ->
S;
{'EXIT', Rsn} ->
io:format("** Crash: ~p~n", [Rsn]),
edit_util:popup_message(State, '*Error*', "** Crash: ~p", [Rsn]);
Other ->
State
end;
execute(State, Mod, Func, Args, Params)
when State#state.pending_cmd /= undefined ->
edit_util:status_msg(State, "Minibuffer busy!");
execute(State, Mod, Func, Args, Params) ->
Cont = make_execute_continuation(Mod, Func, Args, Params),
{Type, Prompt} = hd(Params),
edit_var:set(extended_arg_type, Type),
edit_complete:completion_init(Type),
default_init(State, Type),
State1 = activate_continuation(State, Cont, Prompt ++ " "),
State2 = edit_util:select_window(State1,
fun(W) ->
W#window.minibuffer
end),
case State#state.pending_win of
undefined ->
State2#state{pending_win=(State#state.curwin)#window.id};
_ ->
State2
end.
default_init(State, file) ->
edit_buf:set_text(minibuffer, edit_util:pwd(State));
default_init(State, _) ->
ok.
make_execute_continuation(Mod, Func, Args, Params) ->
fun(State, NewArg) ->
State1 = if length(Params) == 1 ->
deactivate_continuation(State);
true ->
State
end,
execute(State1, Mod, Func, Args ++ [NewArg], tl(Params))
end.
activate_continuation(State, C, Prompt) ->
State1 = State#state{pending_cmd=C},
Enabler = fun(Win) -> Win#window{active=true, prefix=Prompt} end,
edit_util:update_minibuffer_window(State1, Enabler).
deactivate_continuation(State) ->
edit_buf:set_text(minibuffer, ""),
State1 = State#state{pending_cmd=undefined},
Disabler = fun(Win) -> Win#window{active=false, prefix=""}
end,
State2 = edit_util:update_minibuffer_window(State1, Disabler),
State3 =
edit_util:select_window(State2,
fun(W) ->
W#window.id == State2#state.pending_win
end),
State4 = State3#state{pending_win=undefined}.
find_cmd_info(Mod, Func) ->
case catch Mod:command_info() of
{'EXIT', _} ->
{[], ""};
L when is_list(L) ->
case lists:keysearch(Func, 1, L) of
{value, {_, Params, Doc}} ->
{Params, Doc};
_ ->
{[], ""}
end
end.
take_argument(State) when State#state.pending_cmd /= undefined ->
Text = edit_buf:get_text(minibuffer),
edit_history:add(history_var_name(), Text),
Cont = State#state.pending_cmd,
Cont(State, Text).
abort(State) ->
io:format("Aborted!~n"),
State1 = deactivate_continuation(State).
-command({execute_extended_command,
[{mod_func, "M-x"}],
"Like M-x in emacs."}).
execute_extended_command(State, MF) ->
case string:tokens(MF, " :") of
[ModStr, FunStr] ->
Mod = list_to_atom(ModStr),
Fun = list_to_atom(FunStr),
edit:invoke_extended_async(Mod, Fun, []),
State;
_ ->
edit_util:status_msg(State, "Bad string; must be \"Mod:Fun\"")
end.
history_move(State, Dir) ->
edit_history:move(State, history_var_name(), history_region_fun(), Dir).
-command({history_search, [{history_regexp, "History regexp:"}]}).
history_search(State, RE) ->
edit_history:search(State, history_var_name(), history_region_fun(), RE).
history_var_name() ->
TypeString = atom_to_list(edit_var:lookup(extended_arg_type)),
list_to_atom("extended_history:" ++ TypeString).
history_region_fun() ->
fun(Buf) -> {1, edit_buf:point_max(Buf)} end.
|
0af1b74d55a02dc80c741043a593466199f47b210d18e7d47345a84ca062e46d | pfdietz/ansi-test | array-in-bounds-p.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Tue Jan 21 19:57:29 2003
;;;; Contains: Tests for ARRAY-IN-BOUNDS-P
(deftest array-in-bounds-p.1
(array-in-bounds-p #() 0)
nil)
(deftest array-in-bounds-p.2
(array-in-bounds-p #() -1)
nil)
(deftest array-in-bounds-p.3
(let ((a #(a b c d)))
(loop for i from 0 to 4 collect (notnot (array-in-bounds-p a i))))
(t t t t nil))
(deftest array-in-bounds-p.4
(notnot (array-in-bounds-p #0aNIL))
t)
(deftest array-in-bounds-p.5
(array-in-bounds-p "" 0)
nil)
(deftest array-in-bounds-p.6
(array-in-bounds-p "" -1)
nil)
(deftest array-in-bounds-p.7
(let ((a "abcd"))
(loop for i from 0 to 4 collect (notnot (array-in-bounds-p a i))))
(t t t t nil))
(deftest array-in-bounds-p.8
(array-in-bounds-p #* 0)
nil)
(deftest array-in-bounds-p.9
(array-in-bounds-p #* -1)
nil)
(deftest array-in-bounds-p.10
(let ((a #*0110))
(loop for i from 0 to 4 collect (notnot (array-in-bounds-p a i))))
(t t t t nil))
;; Fill pointer tests
(deftest array-in-bounds-p.11
(let ((a (make-array '(10) :fill-pointer 5)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a i))))
(nil t t t t t t t t t t nil))
(deftest array-in-bounds-p.12
(let ((a (make-array '(10) :fill-pointer 5 :element-type 'bit :initial-element 0)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a i))))
(nil t t t t t t t t t t nil))
(deftest array-in-bounds-p.13
(let ((a (make-array '(10) :fill-pointer 5 :element-type 'base-char :initial-element #\x)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a i))))
(nil t t t t t t t t t t nil))
(deftest array-in-bounds-p.14
(let ((a (make-array '(10) :fill-pointer 5 :element-type 'character :initial-element #\x)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a i))))
(nil t t t t t t t t t t nil))
;;; Displaced arrays
(deftest array-in-bounds-p.15
(let* ((a1 (make-array '(20)))
(a2 (make-array '(10) :displaced-to a1)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a2 i))))
(nil t t t t t t t t t t nil))
(deftest array-in-bounds-p.16
(let* ((a1 (make-array '(20) :element-type 'bit :initial-element 0))
(a2 (make-array '(10) :displaced-to a1 :element-type 'bit)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a2 i))))
(nil t t t t t t t t t t nil))
(deftest array-in-bounds-p.17
(let* ((a1 (make-array '(20) :element-type 'character :initial-element #\x))
(a2 (make-array '(10) :displaced-to a1 :element-type 'character)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a2 i))))
(nil t t t t t t t t t t nil))
;;; Multidimensional arrays
(deftest array-in-bounds-p.18
(let ((a (make-array '(3 4))))
(loop for i from -1 to 3 collect
(loop for j from -1 to 4 collect
(notnot (array-in-bounds-p a i j)))))
((nil nil nil nil nil nil)
(nil t t t t nil)
(nil t t t t nil)
(nil t t t t nil)
(nil nil nil nil nil nil)))
(deftest array-in-bounds-p.19
(let ((a (make-array '(1 3 4) :adjustable t)))
(loop for i from -1 to 3 collect
(loop for j from -1 to 4 collect
(notnot (array-in-bounds-p a 0 i j)))))
((nil nil nil nil nil nil)
(nil t t t t nil)
(nil t t t t nil)
(nil t t t t nil)
(nil nil nil nil nil nil)))
;;; Very large indices
(deftest array-in-bounds-p.20
(array-in-bounds-p #(a b c) (1+ most-positive-fixnum))
nil)
(deftest array-in-bounds-p.21
(array-in-bounds-p #(a b c) (1- most-negative-fixnum))
nil)
(deftest array-in-bounds-p.22
(array-in-bounds-p #(a b c) 1000000000000000000)
nil)
(deftest array-in-bounds-p.23
(array-in-bounds-p #(a b c) -1000000000000000000)
nil)
Macro expansion
(deftest array-in-bounds-p.24
(macrolet ((%m (z) z)) (array-in-bounds-p (expand-in-current-env (%m #(a b))) 3))
nil)
(deftest array-in-bounds-p.25
(macrolet ((%m (z) z))
(array-in-bounds-p #(a b) (expand-in-current-env (%m 2))))
nil)
;;; Order of evaluation tests
(deftest array-in-bounds-p.order.1
(let ((x 0) y z)
(values
(array-in-bounds-p (progn (setf y (incf x))
#())
(progn (setf z (incf x))
10))
x y z))
nil 2 1 2)
;;; Error tests
(deftest array-in-bounds-p.error.1
(signals-error (array-in-bounds-p) program-error)
t)
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/arrays/array-in-bounds-p.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests for ARRAY-IN-BOUNDS-P
Fill pointer tests
Displaced arrays
Multidimensional arrays
Very large indices
Order of evaluation tests
Error tests | Author :
Created : Tue Jan 21 19:57:29 2003
(deftest array-in-bounds-p.1
(array-in-bounds-p #() 0)
nil)
(deftest array-in-bounds-p.2
(array-in-bounds-p #() -1)
nil)
(deftest array-in-bounds-p.3
(let ((a #(a b c d)))
(loop for i from 0 to 4 collect (notnot (array-in-bounds-p a i))))
(t t t t nil))
(deftest array-in-bounds-p.4
(notnot (array-in-bounds-p #0aNIL))
t)
(deftest array-in-bounds-p.5
(array-in-bounds-p "" 0)
nil)
(deftest array-in-bounds-p.6
(array-in-bounds-p "" -1)
nil)
(deftest array-in-bounds-p.7
(let ((a "abcd"))
(loop for i from 0 to 4 collect (notnot (array-in-bounds-p a i))))
(t t t t nil))
(deftest array-in-bounds-p.8
(array-in-bounds-p #* 0)
nil)
(deftest array-in-bounds-p.9
(array-in-bounds-p #* -1)
nil)
(deftest array-in-bounds-p.10
(let ((a #*0110))
(loop for i from 0 to 4 collect (notnot (array-in-bounds-p a i))))
(t t t t nil))
(deftest array-in-bounds-p.11
(let ((a (make-array '(10) :fill-pointer 5)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a i))))
(nil t t t t t t t t t t nil))
(deftest array-in-bounds-p.12
(let ((a (make-array '(10) :fill-pointer 5 :element-type 'bit :initial-element 0)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a i))))
(nil t t t t t t t t t t nil))
(deftest array-in-bounds-p.13
(let ((a (make-array '(10) :fill-pointer 5 :element-type 'base-char :initial-element #\x)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a i))))
(nil t t t t t t t t t t nil))
(deftest array-in-bounds-p.14
(let ((a (make-array '(10) :fill-pointer 5 :element-type 'character :initial-element #\x)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a i))))
(nil t t t t t t t t t t nil))
(deftest array-in-bounds-p.15
(let* ((a1 (make-array '(20)))
(a2 (make-array '(10) :displaced-to a1)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a2 i))))
(nil t t t t t t t t t t nil))
(deftest array-in-bounds-p.16
(let* ((a1 (make-array '(20) :element-type 'bit :initial-element 0))
(a2 (make-array '(10) :displaced-to a1 :element-type 'bit)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a2 i))))
(nil t t t t t t t t t t nil))
(deftest array-in-bounds-p.17
(let* ((a1 (make-array '(20) :element-type 'character :initial-element #\x))
(a2 (make-array '(10) :displaced-to a1 :element-type 'character)))
(loop for i from -1 to 10 collect (notnot (array-in-bounds-p a2 i))))
(nil t t t t t t t t t t nil))
(deftest array-in-bounds-p.18
(let ((a (make-array '(3 4))))
(loop for i from -1 to 3 collect
(loop for j from -1 to 4 collect
(notnot (array-in-bounds-p a i j)))))
((nil nil nil nil nil nil)
(nil t t t t nil)
(nil t t t t nil)
(nil t t t t nil)
(nil nil nil nil nil nil)))
(deftest array-in-bounds-p.19
(let ((a (make-array '(1 3 4) :adjustable t)))
(loop for i from -1 to 3 collect
(loop for j from -1 to 4 collect
(notnot (array-in-bounds-p a 0 i j)))))
((nil nil nil nil nil nil)
(nil t t t t nil)
(nil t t t t nil)
(nil t t t t nil)
(nil nil nil nil nil nil)))
(deftest array-in-bounds-p.20
(array-in-bounds-p #(a b c) (1+ most-positive-fixnum))
nil)
(deftest array-in-bounds-p.21
(array-in-bounds-p #(a b c) (1- most-negative-fixnum))
nil)
(deftest array-in-bounds-p.22
(array-in-bounds-p #(a b c) 1000000000000000000)
nil)
(deftest array-in-bounds-p.23
(array-in-bounds-p #(a b c) -1000000000000000000)
nil)
Macro expansion
(deftest array-in-bounds-p.24
(macrolet ((%m (z) z)) (array-in-bounds-p (expand-in-current-env (%m #(a b))) 3))
nil)
(deftest array-in-bounds-p.25
(macrolet ((%m (z) z))
(array-in-bounds-p #(a b) (expand-in-current-env (%m 2))))
nil)
(deftest array-in-bounds-p.order.1
(let ((x 0) y z)
(values
(array-in-bounds-p (progn (setf y (incf x))
#())
(progn (setf z (incf x))
10))
x y z))
nil 2 1 2)
(deftest array-in-bounds-p.error.1
(signals-error (array-in-bounds-p) program-error)
t)
|
7dab0b317d05d7cacf368d065cc7964f6c972fa1036c93b02767b2f719f6bb89 | viercc/coercible-subtypes | Union.hs | # LANGUAGE ScopedTypeVariables #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ExistentialQuantification #
module Newtype.Union(
module Data.Type.Coercion.Related,
IsUnion(..),
withUnion,
unique, greater, idemp, commutative, associative
) where
import Prelude hiding (id, (.))
import Control.Category
import Data.Type.Coercion.Sub (sub, equiv)
import Data.Type.Coercion.Sub.Internal
import Data.Type.Coercion.Related
import Data.Type.Coercion.Related.Internal
import Data.Type.Coercion ( Coercion(Coercion), TestCoercion(..))
-- | @IsUnion x y z@ witnesses the fact:
--
-- * All @x, y, z@ share the same runtime representation
* @z@ is a union type of @x@ and @y@. In other words , the following three holds :
--
-- * @'Sub' x z@
-- * @Sub y z@
-- * For any type @r@ satisfying both of @(Sub x r, Sub y r)@, @Sub z r@.
data IsUnion x y z = IsUnion
{
inl :: !(Sub x z), -- ^ @x@ can be safely coerced to @z@
inr :: !(Sub y z), -- ^ @y@ can be safely coerced to @z@
elim :: forall r. Sub x r -> Sub y r -> Sub z r
-- ^ Given both @x@ and @y@ can be safely coerced to @r@, too @z@ can.
}
instance Eq (IsUnion x y z) where
_ == _ = True
instance Ord (IsUnion x y z) where
compare _ _ = EQ
instance TestCoercion (IsUnion x y) where
testCoercion u1 u2 = Just (unique u1 u2)
-- | For a pair of 'Related' types @x@ and @y@, make some (existentially quantified)
type @xy@ where @xy@ is a union type of @x ,
withUnion :: Related x y -> (forall xy. IsUnion x y xy -> r) -> r
withUnion (Related Coercion) body =
body IsUnion{ inl = sub, inr = id, elim = seq }
| Two union types , z'@ of the same pair of types @x , y@ may be different ,
but they are equivalent in terms of coercibility .
unique :: IsUnion x y z -> IsUnion x y z' -> Coercion z z'
unique xy xy' = equiv (elim xy (inl xy') (inr xy')) (elim xy' (inl xy) (inr xy))
| When @Sub x y@ , @y@ itself is a union type of @x ,
greater :: Sub x y -> IsUnion x y y
greater l = IsUnion{ inl = l, inr = id, elim=seq }
-- | Union is idempotent.
--
-- Note: combining @idemp@ and 'unique', @IsUnion x x z -> Coercion x z@ holds.
idemp :: IsUnion x x x
idemp = greater id
-- | Union is commutative.
--
-- Note: combining @commutative@ and 'unique', @IsUnion x y xy -> IsUnion y x yx -> Coercion xy yx@ holds.
commutative :: IsUnion x y z -> IsUnion y x z
commutative xyz = IsUnion{ inl = inr xyz, inr = inl xyz, elim = flip (elim xyz) }
-- | Union is associative.
--
-- Note: combining @associative@ and 'unique', the following holds.
--
-- > IsUnion x y xy -> IsUnion xy z xy'z
-- > -> IsUnion y z yz -> IsUnion x yz x'yz
-- > -> Coercion xy'z x'yz
associative :: IsUnion x y xy -> IsUnion xy z xyz -> IsUnion y z yz -> IsUnion x yz xyz
associative xy xy'z yz =
IsUnion {
inl = inl xy'z . inl xy
, inr = elim yz (inl xy'z . inr xy) (inr xy'z)
, elim = \x_r yz_r -> elim xy'z (elim xy x_r (yz_r . inl yz)) (yz_r . inr yz)
}
| null | https://raw.githubusercontent.com/viercc/coercible-subtypes/761f1f0df06860abe0fd1442d7d255e241ce98fe/src/Newtype/Union.hs | haskell | # LANGUAGE RankNTypes #
| @IsUnion x y z@ witnesses the fact:
* All @x, y, z@ share the same runtime representation
* @'Sub' x z@
* @Sub y z@
* For any type @r@ satisfying both of @(Sub x r, Sub y r)@, @Sub z r@.
^ @x@ can be safely coerced to @z@
^ @y@ can be safely coerced to @z@
^ Given both @x@ and @y@ can be safely coerced to @r@, too @z@ can.
| For a pair of 'Related' types @x@ and @y@, make some (existentially quantified)
| Union is idempotent.
Note: combining @idemp@ and 'unique', @IsUnion x x z -> Coercion x z@ holds.
| Union is commutative.
Note: combining @commutative@ and 'unique', @IsUnion x y xy -> IsUnion y x yx -> Coercion xy yx@ holds.
| Union is associative.
Note: combining @associative@ and 'unique', the following holds.
> IsUnion x y xy -> IsUnion xy z xy'z
> -> IsUnion y z yz -> IsUnion x yz x'yz
> -> Coercion xy'z x'yz | # LANGUAGE ScopedTypeVariables #
# LANGUAGE ExistentialQuantification #
module Newtype.Union(
module Data.Type.Coercion.Related,
IsUnion(..),
withUnion,
unique, greater, idemp, commutative, associative
) where
import Prelude hiding (id, (.))
import Control.Category
import Data.Type.Coercion.Sub (sub, equiv)
import Data.Type.Coercion.Sub.Internal
import Data.Type.Coercion.Related
import Data.Type.Coercion.Related.Internal
import Data.Type.Coercion ( Coercion(Coercion), TestCoercion(..))
* @z@ is a union type of @x@ and @y@. In other words , the following three holds :
data IsUnion x y z = IsUnion
{
elim :: forall r. Sub x r -> Sub y r -> Sub z r
}
instance Eq (IsUnion x y z) where
_ == _ = True
instance Ord (IsUnion x y z) where
compare _ _ = EQ
instance TestCoercion (IsUnion x y) where
testCoercion u1 u2 = Just (unique u1 u2)
type @xy@ where @xy@ is a union type of @x ,
withUnion :: Related x y -> (forall xy. IsUnion x y xy -> r) -> r
withUnion (Related Coercion) body =
body IsUnion{ inl = sub, inr = id, elim = seq }
| Two union types , z'@ of the same pair of types @x , y@ may be different ,
but they are equivalent in terms of coercibility .
unique :: IsUnion x y z -> IsUnion x y z' -> Coercion z z'
unique xy xy' = equiv (elim xy (inl xy') (inr xy')) (elim xy' (inl xy) (inr xy))
| When @Sub x y@ , @y@ itself is a union type of @x ,
greater :: Sub x y -> IsUnion x y y
greater l = IsUnion{ inl = l, inr = id, elim=seq }
idemp :: IsUnion x x x
idemp = greater id
commutative :: IsUnion x y z -> IsUnion y x z
commutative xyz = IsUnion{ inl = inr xyz, inr = inl xyz, elim = flip (elim xyz) }
associative :: IsUnion x y xy -> IsUnion xy z xyz -> IsUnion y z yz -> IsUnion x yz xyz
associative xy xy'z yz =
IsUnion {
inl = inl xy'z . inl xy
, inr = elim yz (inl xy'z . inr xy) (inr xy'z)
, elim = \x_r yz_r -> elim xy'z (elim xy x_r (yz_r . inl yz)) (yz_r . inr yz)
}
|
9c453a6f648d32303aba2134b6918a811c52dece3927037783d6792e66bf1295 | donaldsonjw/bigloo | evaluate.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / runtime / Eval / evaluate.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Fri Jul 2 10:01:28 2010 * /
* Last change : We d Nov 19 13:25:11 2014 ( serrano ) * /
* Copyright : 2010 - 14 * /
;* ------------------------------------------------------------- */
* New Bigloo interpreter * /
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module __evaluate
(import __type
__error
__bigloo
__tvector
__structure
__tvector
__bexit
__bignum
__os
__dsssl
__bit
__param
__bexit
__object
__thread
__r4_numbers_6_5
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_characters_6_6
__r4_equivalence_6_2
__r4_booleans_6_1
__r4_symbols_6_4
__r4_strings_6_7
__r4_pairs_and_lists_6_3
__r4_control_features_6_9
__r4_vectors_6_8
__r4_ports_6_10_1
__r4_output_6_10_3
__r5_control_features_6_4
__pp
__reader
__progn
__expand
__evenv
__evcompile
__everror
__evmodule
__evaluate_types
__evaluate_avar
__evaluate_fsize
__evaluate_uncomp
__evaluate_comp)
(export (evaluate2 sexp env loc)
(get-evaluation-context)
(set-evaluation-context! v)
(evaluate2-restore-bp! ::int)
(evaluate2-restore-state! ::vector)))
;*---------------------------------------------------------------------*/
;* untype-ident ... */
;*---------------------------------------------------------------------*/
(define (untype-ident id::symbol)
(let* ((string (symbol->string id))
(len (string-length string)))
(let loop ((walker 0))
(cond
((=fx walker len)
(cons id #f))
((and (char=? (string-ref string walker) #\:)
(<fx walker (-fx len 1))
(char=? (string-ref string (+fx walker 1)) #\:))
(cons (string->symbol (substring string 0 walker))
(string->symbol (substring string (+fx walker 2)))))
(else
(loop (+fx walker 1)))))))
;*---------------------------------------------------------------------*/
;* get-evaluation-context ... */
;*---------------------------------------------------------------------*/
(define (get-evaluation-context)
(let ( (s (find-state)) )
(let ( (bp (vector-ref s 0)) )
(let ( (r (make-vector bp "")) )
(let rec ( (i 0) )
(when (<fx i bp)
(vector-set! r i (vector-ref s i))
(rec (+fx i 1)) ))
r ))))
;*---------------------------------------------------------------------*/
;* set-evaluation-context! ... */
;*---------------------------------------------------------------------*/
(define (set-evaluation-context! v)
(let ( (s (find-state)) )
(let ( (bp (vector-ref v 0)) )
(let rec ( (i 0) )
(when (<fx i bp)
(vector-set! s i (vector-ref v i))
(rec (+fx i 1)) )))))
;*---------------------------------------------------------------------*/
;* evaluate2-restore-bp! ... */
;*---------------------------------------------------------------------*/
(define (evaluate2-restore-bp! bp)
(let ((s ($evmeaning-evstate (current-dynamic-env))))
(vector-set! s 0 bp)))
;*---------------------------------------------------------------------*/
;* evaluate2-restore-state! ... */
;*---------------------------------------------------------------------*/
(define (evaluate2-restore-state! state)
(let ((env (current-dynamic-env)))
($evmeaning-evstate-set! env state)))
;*---------------------------------------------------------------------*/
* ... * /
;*---------------------------------------------------------------------*/
(define (evaluate2 sexp env loc)
(let ( (ast (extract-loops (convert sexp env loc))) )
(when (> (bigloo-debug) 10) (pp (uncompile ast)))
(analyse-vars ast)
(let ( (n (frame-size ast)) )
(let ( (f (compile ast)) )
(let ( (s (find-state)) )
(let ( (bp (vector-ref s 0)) )
(unwind-protect
(f s)
(vector-set! s 0 bp) )))))))
;*---------------------------------------------------------------------*/
;* get-location ... */
;*---------------------------------------------------------------------*/
(define (get-location exp loc)
(or (get-source-location exp) loc))
;*---------------------------------------------------------------------*/
;* get-location3 ... */
;*---------------------------------------------------------------------*/
(define (get-location3 exp lst loc)
(or (get-source-location exp)
(get-source-location lst)
loc))
;*---------------------------------------------------------------------*/
;* convert ... */
;*---------------------------------------------------------------------*/
(define (convert e globals loc)
(conv e '() globals #f 'toplevel loc #t) )
;*---------------------------------------------------------------------*/
;* conv-var ... */
;*---------------------------------------------------------------------*/
(define (conv-var v locals)
(let rec ( (l locals) )
(if (null? l)
#f
(let ( (rv (car l)) )
(with-access::ev_var rv (name)
(if (eq? v name)
rv
(rec (cdr l)) ))))))
;*---------------------------------------------------------------------*/
;* conv-begin ... */
;*---------------------------------------------------------------------*/
(define (conv-begin l locals globals tail? where loc top?)
(let ( (loc (get-location l loc)) )
(match-case l
(()
(instantiate::ev_litt
(value #unspecified)))
((?e)
(conv e locals globals tail? where (get-location e loc) top?))
((?e1 . ?r)
(instantiate::ev_prog2
(e1 (conv e1 locals globals #f where (get-location e1 loc) top?))
(e2 (conv-begin r locals globals tail? where loc top?)) ))
(else
(evcompile-error loc "eval" "bad syntax" l)) )))
;*---------------------------------------------------------------------*/
;* conv-global ... */
;*---------------------------------------------------------------------*/
(define (conv-global loc id globals)
(instantiate::ev_global
(loc loc)
(name id)
(mod (if (evmodule? globals) globals ($eval-module)))))
;*---------------------------------------------------------------------*/
;* conv-field-ref ... */
;*---------------------------------------------------------------------*/
(define (conv-field-ref e locals globals tail? where loc top?)
(let* ( (l (cdr e))
(v (conv-var (car l) locals)) )
(if (isa? v ev_var)
(with-access::ev_var v (type name)
(let loop ( (node v)
(klass (class-exists type))
(fields (cdr l)) )
(cond
((null? fields)
node)
((class? klass)
(let ( (field (find-class-field klass (car fields))) )
(if (class-field? field)
(let ( (node (make-class-field-ref
field node loc tail?)) )
(loop node
(class-field-type field)
(cdr fields)) )
(evcompile-error loc type
(format "Class \"~a\" has no field \"~a\"" type (car fields))
e) )))
(else
(evcompile-error loc (or type name)
"Static type not a class" e) ))))
(evcompile-error loc (cadr e) "Variable unbound" e) )))
;*---------------------------------------------------------------------*/
;* conv-field-set ... */
;*---------------------------------------------------------------------*/
(define (conv-field-set l e2 e locals globals tail? where loc top?)
(let* ( (v (conv-var (car l) locals))
(e2 (conv e2 locals globals #f where loc #f)) )
(if (isa? v ev_var)
(with-access::ev_var v (type name)
(let loop ( (node v)
(klass (class-exists type))
(fields (cdr l)) )
(cond
((null? fields)
node)
((class? klass)
(let ( (field (find-class-field klass (car fields))) )
(if (class-field? field)
(if (null? (cdr fields))
(if (class-field-mutable? field)
(make-class-field-set
field (list node e2) loc tail?)
(evcompile-error loc (car fields)
"Field read-only"
e))
(let ( (node (make-class-field-ref
field node loc tail?)) )
(loop node
(class-field-type field)
(cdr fields)) ))
(evcompile-error loc type
(format "Class \"~a\" has no field \"~a\"" type (car fields))
e) )))
(else
(evcompile-error loc
(or type name) "Static type not a class" e) ))))
(evcompile-error loc (car l) "Variable unbound" e) )))
;*---------------------------------------------------------------------*/
;* make-class-field-ref ... */
;*---------------------------------------------------------------------*/
(define (make-class-field-ref field arg loc tail?)
(let ( (get (class-field-accessor field)) )
(instantiate::ev_app
(loc loc)
(fun (instantiate::ev_litt (value get)))
(args (list arg))
(tail? tail?))))
;*---------------------------------------------------------------------*/
;* make-class-field-set ... */
;*---------------------------------------------------------------------*/
(define (make-class-field-set field args loc tail?)
(let ( (set (class-field-mutator field)) )
(instantiate::ev_app
(loc loc)
(fun (instantiate::ev_litt (value set)))
(args args)
(tail? tail?))))
;*---------------------------------------------------------------------*/
;* evepairify ... */
;*---------------------------------------------------------------------*/
(define (evepairify p loc)
(econs (car p) (cdr p) loc))
;*---------------------------------------------------------------------*/
;* type-check ... */
;*---------------------------------------------------------------------*/
(define (type-check var tname loc procname body)
(if (symbol? tname)
(let ((pred (case tname
((pair) 'pair?)
((vector) 'vector?)
((symbol) 'symbol?)
((char) 'char?)
((int bint) 'integer?)
((real breal) 'real?)
((bool) 'boolean?)
((struct) 'struct?)
((class) 'class?)
((string bstring) 'string?)
(else `(lambda (o)
(let ((c (class-exists ',tname)))
(if c (isa? o c) #t)))))))
(evepairify
`(if (,pred ,var)
,body
,(match-case loc
((at ?fname ?pos)
`(bigloo-type-error/location
,(when (symbol? procname) (symbol->string procname))
,(symbol->string tname) ,var
,fname ,pos))
(else
`(bigloo-type-error
,(when (symbol? procname) (symbol->string procname))
,(symbol->string tname) ,var))))
loc))
body))
;*---------------------------------------------------------------------*/
;* type-checks ... */
;*---------------------------------------------------------------------*/
(define (type-checks vars srcs body loc procname)
(if (<=fx (bigloo-debug) 0)
body
(let loop ((vars vars)
(srcs srcs))
(if (null? vars)
body
(let* ((v (car vars))
(id (car v))
(tname (cdr v)))
(if tname
(let ((loc (get-location3 (car srcs) srcs loc)))
(type-check id tname loc procname
(loop (cdr vars) (cdr srcs))))
(loop (cdr vars) (cdr srcs))))))))
;*---------------------------------------------------------------------*/
;* type-result ... */
;*---------------------------------------------------------------------*/
(define (type-result type body loc)
(if (and type (>=fx (bigloo-debug) 1))
(let ((tmp (gensym 'tmp)))
(evepairify
`(let ((,(string->symbol (format "~a::~a" tmp type)) ,body))
,tmp)
(get-location body loc)))
body))
;*---------------------------------------------------------------------*/
;* conv ... */
;*---------------------------------------------------------------------*/
(define (conv e locals globals tail? where loc top?)
(define (rconv/loc e loc)
(conv e locals globals tail? where loc #f))
(define (rconv e)
(rconv/loc e (get-location e loc)))
(define (uconv/loc+where e loc where)
(conv e locals globals #f where loc #f))
(define (uconv/loc e loc)
(conv e locals globals #f where loc #f))
(define (uconv e)
(uconv/loc e (get-location e loc)))
(define (uconv/where e where)
(uconv/loc+where e (get-location e loc) where))
(define (uconv* es)
(let loop ((es es))
(if (null? es)
'()
(let ((e (car es)))
(cons (conv e locals globals #f where (get-location3 e es loc) #f)
(loop (cdr es)))))))
(define (conv-lambda formals body where type)
(define (split-formals l)
(let rec ( (r l) (flat '()) (arity 0) )
(cond
((null? r)
(values (reverse! flat) arity))
((not (pair? r))
(values (reverse! (cons (untype-ident r) flat)) (-fx -1 arity)))
(else
(rec (cdr r)
(cons (untype-ident (car r)) flat) (+fx arity 1))) )))
(multiple-value-bind (args arity)
(split-formals (dsssl-formals->scheme-typed-formals formals error #t))
(let ( (vars (map (lambda (v)
(instantiate::ev_var
(name (car v))
(type (cdr v))) )
args ))
(body (make-dsssl-function-prelude e formals
(type-checks args args (type-result type body loc) loc where)
error))
(nloc (get-location body loc)) )
(instantiate::ev_abs
(loc loc)
(where where)
(arity arity)
(vars vars)
(body (conv body (append vars locals) globals #t where nloc #f)) ))))
(match-case e
((atom ?x)
(if (symbol? x)
(or (conv-var x locals) (conv-global loc x globals))
(instantiate::ev_litt
(value x)) ))
((module . ?bah)
(if top?
(let ((forms (evmodule e (get-location e loc))))
(conv (expand forms) locals
($eval-module) where #f loc #t))
(evcompile-error loc "eval" "Illegal non toplevel module declaration" e) ))
((@ (and ?id (? symbol?)) (and ?modname (? symbol?)))
(instantiate::ev_global
(loc loc)
(name id)
(mod (eval-find-module modname))))
((-> . ?l)
(if (and (pair? l) (pair? (cdr l)) (every symbol? l))
(conv-field-ref e locals globals tail? where loc top?)
(evcompile-error loc "eval" "Illegal form" e) ))
(((and (? symbol?)
(? (lambda (x) (conv-var x locals)))
?fun)
. ?args)
(let ( (fun (uconv fun)) (args (uconv* args)) )
(instantiate::ev_app
(loc loc)
(fun fun)
(args args)
(tail? tail?)) ))
((trap ?e)
(instantiate::ev_trap
(e (uconv e))) )
((quote ?v)
(instantiate::ev_litt
(value v)) )
((if ?p ?t ?o)
(instantiate::ev_if
(p (uconv/loc p (get-location p loc)))
(t (rconv/loc t (get-location t loc)))
(e (rconv/loc o (get-location o loc)))) )
((if ?p ?t)
(instantiate::ev_if
(p (uconv/loc p (get-location p loc)))
(t (rconv/loc t (get-location t loc)))
(e (rconv/loc e (get-location #f loc)))) )
(((kwote or) . ?args)
(instantiate::ev_or
(args (uconv* args))) )
(((kwote and) . ?args)
(instantiate::ev_and
(args (uconv* args))) )
((begin . ?l)
(conv-begin l locals globals tail? where loc top?) )
((let ?binds . ?body)
(let* ( (ubinds (map (lambda (b) (untype-ident (car b))) binds))
(vars (map (lambda (i)
(instantiate::ev_var
(name (car i))
(type (cdr i)) ))
ubinds))
(body (if (pair? (cdr body)) (econs 'begin body loc) (car body)))
(tbody (type-checks ubinds binds body loc where)) )
(let ( (bloc (get-location binds loc)) )
(instantiate::ev_let
(vars vars)
(vals (map (lambda (b)
(let ( (loc (get-location b bloc)) )
(uconv/loc (cadr b) loc) ))
binds))
(body (conv tbody (append vars locals) globals tail? where loc #f)) ))))
((let* ?binds . ?body)
(define (conv-vals l vars locals loc)
(if (null? l)
'()
(let ( (loc (get-location (car l) loc)) )
(cons (conv (cadar l) locals globals #f where loc #f)
(conv-vals (cdr l) (cdr vars) (cons (car vars) locals) loc) ))))
(let ( (vars (map (lambda (b)
(let ( (i (untype-ident (car b))) )
(instantiate::ev_var
(name (car i))
(type (cdr i)) )))
binds))
(bloc (get-location binds loc)) )
(instantiate::ev_let*
(vars vars)
(vals (conv-vals binds vars locals bloc))
(body (conv-begin body (append (reverse vars) locals) globals tail? where loc #f)) )))
((letrec ?binds . ?body)
(let* ( (ubinds (map (lambda (b) (untype-ident (car b))) binds))
(vars (map (lambda (i)
(instantiate::ev_var
(name (car i))
(type (cdr i)) ))
ubinds))
(locals (append vars locals))
(body (if (pair? (cdr body)) (econs 'begin body loc) (car body)))
(tbody (type-checks ubinds binds body loc where))
(bloc (get-location binds loc)) )
(instantiate::ev_letrec
(vars vars)
(vals (map (lambda (b)
(conv (cadr b) locals globals #f (symbol-append (car b) '| | where) (get-location b bloc) #f)) binds) )
(body (conv tbody locals globals tail? where loc #f) ))))
((set! (@ (and ?id (? symbol?)) (and ?modname (? symbol?))) ?e)
(instantiate::ev_setglobal
(loc loc)
(name id)
(mod (eval-find-module modname))
(e (uconv e))))
((set! (-> . ?l) ?e2)
(if (and (pair? l) (pair? (cdr l)) (every symbol? l))
(conv-field-set l e2 e locals globals tail? where loc top?)
(evcompile-error loc "eval" "Illegal form" e) ))
((set! ?v ?e)
(let ( (cv (conv-var v locals)) (e (uconv e)) )
(if cv
(instantiate::ev_setlocal
(v cv)
(e e))
(instantiate::ev_setglobal
(loc loc)
(name v)
(mod (if (evmodule? globals) globals ($eval-module)))
(e e)) )))
((set! . ?-)
(evcompile-error loc "eval" "Illegal form" e))
((define ?gv (lambda ?formals ?body))
(let ((tid (untype-ident gv)))
(instantiate::ev_defglobal
(loc loc)
(name (car tid))
(mod (if (evmodule? globals) globals ($eval-module)))
(e (conv-lambda formals body gv (cdr tid))) )))
((define ?gv ?ge)
(let ( (tid (untype-ident gv)) )
(instantiate::ev_defglobal
(loc loc)
(name (car tid))
(mod (if (evmodule? globals) globals ($eval-module)))
(e (uconv/where
(type-result (cdr tid) ge loc)
(if top? gv where))) )))
((bind-exit (?v) . ?body)
(let ( (var (instantiate::ev_var (name v) (type #f))) )
(instantiate::ev_bind-exit
(var var)
(body (conv-begin body (cons var locals) globals #f where loc #f)) )))
((unwind-protect ?e . ?body)
(instantiate::ev_unwind-protect
(e (uconv e))
(body (conv-begin body locals globals #f where loc #f)) ))
((with-handler ?h . ?body)
(instantiate::ev_with-handler
(handler (uconv h))
(body (conv-begin body locals globals #f where loc #f)) ))
((synchronize ?m :prelock ?p . ?body)
(instantiate::ev_synchronize
(loc loc)
(mutex (uconv m))
(prelock (uconv p))
(body (conv-begin body locals globals #f where loc #f)) ))
((synchronize ?m . ?body)
(instantiate::ev_synchronize
(loc loc)
(mutex (uconv m))
(prelock (uconv '()))
(body (conv-begin body locals globals #f where loc #f)) ))
((lambda ?formals ?body)
(conv-lambda formals body (symbol-append '\@ where) #f) )
((?f . ?args)
(let ( (fun (uconv f)) (args (uconv* args)) )
(instantiate::ev_app
(loc loc)
(fun fun)
(args args)
(tail? tail?)) ))
(else (evcompile-error loc "eval" "bad syntax" e)) ))
| null | https://raw.githubusercontent.com/donaldsonjw/bigloo/a4d06e409d0004e159ce92b9908719510a18aed5/runtime/Eval/evaluate.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* untype-ident ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* get-evaluation-context ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* set-evaluation-context! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evaluate2-restore-bp! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evaluate2-restore-state! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* get-location ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* get-location3 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* convert ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* conv-var ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* conv-begin ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* conv-global ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* conv-field-ref ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* conv-field-set ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* make-class-field-ref ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* make-class-field-set ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evepairify ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* type-check ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* type-checks ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* type-result ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* conv ... */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / bigloo / runtime / Eval / evaluate.scm * /
* Author : * /
* Creation : Fri Jul 2 10:01:28 2010 * /
* Last change : We d Nov 19 13:25:11 2014 ( serrano ) * /
* Copyright : 2010 - 14 * /
* New Bigloo interpreter * /
(module __evaluate
(import __type
__error
__bigloo
__tvector
__structure
__tvector
__bexit
__bignum
__os
__dsssl
__bit
__param
__bexit
__object
__thread
__r4_numbers_6_5
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_characters_6_6
__r4_equivalence_6_2
__r4_booleans_6_1
__r4_symbols_6_4
__r4_strings_6_7
__r4_pairs_and_lists_6_3
__r4_control_features_6_9
__r4_vectors_6_8
__r4_ports_6_10_1
__r4_output_6_10_3
__r5_control_features_6_4
__pp
__reader
__progn
__expand
__evenv
__evcompile
__everror
__evmodule
__evaluate_types
__evaluate_avar
__evaluate_fsize
__evaluate_uncomp
__evaluate_comp)
(export (evaluate2 sexp env loc)
(get-evaluation-context)
(set-evaluation-context! v)
(evaluate2-restore-bp! ::int)
(evaluate2-restore-state! ::vector)))
(define (untype-ident id::symbol)
(let* ((string (symbol->string id))
(len (string-length string)))
(let loop ((walker 0))
(cond
((=fx walker len)
(cons id #f))
((and (char=? (string-ref string walker) #\:)
(<fx walker (-fx len 1))
(char=? (string-ref string (+fx walker 1)) #\:))
(cons (string->symbol (substring string 0 walker))
(string->symbol (substring string (+fx walker 2)))))
(else
(loop (+fx walker 1)))))))
(define (get-evaluation-context)
(let ( (s (find-state)) )
(let ( (bp (vector-ref s 0)) )
(let ( (r (make-vector bp "")) )
(let rec ( (i 0) )
(when (<fx i bp)
(vector-set! r i (vector-ref s i))
(rec (+fx i 1)) ))
r ))))
(define (set-evaluation-context! v)
(let ( (s (find-state)) )
(let ( (bp (vector-ref v 0)) )
(let rec ( (i 0) )
(when (<fx i bp)
(vector-set! s i (vector-ref v i))
(rec (+fx i 1)) )))))
(define (evaluate2-restore-bp! bp)
(let ((s ($evmeaning-evstate (current-dynamic-env))))
(vector-set! s 0 bp)))
(define (evaluate2-restore-state! state)
(let ((env (current-dynamic-env)))
($evmeaning-evstate-set! env state)))
* ... * /
(define (evaluate2 sexp env loc)
(let ( (ast (extract-loops (convert sexp env loc))) )
(when (> (bigloo-debug) 10) (pp (uncompile ast)))
(analyse-vars ast)
(let ( (n (frame-size ast)) )
(let ( (f (compile ast)) )
(let ( (s (find-state)) )
(let ( (bp (vector-ref s 0)) )
(unwind-protect
(f s)
(vector-set! s 0 bp) )))))))
(define (get-location exp loc)
(or (get-source-location exp) loc))
(define (get-location3 exp lst loc)
(or (get-source-location exp)
(get-source-location lst)
loc))
(define (convert e globals loc)
(conv e '() globals #f 'toplevel loc #t) )
(define (conv-var v locals)
(let rec ( (l locals) )
(if (null? l)
#f
(let ( (rv (car l)) )
(with-access::ev_var rv (name)
(if (eq? v name)
rv
(rec (cdr l)) ))))))
(define (conv-begin l locals globals tail? where loc top?)
(let ( (loc (get-location l loc)) )
(match-case l
(()
(instantiate::ev_litt
(value #unspecified)))
((?e)
(conv e locals globals tail? where (get-location e loc) top?))
((?e1 . ?r)
(instantiate::ev_prog2
(e1 (conv e1 locals globals #f where (get-location e1 loc) top?))
(e2 (conv-begin r locals globals tail? where loc top?)) ))
(else
(evcompile-error loc "eval" "bad syntax" l)) )))
(define (conv-global loc id globals)
(instantiate::ev_global
(loc loc)
(name id)
(mod (if (evmodule? globals) globals ($eval-module)))))
(define (conv-field-ref e locals globals tail? where loc top?)
(let* ( (l (cdr e))
(v (conv-var (car l) locals)) )
(if (isa? v ev_var)
(with-access::ev_var v (type name)
(let loop ( (node v)
(klass (class-exists type))
(fields (cdr l)) )
(cond
((null? fields)
node)
((class? klass)
(let ( (field (find-class-field klass (car fields))) )
(if (class-field? field)
(let ( (node (make-class-field-ref
field node loc tail?)) )
(loop node
(class-field-type field)
(cdr fields)) )
(evcompile-error loc type
(format "Class \"~a\" has no field \"~a\"" type (car fields))
e) )))
(else
(evcompile-error loc (or type name)
"Static type not a class" e) ))))
(evcompile-error loc (cadr e) "Variable unbound" e) )))
(define (conv-field-set l e2 e locals globals tail? where loc top?)
(let* ( (v (conv-var (car l) locals))
(e2 (conv e2 locals globals #f where loc #f)) )
(if (isa? v ev_var)
(with-access::ev_var v (type name)
(let loop ( (node v)
(klass (class-exists type))
(fields (cdr l)) )
(cond
((null? fields)
node)
((class? klass)
(let ( (field (find-class-field klass (car fields))) )
(if (class-field? field)
(if (null? (cdr fields))
(if (class-field-mutable? field)
(make-class-field-set
field (list node e2) loc tail?)
(evcompile-error loc (car fields)
"Field read-only"
e))
(let ( (node (make-class-field-ref
field node loc tail?)) )
(loop node
(class-field-type field)
(cdr fields)) ))
(evcompile-error loc type
(format "Class \"~a\" has no field \"~a\"" type (car fields))
e) )))
(else
(evcompile-error loc
(or type name) "Static type not a class" e) ))))
(evcompile-error loc (car l) "Variable unbound" e) )))
(define (make-class-field-ref field arg loc tail?)
(let ( (get (class-field-accessor field)) )
(instantiate::ev_app
(loc loc)
(fun (instantiate::ev_litt (value get)))
(args (list arg))
(tail? tail?))))
(define (make-class-field-set field args loc tail?)
(let ( (set (class-field-mutator field)) )
(instantiate::ev_app
(loc loc)
(fun (instantiate::ev_litt (value set)))
(args args)
(tail? tail?))))
(define (evepairify p loc)
(econs (car p) (cdr p) loc))
(define (type-check var tname loc procname body)
(if (symbol? tname)
(let ((pred (case tname
((pair) 'pair?)
((vector) 'vector?)
((symbol) 'symbol?)
((char) 'char?)
((int bint) 'integer?)
((real breal) 'real?)
((bool) 'boolean?)
((struct) 'struct?)
((class) 'class?)
((string bstring) 'string?)
(else `(lambda (o)
(let ((c (class-exists ',tname)))
(if c (isa? o c) #t)))))))
(evepairify
`(if (,pred ,var)
,body
,(match-case loc
((at ?fname ?pos)
`(bigloo-type-error/location
,(when (symbol? procname) (symbol->string procname))
,(symbol->string tname) ,var
,fname ,pos))
(else
`(bigloo-type-error
,(when (symbol? procname) (symbol->string procname))
,(symbol->string tname) ,var))))
loc))
body))
(define (type-checks vars srcs body loc procname)
(if (<=fx (bigloo-debug) 0)
body
(let loop ((vars vars)
(srcs srcs))
(if (null? vars)
body
(let* ((v (car vars))
(id (car v))
(tname (cdr v)))
(if tname
(let ((loc (get-location3 (car srcs) srcs loc)))
(type-check id tname loc procname
(loop (cdr vars) (cdr srcs))))
(loop (cdr vars) (cdr srcs))))))))
(define (type-result type body loc)
(if (and type (>=fx (bigloo-debug) 1))
(let ((tmp (gensym 'tmp)))
(evepairify
`(let ((,(string->symbol (format "~a::~a" tmp type)) ,body))
,tmp)
(get-location body loc)))
body))
(define (conv e locals globals tail? where loc top?)
(define (rconv/loc e loc)
(conv e locals globals tail? where loc #f))
(define (rconv e)
(rconv/loc e (get-location e loc)))
(define (uconv/loc+where e loc where)
(conv e locals globals #f where loc #f))
(define (uconv/loc e loc)
(conv e locals globals #f where loc #f))
(define (uconv e)
(uconv/loc e (get-location e loc)))
(define (uconv/where e where)
(uconv/loc+where e (get-location e loc) where))
(define (uconv* es)
(let loop ((es es))
(if (null? es)
'()
(let ((e (car es)))
(cons (conv e locals globals #f where (get-location3 e es loc) #f)
(loop (cdr es)))))))
(define (conv-lambda formals body where type)
(define (split-formals l)
(let rec ( (r l) (flat '()) (arity 0) )
(cond
((null? r)
(values (reverse! flat) arity))
((not (pair? r))
(values (reverse! (cons (untype-ident r) flat)) (-fx -1 arity)))
(else
(rec (cdr r)
(cons (untype-ident (car r)) flat) (+fx arity 1))) )))
(multiple-value-bind (args arity)
(split-formals (dsssl-formals->scheme-typed-formals formals error #t))
(let ( (vars (map (lambda (v)
(instantiate::ev_var
(name (car v))
(type (cdr v))) )
args ))
(body (make-dsssl-function-prelude e formals
(type-checks args args (type-result type body loc) loc where)
error))
(nloc (get-location body loc)) )
(instantiate::ev_abs
(loc loc)
(where where)
(arity arity)
(vars vars)
(body (conv body (append vars locals) globals #t where nloc #f)) ))))
(match-case e
((atom ?x)
(if (symbol? x)
(or (conv-var x locals) (conv-global loc x globals))
(instantiate::ev_litt
(value x)) ))
((module . ?bah)
(if top?
(let ((forms (evmodule e (get-location e loc))))
(conv (expand forms) locals
($eval-module) where #f loc #t))
(evcompile-error loc "eval" "Illegal non toplevel module declaration" e) ))
((@ (and ?id (? symbol?)) (and ?modname (? symbol?)))
(instantiate::ev_global
(loc loc)
(name id)
(mod (eval-find-module modname))))
((-> . ?l)
(if (and (pair? l) (pair? (cdr l)) (every symbol? l))
(conv-field-ref e locals globals tail? where loc top?)
(evcompile-error loc "eval" "Illegal form" e) ))
(((and (? symbol?)
(? (lambda (x) (conv-var x locals)))
?fun)
. ?args)
(let ( (fun (uconv fun)) (args (uconv* args)) )
(instantiate::ev_app
(loc loc)
(fun fun)
(args args)
(tail? tail?)) ))
((trap ?e)
(instantiate::ev_trap
(e (uconv e))) )
((quote ?v)
(instantiate::ev_litt
(value v)) )
((if ?p ?t ?o)
(instantiate::ev_if
(p (uconv/loc p (get-location p loc)))
(t (rconv/loc t (get-location t loc)))
(e (rconv/loc o (get-location o loc)))) )
((if ?p ?t)
(instantiate::ev_if
(p (uconv/loc p (get-location p loc)))
(t (rconv/loc t (get-location t loc)))
(e (rconv/loc e (get-location #f loc)))) )
(((kwote or) . ?args)
(instantiate::ev_or
(args (uconv* args))) )
(((kwote and) . ?args)
(instantiate::ev_and
(args (uconv* args))) )
((begin . ?l)
(conv-begin l locals globals tail? where loc top?) )
((let ?binds . ?body)
(let* ( (ubinds (map (lambda (b) (untype-ident (car b))) binds))
(vars (map (lambda (i)
(instantiate::ev_var
(name (car i))
(type (cdr i)) ))
ubinds))
(body (if (pair? (cdr body)) (econs 'begin body loc) (car body)))
(tbody (type-checks ubinds binds body loc where)) )
(let ( (bloc (get-location binds loc)) )
(instantiate::ev_let
(vars vars)
(vals (map (lambda (b)
(let ( (loc (get-location b bloc)) )
(uconv/loc (cadr b) loc) ))
binds))
(body (conv tbody (append vars locals) globals tail? where loc #f)) ))))
((let* ?binds . ?body)
(define (conv-vals l vars locals loc)
(if (null? l)
'()
(let ( (loc (get-location (car l) loc)) )
(cons (conv (cadar l) locals globals #f where loc #f)
(conv-vals (cdr l) (cdr vars) (cons (car vars) locals) loc) ))))
(let ( (vars (map (lambda (b)
(let ( (i (untype-ident (car b))) )
(instantiate::ev_var
(name (car i))
(type (cdr i)) )))
binds))
(bloc (get-location binds loc)) )
(instantiate::ev_let*
(vars vars)
(vals (conv-vals binds vars locals bloc))
(body (conv-begin body (append (reverse vars) locals) globals tail? where loc #f)) )))
((letrec ?binds . ?body)
(let* ( (ubinds (map (lambda (b) (untype-ident (car b))) binds))
(vars (map (lambda (i)
(instantiate::ev_var
(name (car i))
(type (cdr i)) ))
ubinds))
(locals (append vars locals))
(body (if (pair? (cdr body)) (econs 'begin body loc) (car body)))
(tbody (type-checks ubinds binds body loc where))
(bloc (get-location binds loc)) )
(instantiate::ev_letrec
(vars vars)
(vals (map (lambda (b)
(conv (cadr b) locals globals #f (symbol-append (car b) '| | where) (get-location b bloc) #f)) binds) )
(body (conv tbody locals globals tail? where loc #f) ))))
((set! (@ (and ?id (? symbol?)) (and ?modname (? symbol?))) ?e)
(instantiate::ev_setglobal
(loc loc)
(name id)
(mod (eval-find-module modname))
(e (uconv e))))
((set! (-> . ?l) ?e2)
(if (and (pair? l) (pair? (cdr l)) (every symbol? l))
(conv-field-set l e2 e locals globals tail? where loc top?)
(evcompile-error loc "eval" "Illegal form" e) ))
((set! ?v ?e)
(let ( (cv (conv-var v locals)) (e (uconv e)) )
(if cv
(instantiate::ev_setlocal
(v cv)
(e e))
(instantiate::ev_setglobal
(loc loc)
(name v)
(mod (if (evmodule? globals) globals ($eval-module)))
(e e)) )))
((set! . ?-)
(evcompile-error loc "eval" "Illegal form" e))
((define ?gv (lambda ?formals ?body))
(let ((tid (untype-ident gv)))
(instantiate::ev_defglobal
(loc loc)
(name (car tid))
(mod (if (evmodule? globals) globals ($eval-module)))
(e (conv-lambda formals body gv (cdr tid))) )))
((define ?gv ?ge)
(let ( (tid (untype-ident gv)) )
(instantiate::ev_defglobal
(loc loc)
(name (car tid))
(mod (if (evmodule? globals) globals ($eval-module)))
(e (uconv/where
(type-result (cdr tid) ge loc)
(if top? gv where))) )))
((bind-exit (?v) . ?body)
(let ( (var (instantiate::ev_var (name v) (type #f))) )
(instantiate::ev_bind-exit
(var var)
(body (conv-begin body (cons var locals) globals #f where loc #f)) )))
((unwind-protect ?e . ?body)
(instantiate::ev_unwind-protect
(e (uconv e))
(body (conv-begin body locals globals #f where loc #f)) ))
((with-handler ?h . ?body)
(instantiate::ev_with-handler
(handler (uconv h))
(body (conv-begin body locals globals #f where loc #f)) ))
((synchronize ?m :prelock ?p . ?body)
(instantiate::ev_synchronize
(loc loc)
(mutex (uconv m))
(prelock (uconv p))
(body (conv-begin body locals globals #f where loc #f)) ))
((synchronize ?m . ?body)
(instantiate::ev_synchronize
(loc loc)
(mutex (uconv m))
(prelock (uconv '()))
(body (conv-begin body locals globals #f where loc #f)) ))
((lambda ?formals ?body)
(conv-lambda formals body (symbol-append '\@ where) #f) )
((?f . ?args)
(let ( (fun (uconv f)) (args (uconv* args)) )
(instantiate::ev_app
(loc loc)
(fun fun)
(args args)
(tail? tail?)) ))
(else (evcompile-error loc "eval" "bad syntax" e)) ))
|
b3eac431146b726229e1ec31b61629d34edb52e5f9ad6a012bdacce7dcb7246a | vindarel/cl-torrents-web | torrents-reblocks.lisp | (defpackage torrents-reblocks
(:use #:cl
#:torrents ;; local project
#:weblocks-ui/form
#:weblocks/html)
(:import-from #:weblocks/app
#:defapp)
(:import-from #:weblocks/widget
#:get-html-tag
#:render
#:update
#:defwidget)
(:import-from #:weblocks/actions
#:make-js-action)
(:export #:start
#:main))
(in-package :torrents-reblocks)
(defapp torrents)
(weblocks/debug:on)
(defvar *port* (find-port:find-port :min 4000))
(defparameter *title* "torrents-web")
(defun assoc-value (alist key &key (test #'equalp))
Do n't import Alexandria just for that .
;; See also Quickutil to import only the utility we need.
/
(cdr (assoc key alist :test test)))
(defwidget result ()
((torrent
:initarg :torrent
:accessor result-torrent)
;xxx the magnet should be in a "torrent" object, not alist.
(magnet
:initform nil
:accessor result-magnet)
(clicked-p
:initform nil
:accessor result-clicked-p)))
(defun make-result (torrent)
(make-instance 'result :torrent torrent))
(defmethod render ((it result))
(let ((torrent (result-torrent it)))
(flet ((see-magnet (&key &allow-other-keys)
(log:info "see-magnet of widget ~a~&" (result-torrent it))
(setf (result-magnet it) (magnet-link-from torrent))
(update it)))
(with-html
(:td (:a :href (href torrent)
(title torrent)))
(:td (seeders torrent))
(:td (leechers torrent))
(:td (source torrent))
(:td
(with-html-form (:POST #'see-magnet)
(:input :type "submit"
:class "ui primary button"
:value "magnet")))
(when (result-magnet it)
(:tr
(:td :colspan 5
(:h4 (format nil "magnet:"))
(:div (result-magnet it)))))))))
(defwidget results-list ()
((results
:initarg :results
:accessor results)))
(defun make-results-list (results)
(make-instance 'results-list :results results))
(defmethod render ((it results-list))
(let ((results (results it)))
(flet ((query (&key query &allow-other-keys)
(let (search-results)
(log:info "searching for" query)
(setf search-results (async-torrents query))
(setf (results it) (loop for res in search-results
:collect (make-result res)))
(log:info "finished search")
(weblocks/widget:update (weblocks/widgets/root:get)))))
(with-html
(with-html
(:doctype)
(:html
(:head
(:meta :http-equiv "Content-Type" :content "text/html; charset=utf-8") ;; useless
(:meta :charset "UTF-8")
(:meta :charset "UTF-8")
(:link :rel "stylesheet" :type "text/css" :href "[email protected]/dist/semantic.min.css" )
(:title *title*))
(:h1 (:a :href "-torrents-web" "cl-torrents"))
(with-html-form (:POST #'query)
(:div :class "ui action input"
(:input :type "text"
:name "query"
:class "ui input"
:placeholder "search...")
(:input :type "submit"
:value "Search")))
(when results
(:table :class "ui selectable table"
(:thead
(:th "Title")
(:th "Seeders")
(:th "Leechers")
(:th "Source")
(:th ))
(:tbody)
(dolist (it results)
(render it))))))))))
(defmethod weblocks/session:init ((app torrents))
(make-results-list nil))
(defun start ()
(weblocks/debug:on)
(weblocks/server:start :port *port*))
(defun stop ()
(weblocks/server:stop))
(defun reset ()
"Restart (development), take code changes into account."
(weblocks/debug:reset-latest-session))
(defun main ()
(defvar *port* (find-port:find-port))
(start)
(handler-case (bt:join-thread (find-if (lambda (th)
(search "hunchentoot" (bt:thread-name th)))
(bt:all-threads)))
(#+sbcl sb-sys:interactive-interrupt
#+ccl ccl:interrupt-signal-condition
#+clisp system::simple-interrupt-condition
#+ecl ext:interactive-interrupt
#+allegro excl:interrupt-signal
() (progn
(format *error-output* "Aborting.~&")
( weblocks : stop )
(uiop:quit 1))
;; for others, unhandled errors (we might want to do the same).
(error (c) (format t "Woops, an unknown error occured:~&~a~&" c)))))
| null | https://raw.githubusercontent.com/vindarel/cl-torrents-web/c35e93ec658aa69aadf4df70f33e31f37c609f06/src/torrents-reblocks.lisp | lisp | local project
See also Quickutil to import only the utility we need.
xxx the magnet should be in a "torrent" object, not alist.
useless
for others, unhandled errors (we might want to do the same). | (defpackage torrents-reblocks
(:use #:cl
#:weblocks-ui/form
#:weblocks/html)
(:import-from #:weblocks/app
#:defapp)
(:import-from #:weblocks/widget
#:get-html-tag
#:render
#:update
#:defwidget)
(:import-from #:weblocks/actions
#:make-js-action)
(:export #:start
#:main))
(in-package :torrents-reblocks)
(defapp torrents)
(weblocks/debug:on)
(defvar *port* (find-port:find-port :min 4000))
(defparameter *title* "torrents-web")
(defun assoc-value (alist key &key (test #'equalp))
Do n't import Alexandria just for that .
/
(cdr (assoc key alist :test test)))
(defwidget result ()
((torrent
:initarg :torrent
:accessor result-torrent)
(magnet
:initform nil
:accessor result-magnet)
(clicked-p
:initform nil
:accessor result-clicked-p)))
(defun make-result (torrent)
(make-instance 'result :torrent torrent))
(defmethod render ((it result))
(let ((torrent (result-torrent it)))
(flet ((see-magnet (&key &allow-other-keys)
(log:info "see-magnet of widget ~a~&" (result-torrent it))
(setf (result-magnet it) (magnet-link-from torrent))
(update it)))
(with-html
(:td (:a :href (href torrent)
(title torrent)))
(:td (seeders torrent))
(:td (leechers torrent))
(:td (source torrent))
(:td
(with-html-form (:POST #'see-magnet)
(:input :type "submit"
:class "ui primary button"
:value "magnet")))
(when (result-magnet it)
(:tr
(:td :colspan 5
(:h4 (format nil "magnet:"))
(:div (result-magnet it)))))))))
(defwidget results-list ()
((results
:initarg :results
:accessor results)))
(defun make-results-list (results)
(make-instance 'results-list :results results))
(defmethod render ((it results-list))
(let ((results (results it)))
(flet ((query (&key query &allow-other-keys)
(let (search-results)
(log:info "searching for" query)
(setf search-results (async-torrents query))
(setf (results it) (loop for res in search-results
:collect (make-result res)))
(log:info "finished search")
(weblocks/widget:update (weblocks/widgets/root:get)))))
(with-html
(with-html
(:doctype)
(:html
(:head
(:meta :charset "UTF-8")
(:meta :charset "UTF-8")
(:link :rel "stylesheet" :type "text/css" :href "[email protected]/dist/semantic.min.css" )
(:title *title*))
(:h1 (:a :href "-torrents-web" "cl-torrents"))
(with-html-form (:POST #'query)
(:div :class "ui action input"
(:input :type "text"
:name "query"
:class "ui input"
:placeholder "search...")
(:input :type "submit"
:value "Search")))
(when results
(:table :class "ui selectable table"
(:thead
(:th "Title")
(:th "Seeders")
(:th "Leechers")
(:th "Source")
(:th ))
(:tbody)
(dolist (it results)
(render it))))))))))
(defmethod weblocks/session:init ((app torrents))
(make-results-list nil))
(defun start ()
(weblocks/debug:on)
(weblocks/server:start :port *port*))
(defun stop ()
(weblocks/server:stop))
(defun reset ()
"Restart (development), take code changes into account."
(weblocks/debug:reset-latest-session))
(defun main ()
(defvar *port* (find-port:find-port))
(start)
(handler-case (bt:join-thread (find-if (lambda (th)
(search "hunchentoot" (bt:thread-name th)))
(bt:all-threads)))
(#+sbcl sb-sys:interactive-interrupt
#+ccl ccl:interrupt-signal-condition
#+clisp system::simple-interrupt-condition
#+ecl ext:interactive-interrupt
#+allegro excl:interrupt-signal
() (progn
(format *error-output* "Aborting.~&")
( weblocks : stop )
(uiop:quit 1))
(error (c) (format t "Woops, an unknown error occured:~&~a~&" c)))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.