code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DuplicateRecordFields #-}
module PostgREST.DbRequestBuilder (
readRequest
, mutateRequest
, readRpcRequest
, fieldNames
) where
import Control.Applicative
import Control.Arrow ((***))
import Control.Lens.Getter (view)
import Control.Lens.Tuple (_1)
import qualified Data.ByteString.Char8 as BS
import Data.List (delete)
import Data.Maybe (fromJust)
import Data.Text (isInfixOf)
import Data.Tree
import Data.Either.Combinators (mapLeft)
import Network.Wai
import Data.Foldable (foldr1)
import qualified Data.HashMap.Strict as M
import PostgREST.ApiRequest ( ApiRequest(..)
, PreferRepresentation(..)
, Action(..), Target(..)
, PreferRepresentation (..)
)
import PostgREST.Error (apiRequestError)
import PostgREST.Parsers
import PostgREST.RangeQuery (NonnegRange, restrictRange)
import PostgREST.Types
import Protolude hiding (from, dropWhile, drop)
import Text.Regex.TDFA ((=~))
import Unsafe (unsafeHead)
readRequest :: Maybe Integer -> [Relation] -> M.HashMap Text ProcDescription -> ApiRequest -> Either Response ReadRequest
readRequest maxRows allRels allProcs apiRequest =
mapLeft apiRequestError $
treeRestrictRange maxRows =<<
augumentRequestWithJoin schema relations =<<
parseReadRequest
where
(schema, rootTableName) = fromJust $ -- Make it safe
let target = iTarget apiRequest in
case target of
(TargetIdent (QualifiedIdentifier s t) ) -> Just (s, t)
(TargetProc (QualifiedIdentifier s proc) ) -> Just (s, tName)
where
retType = pdReturnType <$> M.lookup proc allProcs
tName = case retType of
Just (SetOf (Composite qi)) -> qiName qi
Just (Single (Composite qi)) -> qiName qi
_ -> proc
_ -> Nothing
action :: Action
action = iAction apiRequest
parseReadRequest :: Either ApiRequestError ReadRequest
parseReadRequest = addFiltersOrdersRanges apiRequest <*>
pRequestSelect rootName selStr
where
selStr = iSelect apiRequest
rootName = if action == ActionRead
then rootTableName
else sourceCTEName
relations :: [Relation]
relations = case action of
ActionCreate -> fakeSourceRelations ++ allRels
ActionUpdate -> fakeSourceRelations ++ allRels
ActionDelete -> fakeSourceRelations ++ allRels
ActionInvoke _ -> fakeSourceRelations ++ allRels
_ -> allRels
where fakeSourceRelations = mapMaybe (toSourceRelation rootTableName) allRels -- see comment in toSourceRelation
treeRestrictRange :: Maybe Integer -> ReadRequest -> Either ApiRequestError ReadRequest
treeRestrictRange maxRows_ request = pure $ nodeRestrictRange maxRows_ `fmap` request
where
nodeRestrictRange :: Maybe Integer -> ReadNode -> ReadNode
nodeRestrictRange m (q@Select {range_=r}, i) = (q{range_=restrictRange m r }, i)
augumentRequestWithJoin :: Schema -> [Relation] -> ReadRequest -> Either ApiRequestError ReadRequest
augumentRequestWithJoin schema allRels request =
addRelations schema allRels Nothing request
>>= addJoinFilters schema
addRelations :: Schema -> [Relation] -> Maybe ReadRequest -> ReadRequest -> Either ApiRequestError ReadRequest
addRelations schema allRelations parentNode (Node readNode@(query, (name, _, alias, relationDetail)) forest) =
case parentNode of
(Just (Node (Select{from=[parentNodeTable]}, (_, _, _, _)) _)) ->
Node <$> readNode' <*> forest'
where
forest' = updateForest $ hush node'
node' = Node <$> readNode' <*> pure forest
readNode' = addRel readNode <$> rel
rel :: Either ApiRequestError Relation
rel = note (NoRelationBetween parentNodeTable name)
$ findRelation schema name parentNodeTable relationDetail
where
findRelation s nodeTableName parentNodeTableName Nothing =
find (\r ->
s == tableSchema (relTable r) && -- match schema for relation table
s == tableSchema (relFTable r) && -- match schema for relation foriegn table
(
-- (request) => projects { ..., clients{...} }
-- will match
-- (relation type) => parent
-- (entity) => clients {id}
-- (foriegn entity) => projects {client_id}
(
nodeTableName == tableName (relTable r) && -- match relation table name
parentNodeTableName == tableName (relFTable r) -- match relation foreign table name
) ||
-- (request) => projects { ..., client_id{...} }
-- will match
-- (relation type) => parent
-- (entity) => clients {id}
-- (foriegn entity) => projects {client_id}
(
parentNodeTableName == tableName (relFTable r) &&
length (relFColumns r) == 1 &&
nodeTableName `colMatches` (colName . unsafeHead . relFColumns) r
)
-- (request) => project_id { ..., client_id{...} }
-- will match
-- (relation type) => parent
-- (entity) => clients {id}
-- (foriegn entity) => projects {client_id}
-- this case works becasue before reaching this place
-- addRelation will turn project_id to project so the above condition will match
)
) allRelations
findRelation s nodeTableName parentNodeTableName (Just rd) =
find (\r ->
s == tableSchema (relTable r) && -- match schema for relation table
s == tableSchema (relFTable r) && -- match schema for relation foriegn table
(
-- (request) => clients { ..., project.client_id{...} }
-- will match
-- (relation type) => parent
-- (entity) => clients {id}
-- (foriegn entity) => projects {client_id}
(
nodeTableName == tableName (relTable r) && -- match relation table name
parentNodeTableName == tableName (relFTable r) && -- && -- match relation foreign table name
length (relColumns r) == 1 &&
rd == (colName . unsafeHead . relColumns) r
)
||
-- (request) => tasks { ..., users.tasks_users{...} }
-- will match
-- (relation type) => many
-- (entity) => users
-- (foriegn entity) => tasks
(
relType r == Many &&
nodeTableName == tableName (relTable r) && -- match relation table name
parentNodeTableName == tableName (relFTable r) && -- match relation foreign table name
rd == tableName (fromJust (relLTable r))
)
)
) allRelations
n `colMatches` rc = (toS ("^" <> rc <> "_?(?:|[iI][dD]|[fF][kK])$") :: BS.ByteString) =~ (toS n :: BS.ByteString)
addRel :: (ReadQuery, (NodeName, Maybe Relation, Maybe Alias, Maybe RelationDetail)) -> Relation -> (ReadQuery, (NodeName, Maybe Relation, Maybe Alias, Maybe RelationDetail))
addRel (query', (n, _, a, _)) r = (query' {from=fromRelation}, (n, Just r, a, Nothing))
where fromRelation = map (\t -> if t == n then tableName (relTable r) else t) (from query')
_ -> n' <$> updateForest (Just (n' forest))
where
n' = Node (query, (name, Just r, alias, Nothing))
t = Table schema name Nothing True -- !!! TODO find another way to get the table from the query
r = Relation t [] t [] Root Nothing Nothing Nothing
where
updateForest :: Maybe ReadRequest -> Either ApiRequestError [ReadRequest]
updateForest n = mapM (addRelations schema allRelations n) forest
addJoinFilters :: Schema -> ReadRequest -> Either ApiRequestError ReadRequest
addJoinFilters schema (Node node@(query, nodeProps@(_, relation, _, _)) forest) =
case relation of
Just Relation{relType=Root} -> Node node <$> updatedForest -- this is the root node
Just rel@Relation{relType=Parent} -> Node (augmentQuery rel, nodeProps) <$> updatedForest
Just rel@Relation{relType=Child} -> Node (augmentQuery rel, nodeProps) <$> updatedForest
Just rel@Relation{relType=Many, relLTable=(Just linkTable)} ->
let rq = augmentQuery rel in
Node (rq{from=tableName linkTable:from rq}, nodeProps) <$> updatedForest
_ -> Left UnknownRelation
where
updatedForest = mapM (addJoinFilters schema) forest
augmentQuery rel = foldr addFilterToReadQuery query (getJoinFilters rel)
addFilterToReadQuery flt rq@Select{where_=lf} = rq{where_=addFilterToLogicForest flt lf}::ReadQuery
getJoinFilters :: Relation -> [Filter]
getJoinFilters (Relation t cols ft fcs typ lt lc1 lc2) =
case typ of
Child -> zipWith (toFilter tN ftN) cols fcs
Parent -> zipWith (toFilter tN ftN) cols fcs
Many -> zipWith (toFilter tN ltN) cols (fromMaybe [] lc1) ++ zipWith (toFilter ftN ltN) fcs (fromMaybe [] lc2)
Root -> undefined --error "undefined getJoinFilters"
where
s = if typ == Parent then "" else tableSchema t
tN = tableName t
ftN = tableName ft
ltN = fromMaybe "" (tableName <$> lt)
toFilter :: Text -> Text -> Column -> Column -> Filter
toFilter tb ftb c fc = Filter (colName c, Nothing) (OpExpr False (Join (QualifiedIdentifier s tb) (ForeignKey fc{colTable=(colTable fc){tableName=ftb}})))
addFiltersOrdersRanges :: ApiRequest -> Either ApiRequestError (ReadRequest -> ReadRequest)
addFiltersOrdersRanges apiRequest = foldr1 (liftA2 (.)) [
flip (foldr addFilter) <$> filters,
flip (foldr addOrder) <$> orders,
flip (foldr addRange) <$> ranges,
flip (foldr addLogicTree) <$> logicForest
]
{-
The esence of what is going on above is that we are composing tree functions
of type (ReadRequest->ReadRequest) that are in (Either ParseError a) context
-}
where
filters :: Either ApiRequestError [(EmbedPath, Filter)]
filters = mapM pRequestFilter flts
logicForest :: Either ApiRequestError [(EmbedPath, LogicTree)]
logicForest = mapM pRequestLogicTree logFrst
action = iAction apiRequest
-- there can be no filters on the root table when we are doing insert/update/delete
(flts, logFrst) =
case action of
ActionInvoke _ -> (iFilters apiRequest, iLogic apiRequest)
ActionRead -> (iFilters apiRequest, iLogic apiRequest)
_ -> join (***) (filter (( "." `isInfixOf` ) . fst)) (iFilters apiRequest, iLogic apiRequest)
orders :: Either ApiRequestError [(EmbedPath, [OrderTerm])]
orders = mapM pRequestOrder $ iOrder apiRequest
ranges :: Either ApiRequestError [(EmbedPath, NonnegRange)]
ranges = mapM pRequestRange $ M.toList $ iRange apiRequest
addFilterToNode :: Filter -> ReadRequest -> ReadRequest
addFilterToNode flt (Node (q@Select {where_=lf}, i) f) = Node (q{where_=addFilterToLogicForest flt lf}::ReadQuery, i) f
addFilter :: (EmbedPath, Filter) -> ReadRequest -> ReadRequest
addFilter = addProperty addFilterToNode
addOrderToNode :: [OrderTerm] -> ReadRequest -> ReadRequest
addOrderToNode o (Node (q,i) f) = Node (q{order=Just o}, i) f
addOrder :: (EmbedPath, [OrderTerm]) -> ReadRequest -> ReadRequest
addOrder = addProperty addOrderToNode
addRangeToNode :: NonnegRange -> ReadRequest -> ReadRequest
addRangeToNode r (Node (q,i) f) = Node (q{range_=r}, i) f
addRange :: (EmbedPath, NonnegRange) -> ReadRequest -> ReadRequest
addRange = addProperty addRangeToNode
addLogicTreeToNode :: LogicTree -> ReadRequest -> ReadRequest
addLogicTreeToNode t (Node (q@Select{where_=lf},i) f) = Node (q{where_=t:lf}::ReadQuery, i) f
addLogicTree :: (EmbedPath, LogicTree) -> ReadRequest -> ReadRequest
addLogicTree = addProperty addLogicTreeToNode
addProperty :: (a -> ReadRequest -> ReadRequest) -> (EmbedPath, a) -> ReadRequest -> ReadRequest
addProperty f ([], a) n = f a n
addProperty f (path, a) (Node rn forest) =
case targetNode of
Nothing -> Node rn forest -- the property is silenty dropped in the Request does not contain the required path
Just tn -> Node rn (addProperty f (remainingPath, a) tn:restForest)
where
targetNodeName:remainingPath = path
(targetNode,restForest) = splitForest targetNodeName forest
splitForest :: NodeName -> Forest ReadNode -> (Maybe ReadRequest, Forest ReadNode)
splitForest name forst =
case maybeNode of
Nothing -> (Nothing,forest)
Just node -> (Just node, delete node forest)
where
maybeNode :: Maybe ReadRequest
maybeNode = find fnd forst
where
fnd :: ReadRequest -> Bool
fnd (Node (_,(n,_,_,_)) _) = n == name
-- in a relation where one of the tables mathces "TableName"
-- replace the name to that table with pg_source
-- this "fake" relations is needed so that in a mutate query
-- we can look a the "returning *" part which is wrapped with a "with"
-- as just another table that has relations with other tables
toSourceRelation :: TableName -> Relation -> Maybe Relation
toSourceRelation mt r@(Relation t _ ft _ _ rt _ _)
| mt == tableName t = Just $ r {relTable=t {tableName=sourceCTEName}}
| mt == tableName ft = Just $ r {relFTable=t {tableName=sourceCTEName}}
| Just mt == (tableName <$> rt) = Just $ r {relLTable=(\tbl -> tbl {tableName=sourceCTEName}) <$> rt}
| otherwise = Nothing
mutateRequest :: ApiRequest -> [FieldName] -> Either Response MutateRequest
mutateRequest apiRequest fldNames = mapLeft apiRequestError $
case action of
ActionCreate -> Right $ Insert rootTableName payload returnings
ActionUpdate -> Update rootTableName <$> pure payload <*> combinedLogic <*> pure returnings
ActionDelete -> Delete rootTableName <$> combinedLogic <*> pure returnings
_ -> Left UnsupportedVerb
where
action = iAction apiRequest
payload = fromJust $ iPayload apiRequest
rootTableName = -- TODO: Make it safe
let target = iTarget apiRequest in
case target of
(TargetIdent (QualifiedIdentifier _ t) ) -> t
_ -> undefined
returnings = if iPreferRepresentation apiRequest == None then [] else fldNames
filters = map snd <$> mapM pRequestFilter mutateFilters
logic = map snd <$> mapM pRequestLogicTree logicFilters
combinedLogic = foldr addFilterToLogicForest <$> logic <*> filters
-- update/delete filters can be only on the root table
(mutateFilters, logicFilters) = join (***) onlyRoot (iFilters apiRequest, iLogic apiRequest)
onlyRoot = filter (not . ( "." `isInfixOf` ) . fst)
readRpcRequest :: ApiRequest -> Either Response [RpcQParam]
readRpcRequest apiRequest = mapLeft apiRequestError rpcQParams
where
rpcQParams = mapM pRequestRpcQParam $ iRpcQParams apiRequest
fieldNames :: ReadRequest -> [FieldName]
fieldNames (Node (sel, _) forest) =
map (fst . view _1) (select sel) ++ map colName fks
where
fks = concatMap (fromMaybe [] . f) forest
f (Node (_, (_, Just Relation{relFColumns=cols, relType=Parent}, _, _)) _) = Just cols
f _ = Nothing
-- Traditional filters(e.g. id=eq.1) are added as root nodes of the LogicTree
-- they are later concatenated with AND in the QueryBuilder
addFilterToLogicForest :: Filter -> [LogicTree] -> [LogicTree]
addFilterToLogicForest flt lf = Stmnt flt : lf
|
ruslantalpa/postgrest
|
src/PostgREST/DbRequestBuilder.hs
|
mit
| 16,405
| 0
| 28
| 4,700
| 4,236
| 2,263
| 1,973
| 241
| 10
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Graphics.Urho3D.Network.Network(
Network
, networkContext
, networkConnect
, networkDisconnect
, networkStartServer
, networkStopServer
, networkBroadcastMessage
, networkSetUpdateFps
, networkSetSimulatedLatency
, networkSetSimulatedPacketLoss
, networkGetServerConnection
, networkGetClientConnections
, networkIsServerRunning
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
import Data.Monoid
import Data.Vector (Vector)
import Foreign
import Foreign.C.String
import Graphics.Urho3D.Container.ForeignVector
import Graphics.Urho3D.Container.Ptr
import Graphics.Urho3D.Core.Context
import Graphics.Urho3D.Core.Object
import Graphics.Urho3D.Monad
import Graphics.Urho3D.Network.Connection
import Graphics.Urho3D.Network.Internal.Network
import Graphics.Urho3D.Parent
import Graphics.Urho3D.Scene.Scene
import qualified Data.ByteString as BS
import qualified Data.ByteString.Unsafe as BS
C.context (C.cppCtx
<> networkCntx
<> contextContext
<> sceneContext
<> connectionContext
<> objectContext)
C.include "<Urho3D/Network/Network.h>"
C.using "namespace Urho3D"
networkContext :: C.Context
networkContext = networkCntx <> objectContext
C.verbatim "typedef Vector<SharedPtr<Connection> > VectorSharedPtrConnection;"
deriveParent ''Object ''Network
instance Subsystem Network where
getSubsystemImpl ptr = [C.exp| Network* { $(Object* ptr)->GetSubsystem<Network>() } |]
-- | Connect to a server using UDP protocol. Return true if connection process successfully started.
-- bool Connect(const String& address, unsigned short port, Scene* scene, const VariantMap& identity = Variant::emptyVariantMap);
networkConnect :: (Parent Network a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Network' or ancestor
-> String -- ^ address
-> Word -- ^ Port
-> Ptr Scene -- ^ Scene
-> m Bool
networkConnect ptr address port pscene = liftIO $ withCString address $ \address' -> do
let ptr' = parentPointer ptr
port' = fromIntegral port
toBool <$> [C.exp| int { (int)$(Network* ptr')->Connect(String($(const char* address')), $(unsigned short port'), $(Scene* pscene)) } |]
-- | Disconnect the connection to the server. If wait time is non-zero, will block while waiting for disconnect to finish.
-- void Disconnect(int waitMSec = 0);
networkDisconnect :: (Parent Network a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Network' or ancestor
-> Int -- ^ Wait milliseconds default 0
-> m ()
networkDisconnect ptr wmsec = liftIO $ do
let ptr' = parentPointer ptr
wmsec' = fromIntegral wmsec
[C.exp| void { $(Network* ptr')->Disconnect($(int wmsec')) } |]
-- | Start a server on a port using UDP protocol. Return true if successful.
-- bool StartServer(unsigned short port);
networkStartServer :: (Parent Network a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Network' or ancestor
-> Word -- ^ Port
-> m Bool
networkStartServer ptr port = liftIO $ do
let ptr' = parentPointer ptr
port' = fromIntegral port
toBool <$> [C.exp| int { (int)$(Network* ptr')->StartServer($(int port')) } |]
-- | Stop the server.
-- void StopServer();
networkStopServer :: (Parent Network a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Network' or ancestor
-> m ()
networkStopServer ptr = liftIO $ do
let ptr' = parentPointer ptr
[C.exp| void { $(Network* ptr')->StopServer() } |]
-- | Broadcast a message with content ID to all client connections.
-- void BroadcastMessage
-- (int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes, unsigned contentID = 0);
networkBroadcastMessage :: (Parent Network a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Network' or ancestor
-> Int -- ^ Message id
-> Bool -- ^ Reliable flag
-> Bool -- ^ Keep order flag
-> BS.ByteString -- ^ Buffer
-> Word -- ^ Content ID (default 0)
-> m ()
networkBroadcastMessage ptr msgID reliable inOrder bs contentID = liftIO $ BS.unsafeUseAsCStringLen bs $ \(bsptr, l) -> do
let ptr' = parentPointer ptr
msgID' = fromIntegral msgID
reliable' = fromBool reliable
inOrder' = fromBool inOrder
contentID' = fromIntegral contentID
l' = fromIntegral l
bsptr' = castPtr bsptr
[C.exp| void { $(Network* ptr')->BroadcastMessage($(int msgID'), $(int reliable') != 0, $(int inOrder') != 0, $(const unsigned char* bsptr'), $(unsigned int l'), $(unsigned int contentID')) } |]
-- | Broadcast a remote event to all client connections.
-- void BroadcastRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
-- | Broadcast a remote event to all client connections in a specific scene.
-- void BroadcastRemoteEvent
-- (Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
-- | Broadcast a remote event with the specified node as a sender. Is sent to all client connections in the node's scene.
-- void BroadcastRemoteEvent
-- (Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
-- | Set network update FPS.
-- void SetUpdateFps(int fps);
networkSetUpdateFps :: (Parent Network a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Network' or ancestor
-> Int -- ^ FPS
-> m ()
networkSetUpdateFps ptr fps = liftIO $ do
let ptr' = parentPointer ptr
fps' = fromIntegral fps
[C.exp| void { $(Network* ptr')->SetUpdateFps($(int fps')) } |]
-- | Set simulated latency in milliseconds. This adds a fixed delay before sending each packet.
-- void SetSimulatedLatency(int ms);
networkSetSimulatedLatency :: (Parent Network a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Network' or ancestor
-> Int -- ^ ms
-> m ()
networkSetSimulatedLatency ptr ms = liftIO $ do
let ptr' = parentPointer ptr
ms' = fromIntegral ms
[C.exp| void { $(Network* ptr')->SetSimulatedLatency($(int ms')) } |]
-- | Set simulated packet loss probability between 0.0 - 1.0.
-- void SetSimulatedPacketLoss(float probability);
networkSetSimulatedPacketLoss :: (Parent Network a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Network' or ancestor
-> Float -- ^ probality
-> m ()
networkSetSimulatedPacketLoss ptr pb = liftIO $ do
let ptr' = parentPointer ptr
pb' = realToFrac pb
[C.exp| void { $(Network* ptr')->SetSimulatedPacketLoss($(float pb')) } |]
-- | Register a remote event as allowed to be received. There is also a fixed blacklist of events that can not be allowed in any case, such as ConsoleCommand.
-- void RegisterRemoteEvent(StringHash eventType);
-- | Unregister a remote event as allowed to received.
-- void UnregisterRemoteEvent(StringHash eventType);
-- | Unregister all remote events.
-- void UnregisterAllRemoteEvents();
-- | Set the package download cache directory.
-- void SetPackageCacheDir(const String& path);
-- | Trigger all client connections in the specified scene to download a package file from the server. Can be used to download additional resource packages when clients are already joined in the scene. The package must have been added as a requirement to the scene, or else the eventual download will fail.
-- void SendPackageToClients(Scene* scene, PackageFile* package);
-- | Perform an HTTP request to the specified URL. Empty verb defaults to a GET request. Return a request object which can be used to read the response data.
-- SharedPtr<HttpRequest> MakeHttpRequest
-- (const String& url, const String& verb = String::EMPTY, const Vector<String>& headers = Vector<String>(),
-- const String& postData = String::EMPTY);
-- | Return network update FPS.
-- int GetUpdateFps() const { return updateFps_; }
-- | Return simulated latency in milliseconds.
-- int GetSimulatedLatency() const { return simulatedLatency_; }
-- | Return simulated packet loss probability.
-- float GetSimulatedPacketLoss() const { return simulatedPacketLoss_; }
-- | Return the connection to the server. Null if not connected.
-- Connection* GetServerConnection() const;
networkGetServerConnection :: (Parent Network a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Network' or ancestor
-> m (Maybe (Ptr Connection))
networkGetServerConnection ptr = liftIO $ do
let ptr' = parentPointer ptr
wrapNullPtr <$> [C.exp| Connection* { $(Network* ptr')->GetServerConnection() } |]
-- | Return all client connections.
-- Vector<SharedPtr<Connection> > GetClientConnections() const;
networkGetClientConnections :: (Parent Network a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Network' or ancestor
-> m (Vector (SharedPtr Connection))
networkGetClientConnections ptr = liftIO $ do
let ptr' = parentPointer ptr
resptr <- [C.exp| VectorSharedPtrConnection* {
new VectorSharedPtrConnection($(Network* ptr')->GetClientConnections()) }
|]
v <- peekForeignVectorAs resptr
[C.exp| void { delete $(VectorSharedPtrConnection* resptr) }|]
pure v
-- | Return whether the server is running.
-- bool IsServerRunning() const;
networkIsServerRunning :: (Parent Network a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Network' or ancestor
-> m Bool
networkIsServerRunning ptr = liftIO $ do
let ptr' = parentPointer ptr
toBool <$> [C.exp| int { (int)$(Network* ptr')->IsServerRunning() } |]
-- | Return whether a remote event is allowed to be received.
-- bool CheckRemoteEvent(StringHash eventType) const;
-- | Return the package download cache directory.
-- const String& GetPackageCacheDir() const { return packageCacheDir_; }
|
Teaspot-Studio/Urho3D-Haskell
|
src/Graphics/Urho3D/Network/Network.hs
|
mit
| 9,603
| 0
| 13
| 1,609
| 1,420
| 794
| 626
| -1
| -1
|
module Substitution where
import Data.Map as Map
import Data.Set as Set
----------------------------------------------------------------------------
-- Substitutions
----------------------------------------------------------------------------
type Subst = Map.Map TypeVar Type
nullSubst = Map.empty
class Types t where
apply :: Subst -> t -> t
ftv :: t -> Set.Set TypeVar
instance Types a => Types [a] where
apply s = map (apply s)
ftv = Set.unions $ map ftv
instance Types Monotype where
ftv (TVar t) = Set.singleton t
ftv (TApp t1 t2) = Set.union (ftv t1) (ftv t2)
ftv (TSeq ts) = ftv ts
ftv (TEffectRow es (Just v)) = Set.singleton v
ftv (TFieldRow fs mv) =
case mv of
Just v -> Set.insert v $ ftv fs
Nothing -> ftv fs
ftv (TDotted t) = ftv t
ftv _ = Set.empty
apply sub (TVar t) =
case Map.lookup t sub of
Nothing -> (TVar t)
Just t' -> t'
apply sub (TApp t1 t2) =
case apply sub t1 of
TSeq t1s ->
case apply sub t2 of
TSeq t2s ->
if length t1s == length t2s
then TSeq $ zipWith TApp t1s t2s
else error "somehow the variables in a type application were substituted with sequences of different lengths"
t2' -> TSeq $ map (\st -> TApp st t2') t1s
t1' ->
case apply sub t2 of
TSeq t2s -> TSeq $ map (TApp t1') t2s
t2' -> TApp t1' t2'
TApp (apply sub t1) (apply sub t2)
apply sub (TSeq ts) =
flatten $ apply sub ts
where flatten (TSeq ts':ts) = ts' ++ flatten ts
flatten (t:ts) = t : flatten ts
flatten [] = []
apply sub (TEffectRow es (Just v)) =
case Map.lookup v sub of
Nothing -> TEffectRow es (Just v)
Just (TEffectRow es' v') -> TEffectRow (es ++ es') v'
_ -> error "somehow got non-effect-row substituted for effect row variable"
apply sub (TFieldRow fs (Just v)) =
case Map.lookup v sub of
Nothing -> TFieldRow (apply sub fs) (Just v)
Just (TFieldRow fs' v') -> TFieldRow (apply sub fs ++ fs') v'
_ -> error "somehow got non-field-row substituted for field row variable"
apply sub (TFieldRow fs Nothing) =
TFieldRow (apply sub fs) Nothing
apply sub (TDotted t) =
case apply sub t of
TSeq ts -> TSeq ts
TDotted t' -> TDotted t'
t' -> TDotted t'
apply sub t = t
instance Types Polytype where
ftv (Poly ns t) = ftv t `Set.difference` Set.fromList ns
apply sub (Poly ns t) = Poly ns (apply (foldr Map.delete sub ns) t)
compose :: Subst -> Subst -> Subst
s1 `compose` s2 = Map.map (apply s1) s2 `Map.union` s1
|
robertkleffner/gruit
|
src/Substitution.hs
|
mit
| 2,881
| 10
| 17
| 997
| 712
| 393
| 319
| -1
| -1
|
module DivisionOfLabor.Worker where
import qualified Data.Vector as V
import Data.Vector (Vector)
import DivisionOfLabor.Board
import DivisionOfLabor.Resource
data Worker = Worker
{ location :: Maybe BoardLocation
, cargo :: Vector (Maybe (Resource, Int))
, upgrades :: [Upgrade]
, speed :: Int
} deriving (Eq, Show)
type Upgrade = Int
scout :: Worker
scout = undefined
settler :: Worker
settler = undefined
standard :: Worker
standard = undefined
|
benweitzman/DivisionOfLabor
|
src/lib/DivisionOfLabor/Worker.hs
|
mit
| 473
| 0
| 12
| 90
| 135
| 82
| 53
| 18
| 1
|
{-# LANGUAGE DeriveGeneric, DeriveDataTypeable, TypeFamilies, Arrows, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Server.Game.Player(
PlayerMsg(..)
, player
, module P
) where
import Core
import GHC.Generics (Generic)
import Control.DeepSeq
import Data.Typeable
import Prelude hiding (id, (.))
import FRP.Netwire
import Game.Player as P
import Game.World
import Network.Protocol.Message
data PlayerMsg = PlayerMsgStub
deriving (Typeable, Generic)
instance NFData PlayerMsg
instance Messagable PlayerId where
type MessageType PlayerId = PlayerMsg
fromCounter = PlayerId
toCounter = unPlayerId
player :: Player -> GameActor PlayerId World Player
player startPlayer = makeIndexed simPlayer
where
startPlayer' pid = startPlayer { playerId = pid }
simPlayer pid = loop $ proc (w, p) -> do
p1 <- processMessages processMessage pid . delay (startPlayer' pid) -< p
-- Player requests world info, send respond
worldRequest <- singlePlayerNetMessage isPlayerRequestWorld -< playerName p1
sendNetMessage -< const (playerName p1, worldInfoMsg w) <$> worldRequest
-- Player requests info about himself
playerRequest <- singlePlayerNetMessage isPlayerRequestEnviroment -< playerName p1
sendNetMessage -< const (playerName p1, playerInfoMsg p1) <$> playerRequest
forceNF -< (p1, p1)
processMessage p msg = case msg of
PlayerMsgStub -> p -- TODO
|
NCrashed/sinister
|
src/server/Server/Game/Player.hs
|
mit
| 1,457
| 1
| 16
| 284
| 359
| 192
| 167
| 34
| 1
|
module Main where
import Control.Monad (msum)
import Control.Monad.Logger (runStdoutLoggingT)
import Happstack.Server
import Database.Persist.Postgresql
import App.Types
import Config.DB
import Handler.Agreement
import Handler.Applications
import Handler.Doors
import Handler.DoorKeys
import Handler.Equipment
import Handler.Fob
import Handler.FobAssignments
import Handler.Memberships
import Handler.People
import Handler.Open
import Handler.Style
import Handler.Welcome
import Handler.Helpers.Routing
import Model.DB
main :: IO ()
main = do
connString <- loadDBConfig
withPostgresqlPool connString 5 $ \pool -> do
runStdoutLoggingT $ runSqlPool (runMigration migrateAll) pool
putStrLn $ "Starting server on port " ++ (show $ 8000)
simpleHTTP nullConf $ runApp pool app
app :: App Response
app = do
decodeBody $ defaultBodyPolicy "/tmp/" 4096 4096 4096
msum [
dir "open" open
, dir "doors" doors
, dir "doorKeys" doorKeys
, dir "equipment" equipment
, dir "people" people
, dir "people" (entityId $ \ent ->
msum [ dir "applications" $ applications ent
, dir "membership" $ memberships ent
])
, dir "agreements" agreements
, dir "fobs" fobs
, dir "fobAssignments" fobAssignments
, dir "style" style
, welcome
]
instance BackendHost IO where
runDB action = do
connString <- loadDBConfig
withPostgresqlPool connString 1 $ \pool -> do
runBackendPool pool action
|
flipstone/glados
|
src/Main.hs
|
mit
| 1,488
| 0
| 16
| 310
| 414
| 214
| 200
| 50
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Main ( main ) where
import Data.Text (Text)
import qualified CMark
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Maybe as Maybe
import qualified Data.Ord as Ord
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import qualified Data.Time as Time
import qualified System.Directory as Directory
import qualified System.FilePath as FilePath
import qualified System.IO as IO
import qualified Text.Read as Read
main :: IO ()
main = do
let
input = "content" :: FilePath
output = "_site" :: FilePath
-- Clean the output directory to avoid stale files.
Directory.removePathForcibly output
-- Create the expected hierarchy in the output directory.
mapM_
createDirectoryAt
[ [output]
, [output, "images"]
, [output, "issues"]
, [output, "styles"]
, [output, "surveys"]
]
-- Copy over static files.
mapM_
(copyFileAt input output)
[ ["images", "favicon.ico"]
, ["images", "twitter-card.png"]
, ["styles", "bootstrap-4-3-1.css"]
]
-- Read includes and inject them into the context.
form <- readFileAt [input, "includes", "form.html"]
logo <- readFileAt [input, "includes", "logo.svg"]
let
context :: Context
context =
[ ("", "$")
, ("baseUrl", "https://haskellweekly.news")
, ("form", form)
, ("logo", logo)
]
-- Read templates.
atomEntryTemplate <- readFileAt [input, "templates", "atom-entry.xml"]
baseTemplate <- readFileAt [input, "templates", "base.html"]
issueTemplate <- readFileAt [input, "templates", "issue.html"]
rssItemTemplate <- readFileAt [input, "templates", "rss-item.xml"]
snippetTemplate <- readFileAt [input, "templates", "snippet.html"]
surveyTemplate <- readFileAt [input, "templates", "survey.html"]
-- Read page templates.
advertisingTemplate <- readFileAt [input, "pages", "advertising.html"]
atomTemplate <- readFileAt [input, "pages", "atom.xml"]
indexTemplate <- readFileAt [input, "pages", "index.html"]
rssTemplate <- readFileAt [input, "pages", "rss.xml"]
-- Read survey templates.
surveyFiles <- listDirectoryAt [input, "surveys"]
surveysByYear <- getSurveysByYear input surveyFiles
-- Load issues.
issueFiles <- listDirectoryAt [input, "issues"]
issuesByNumber <- getIssuesByNumber input issueFiles
-- Parse issues.
let
issues = sortIssues (Maybe.mapMaybe parseIssue issuesByNumber)
issueMap = Map.fromListWith
(\ old new -> error ("duplicate issue numbers: " <> show (old, new)))
(map (\ issue -> (issueNumber issue, issue)) issues)
recentIssues = take 7 issues
-- Create issue pages.
mapM_ (createIssue output baseTemplate issueTemplate context issueMap) issues
-- Create feeds.
do
contents <- renderAtom atomTemplate atomEntryTemplate context recentIssues
writeFileAt [output, "haskell-weekly.atom"] contents
do
contents <- renderRss rssTemplate rssItemTemplate context recentIssues
writeFileAt [output, "haskell-weekly.rss"] contents
-- Create advertising page.
do
contents <- renderAdvertising baseTemplate advertisingTemplate context
writeFileAt [output, "advertising.html"] contents
-- Create survey pages.
mapM_ (createSurvey output baseTemplate surveyTemplate context) surveysByYear
-- Create home page.
do
contents <- renderIndex
baseTemplate
indexTemplate
snippetTemplate
context
issues
writeFileAt [output, "index.html"] contents
getSurveysByYear :: FilePath -> [FilePath] -> IO [(Integer, Text)]
getSurveysByYear input =
mapM (getSurvey input)
. Maybe.mapMaybe (Read.readMaybe . FilePath.takeBaseName)
. filter (hasExtension "html")
getSurvey :: FilePath -> Integer -> IO (Integer, Text)
getSurvey input year = do
template <- readFileAt
[input, "surveys", FilePath.addExtension (show year) "html"]
pure (year, template)
getIssuesByNumber :: FilePath -> [FilePath] -> IO [(Integer, Text)]
getIssuesByNumber input =
mapM (getIssue input)
. Maybe.mapMaybe (Read.readMaybe . FilePath.takeBaseName)
. filter (hasExtension "markdown")
getIssue :: FilePath -> Integer -> IO (Integer, Text)
getIssue input number = do
contents <- readFileAt
[input, "issues", FilePath.addExtension (show number) "markdown"]
pure (number, contents)
createIssue :: FilePath -> Text -> Text -> Context -> Map.Map Integer Issue -> Issue -> IO ()
createIssue output baseTemplate issueTemplate context issueMap issue = do
let
number = show (issueNumber issue)
next = Map.lookup (issueNumber issue + 1) issueMap
previous = Map.lookup (issueNumber issue - 1) issueMap
contents <- renderIssue baseTemplate issueTemplate context issue next previous
writeFileAt [output, "issues", FilePath.addExtension number "html"] contents
createSurvey :: FilePath -> Text -> Text -> Context -> (Integer, Text) -> IO ()
createSurvey output baseTemplate surveyTemplate context (year, template) = do
contents <- renderSurvey baseTemplate surveyTemplate template context year
writeFileAt
[output, "surveys", FilePath.addExtension (show year) "html"]
contents
-- Types
data Issue = Issue
{ issueNumber :: Integer
, issueDay :: Time.Day
, issueContents :: Text
} deriving Show
type Context = [(Text, Text)]
data Piece
= Literal Text
| Variable Text
-- Business helpers
commonMark :: Text -> Text
commonMark = CMark.commonmarkToHtml [CMark.optNormalize, CMark.optSmart]
escapeHtml :: Text -> Text
escapeHtml = Text.replace "<" "<" . Text.replace "&" "&"
getDay :: Text -> Maybe Time.Day
getDay meta = case Text.words meta of
["<!--", day, "-->"] -> parseDay "%Y-%m-%d" day
_ -> Nothing
isoDay :: Time.Day -> Text
isoDay = formatDay "%Y-%m-%dT00:00:00Z"
issueContext :: Issue -> Context
issueContext issue = [("number", showText (issueNumber issue))]
issueSummary :: Monad m => Issue -> m Text
issueSummary =
renderTemplate
"Issue $number$ of Haskell Weekly, a free email newsletter about the \
\Haskell programming language."
. issueContext
issueTitle :: Monad m => Issue -> m Text
issueTitle = renderTemplate "Issue $number$" . issueContext
issueUrl :: Monad m => Issue -> m Text
issueUrl = renderTemplate "/issues/$number$.html" . issueContext
lastUpdated :: [Issue] -> Time.Day
lastUpdated =
Maybe.fromMaybe (Time.fromGregorian 1970 1 1)
. Maybe.listToMaybe
. map issueDay
pageTitle :: Monad m => Maybe Text -> m Text
pageTitle maybeTitle = case maybeTitle of
Nothing -> pure "Haskell Weekly"
Just title -> renderTemplate "$title$ :: Haskell Weekly" [("title", title)]
parseIssue :: (Integer, Text) -> Maybe Issue
parseIssue (number, contents) = do
let (meta, body) = Text.breakOn "\n" contents
day <- getDay meta
Just Issue
{ issueNumber = number
, issueDay = day
, issueContents = commonMark body
}
prettyDay :: Time.Day -> Text
prettyDay = formatDay "%Y-%m-%d"
rfcDay :: Time.Day -> Text
rfcDay = formatDay "%a, %d %b %Y 00:00:00 GMT"
sortIssues :: [Issue] -> [Issue]
sortIssues = List.sortBy (Ord.comparing (Ord.Down . issueDay))
surveyContext :: Integer -> Context
surveyContext year = [("year", showText year)]
surveySummary :: Monad m => Integer -> m Text
surveySummary =
renderTemplate
"The $year$ survey of Haskell users by Haskell Weekly, a free email \
\newsletter about the Haskell programming language."
. surveyContext
surveyTitle :: Monad m => Integer -> m Text
surveyTitle = renderTemplate "$year$ survey" . surveyContext
surveyUrl :: Monad m => Integer -> m Text
surveyUrl = renderTemplate "/surveys/$year$.html" . surveyContext
-- Rendering helpers
renderAdvertising :: Monad m => Text -> Text -> Context -> m Text
renderAdvertising template advertisingTemplate context = do
body <- renderTemplate advertisingTemplate context
title <- pageTitle (Just "Advertising")
renderTemplate
template
(context
++ [ ("body", body)
, ("summary", "Information about advertising with Haskell Weekly.")
, ("title", title)
, ("url", "/advertising.html")
]
)
renderAtom :: Monad m => Text -> Text -> Context -> [Issue] -> m Text
renderAtom template entryTemplate context issues = do
entries <- mapM (renderAtomEntry entryTemplate context) issues
renderTemplate
template
(context
++ [ ("entries", mconcat entries)
, ("updated", isoDay (lastUpdated issues))
]
)
renderAtomEntry :: Monad m => Text -> Context -> Issue -> m Text
renderAtomEntry template context issue = renderTemplate
template
(context
++ [ ("content", escapeHtml (issueContents issue))
, ("number", showText (issueNumber issue))
, ("updated", isoDay (issueDay issue))
]
)
renderIndex :: Monad m => Text -> Text -> Text -> Context -> [Issue] -> m Text
renderIndex baseTemplate template snippetTemplate context issues = do
snippets <- mapM (renderSnippet snippetTemplate context) issues
body <- renderTemplate template (("issues", mconcat snippets) : context)
let
summary :: Text
summary
= "Haskell Weekly is a free email newsletter about the Haskell \
\programming language. Each issue features several hand-picked links \
\to interesting content about Haskell from around the web."
title <- pageTitle Nothing
renderTemplate
baseTemplate
(context
++ [("body", body), ("summary", summary), ("title", title), ("url", "")]
)
renderIssue :: Monad m => Text -> Text -> Context -> Issue -> Maybe Issue -> Maybe Issue -> m Text
renderIssue baseTemplate issueTemplate context issue next previous = do
partialTitle <- issueTitle issue
body <- renderTemplate
issueTemplate
(context
++ [ ("body", issueContents issue)
, ("date", prettyDay (issueDay issue))
, ("nextClass", maybe "disabled" (const "") next)
, ("nextHref", maybe "#" (\ i -> "/issues/" <> showText (issueNumber i) <> ".html") next)
, ("number", showText (issueNumber issue))
, ("previousClass", maybe "disabled" (const "") previous)
, ("previousHref", maybe "#" (\ i -> "/issues/" <> showText (issueNumber i) <> ".html") previous)
, ("title", partialTitle)
]
)
summary <- issueSummary issue
url <- issueUrl issue
title <- pageTitle (Just partialTitle)
renderTemplate
baseTemplate
(context
++ [("body", body), ("summary", summary), ("title", title), ("url", url)]
)
renderPiece :: Monad m => Context -> Piece -> m Text
renderPiece context piece = case piece of
Literal text -> pure text
Variable name -> case lookup name context of
Nothing -> fail ("unknown variable: " ++ show name)
Just value -> pure value
renderPieces :: Monad m => Context -> [Piece] -> m Text
renderPieces context pieces = do
rendered <- mapM (renderPiece context) pieces
pure (mconcat rendered)
renderRss :: Monad m => Text -> Text -> Context -> [Issue] -> m Text
renderRss template itemTemplate context issues = do
items <- mapM (renderRssItem itemTemplate context) issues
renderTemplate template (("items", mconcat items) : context)
renderRssItem :: Monad m => Text -> Context -> Issue -> m Text
renderRssItem template context issue = do
title <- issueTitle issue
url <- issueUrl issue
renderTemplate
template
(context
++ [ ("description", escapeHtml (issueContents issue))
, ("pubDate", rfcDay (issueDay issue))
, ("title", title)
, ("url", url)
]
)
renderSnippet :: Monad m => Text -> Context -> Issue -> m Text
renderSnippet template context issue = do
title <- issueTitle issue
url <- issueUrl issue
renderTemplate
template
(context
++ [("date", prettyDay (issueDay issue)), ("title", title), ("url", url)]
)
renderSurvey :: Monad m => Text -> Text -> Text -> Context -> Integer -> m Text
renderSurvey baseTemplate surveyTemplate template context year = do
partialBody <- renderTemplate template context
partialTitle <- surveyTitle year
body <- renderTemplate
surveyTemplate
(context ++ [("body", partialBody), ("title", partialTitle)])
summary <- surveySummary year
title <- pageTitle (Just partialTitle)
url <- surveyUrl year
renderTemplate
baseTemplate
(context
++ [("body", body), ("summary", summary), ("title", title), ("url", url)]
)
renderTemplate :: Monad m => Text -> Context -> m Text
renderTemplate template context = renderPieces context (toPieces template)
toPieces :: Text -> [Piece]
toPieces = textsToPieces . Text.splitOn "$"
textsToPieces :: [Text] -> [Piece]
textsToPieces chunks = case chunks of
[] -> []
[text] -> [Literal text]
text : name : rest -> Literal text : Variable name : textsToPieces rest
-- Generic helpers
copyFileAt :: FilePath -> FilePath -> [FilePath] -> IO ()
copyFileAt input output path = Directory.copyFile
(FilePath.joinPath (input : path))
(FilePath.joinPath (output : path))
createDirectoryAt :: [FilePath] -> IO ()
createDirectoryAt =
Directory.createDirectoryIfMissing True . FilePath.joinPath
formatDay :: Text -> Time.Day -> Text
formatDay format =
Text.pack . Time.formatTime Time.defaultTimeLocale (Text.unpack format)
hasExtension :: Text -> FilePath -> Bool
hasExtension extension =
(== '.' : Text.unpack extension) . FilePath.takeExtension
listDirectoryAt :: [FilePath] -> IO [FilePath]
listDirectoryAt = Directory.listDirectory . FilePath.joinPath
parseDay :: Text -> Text -> Maybe Time.Day
parseDay format =
Time.parseTimeM False Time.defaultTimeLocale (Text.unpack format)
. Text.unpack
readFileAt :: [FilePath] -> IO Text
readFileAt path = do
handle <- IO.openFile (FilePath.joinPath path) IO.ReadMode
IO.hSetEncoding handle IO.utf8
Text.hGetContents handle
showText :: Show a => a -> Text
showText = Text.pack . show
writeFileAt :: [FilePath] -> Text -> IO ()
writeFileAt path contents = do
handle <- IO.openFile (FilePath.joinPath path) IO.WriteMode
IO.hSetEncoding handle IO.utf8
Text.hPutStr handle contents
IO.hFlush handle
|
haskellweekly/haskellweekly.github.io
|
executables/haskell-weekly.hs
|
mit
| 14,099
| 0
| 20
| 2,735
| 4,362
| 2,263
| 2,099
| 327
| 3
|
module Geometry.Cube
( volume
, area
) where
import qualified Geometry.Cuboid as Cuboid
volume :: Float -> Float
volume side = Cuboid.volume side side sdie
area :: Float -> Float
area side = Cuboid.area side side side side
|
hackrole/learn_haskell
|
haskell-good/ch06/Geometry/Cube.hs
|
mit
| 226
| 0
| 6
| 41
| 76
| 42
| 34
| 8
| 1
|
module Types where
import qualified LLVM.General.AST.Type as T
i8 = T.i8
i16 = T.i16
i32 = T.i32
i64 = T.i64
i128 = T.i128
f16 = T.half
f32 = T.float
f64 = T.double
f128 = T.fp128
ptr = T.ptr
void = T.void
char = i8
cstring = ptr char
array = T.ArrayType
|
waterlink/hgo
|
Types.hs
|
mit
| 262
| 0
| 5
| 58
| 111
| 66
| 45
| 16
| 1
|
module WordTrie (getLongerMatches,
getShorterMatches,
readTrieFromFile,
readTrieFromStdin,
Wordbook) where
import Data.Char (isAlpha, toLower)
import Data.List (isPrefixOf)
import Data.ListTrie.Patricia.Set (empty, insert, lookupPrefix,
toList, TrieSet)
import qualified Data.Text as T (dropWhile, dropWhileEnd, filter, pack, Text, toLower, unpack)
import qualified Data.ListTrie.Patricia.Set as Set (filter)
import Data.Map (Map)
import GHC.IO.Handle.Types (Handle)
import System.IO (hGetContents, hGetLine, hIsEOF, openFile, IOMode(ReadMode), stdin)
type Wordbook = TrieSet Map Char
readIntoTrie :: [String] -> Wordbook -> IO Wordbook
readIntoTrie [] wordbook = do
return wordbook
readIntoTrie (x:xs) wordbook | null word = readIntoTrie xs wordbook
| otherwise = readIntoTrie xs $ insert word wordbook
where word = normalizeWord x
readTrieFromStdin :: IO (Wordbook)
readTrieFromStdin = do
content <- hGetContents stdin
let tokens = words content
readIntoTrie tokens empty
strip :: T.Text -> T.Text
strip = T.dropWhileEnd (not . isAlpha) . T.dropWhile (not . isAlpha)
clean :: T.Text -> T.Text
clean = T.filter isAlpha
normalizeWord = T.unpack . clean . T.toLower . strip . T.pack
readTrieFromFile :: String -> IO (Wordbook)
readTrieFromFile path = do
handle <- openFile path ReadMode
content <- hGetContents handle
let tokens = words content
readIntoTrie tokens empty
type Match = (String, String)
lookupIsPrefixTo :: String -> Wordbook -> Wordbook
lookupIsPrefixTo word = Set.filter ((flip isPrefixOf) word)
getLongerMatches :: String -> Wordbook -> [Match]
getLongerMatches prefix dictionary =
[(match, drop (length prefix) match)
| match <- toList (lookupPrefix prefix dictionary)
, match /= prefix]
getShorterMatches :: String -> Wordbook -> [Match]
getShorterMatches prefix dictionary =
[(match, drop (length match) prefix)
| match <- toList (lookupIsPrefixTo prefix dictionary)]
main :: IO ()
main = do
p <- readTrieFromStdin
mapM_ putStrLn (toList p)
|
akaihola/palindromi-haskell
|
src/WordTrie.hs
|
mit
| 2,142
| 0
| 10
| 446
| 706
| 377
| 329
| 53
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configurationaggregator-accountaggregationsource.html
module Stratosphere.ResourceProperties.ConfigConfigurationAggregatorAccountAggregationSource where
import Stratosphere.ResourceImports
-- | Full data type definition for
-- ConfigConfigurationAggregatorAccountAggregationSource. See
-- 'configConfigurationAggregatorAccountAggregationSource' for a more
-- convenient constructor.
data ConfigConfigurationAggregatorAccountAggregationSource =
ConfigConfigurationAggregatorAccountAggregationSource
{ _configConfigurationAggregatorAccountAggregationSourceAccountIds :: ValList Text
, _configConfigurationAggregatorAccountAggregationSourceAllAwsRegions :: Maybe (Val Bool)
, _configConfigurationAggregatorAccountAggregationSourceAwsRegions :: Maybe (ValList Text)
} deriving (Show, Eq)
instance ToJSON ConfigConfigurationAggregatorAccountAggregationSource where
toJSON ConfigConfigurationAggregatorAccountAggregationSource{..} =
object $
catMaybes
[ (Just . ("AccountIds",) . toJSON) _configConfigurationAggregatorAccountAggregationSourceAccountIds
, fmap (("AllAwsRegions",) . toJSON) _configConfigurationAggregatorAccountAggregationSourceAllAwsRegions
, fmap (("AwsRegions",) . toJSON) _configConfigurationAggregatorAccountAggregationSourceAwsRegions
]
-- | Constructor for 'ConfigConfigurationAggregatorAccountAggregationSource'
-- containing required fields as arguments.
configConfigurationAggregatorAccountAggregationSource
:: ValList Text -- ^ 'ccaaasAccountIds'
-> ConfigConfigurationAggregatorAccountAggregationSource
configConfigurationAggregatorAccountAggregationSource accountIdsarg =
ConfigConfigurationAggregatorAccountAggregationSource
{ _configConfigurationAggregatorAccountAggregationSourceAccountIds = accountIdsarg
, _configConfigurationAggregatorAccountAggregationSourceAllAwsRegions = Nothing
, _configConfigurationAggregatorAccountAggregationSourceAwsRegions = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configurationaggregator-accountaggregationsource.html#cfn-config-configurationaggregator-accountaggregationsource-accountids
ccaaasAccountIds :: Lens' ConfigConfigurationAggregatorAccountAggregationSource (ValList Text)
ccaaasAccountIds = lens _configConfigurationAggregatorAccountAggregationSourceAccountIds (\s a -> s { _configConfigurationAggregatorAccountAggregationSourceAccountIds = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configurationaggregator-accountaggregationsource.html#cfn-config-configurationaggregator-accountaggregationsource-allawsregions
ccaaasAllAwsRegions :: Lens' ConfigConfigurationAggregatorAccountAggregationSource (Maybe (Val Bool))
ccaaasAllAwsRegions = lens _configConfigurationAggregatorAccountAggregationSourceAllAwsRegions (\s a -> s { _configConfigurationAggregatorAccountAggregationSourceAllAwsRegions = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configurationaggregator-accountaggregationsource.html#cfn-config-configurationaggregator-accountaggregationsource-awsregions
ccaaasAwsRegions :: Lens' ConfigConfigurationAggregatorAccountAggregationSource (Maybe (ValList Text))
ccaaasAwsRegions = lens _configConfigurationAggregatorAccountAggregationSourceAwsRegions (\s a -> s { _configConfigurationAggregatorAccountAggregationSourceAwsRegions = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/ConfigConfigurationAggregatorAccountAggregationSource.hs
|
mit
| 3,643
| 0
| 13
| 262
| 358
| 204
| 154
| 33
| 1
|
import qualified Data.ByteString.Lazy as L
hasElfMagick :: L.ByteString -> Bool
hasElfMagick content = elfMagick == L.take 4 content
where elfMagick = L.pack [0x7f, 0x45, 0x4c, 0x46]
isElfFile :: FilePath -> IO Bool
isElfFile path = do
content <- L.readFile path
return $ hasElfMagick content
|
Tr1p0d/realWorldHaskell
|
rwh8/elfmagick.hs
|
gpl-2.0
| 298
| 0
| 9
| 49
| 106
| 55
| 51
| 8
| 1
|
import Control.Exception as C
import Data.List as L
import Data.Maybe as M
import Debug.Trace as D
import System.Environment
import Text.Printf as T
data Op = Or | And | Star deriving (Show, Eq, Ord)
data RxTree = Empty | Atom Char | RxTree { nodeop::Op, subexp::Bool, t_left::RxTree, t_right:: RxTree } deriving Show
data ParseState = ParseState { tree::RxTree, left::String } deriving Show
data Match = Match { from::Int, to::Int } deriving Show
parse_rx :: String -> RxTree
parse_rx str = let state = ParseState Empty str
final_state = parse_rx_helper state
in tree final_state
parse_rx_helper :: ParseState -> ParseState
parse_rx_helper state@(ParseState t []) = state
parse_rx_helper (ParseState t (c:left)) | c == '(' = parse_rx_helper . merge_subexpr $ ParseState t left
| c == ')' = ParseState t left
| c == '|' = parse_rx_helper $ ParseState (RxTree Or False t Empty) left
| c == '*' = parse_rx_helper $ ParseState (push_star_down t) left
| otherwise = parse_rx_helper $ ParseState (append_atom t c) left
merge_subexpr :: ParseState -> ParseState
merge_subexpr (ParseState t0 ini) = let (ParseState t1 left) = parse_rx_helper $ ParseState Empty ini
t1' = decorate_as_subexpr t1
in (ParseState (merge_trees t0 t1') left)
decorate_as_subexpr :: RxTree -> RxTree
decorate_as_subexpr (RxTree op exp left right) = RxTree op True left right
decorate_as_subexpr t = t
merge_trees :: RxTree -> RxTree -> RxTree
merge_trees Empty t = t
merge_trees (RxTree op False t0 Empty) t1 = RxTree op False t0 t1
merge_trees t0 t1 = RxTree And False t0 t1
append_atom :: RxTree -> Char -> RxTree
append_atom Empty c = Atom c
append_atom (Atom c0) c = RxTree And False (Atom c0) (Atom c)
append_atom tree@(RxTree op exp left right) c | And > op && (not exp) = RxTree op False left (append_atom right c)
| otherwise = RxTree And False tree (Atom c)
push_star_down :: RxTree -> RxTree
push_star_down (Atom c) = RxTree Star False (Atom c) (Atom '*')
push_star_down tree@(RxTree op exp left right) | Star > op && (not exp) = RxTree op False left (push_star_down right)
| otherwise = RxTree Star False tree (Atom '*')
-----------------------------------------------------------------------------------------------------------------------
search :: String -> RxTree -> Maybe Match
search str tree = head_maybe $ search_helper str tree
search_helper :: String -> RxTree -> [Match]
--search_helper str tree | D.traceShow (str, tree) False = undefined
search_helper str Empty = map (\(i,s) -> Match i i) (zip [0..] str)
search_helper "" _ = []
search_helper str (Atom c) = map (\(i,s) -> Match i (i+1)) $ filter (\(i,s) -> s == c) (zip [0..] str)
search_helper str (RxTree Or _ t0 t1) = let left_matches = search_helper str t0
right_matches = search_helper str t1
in sort_matches left_matches right_matches
search_helper str (RxTree And _ t0 t1) = let search_after_match = \m -> search_helper_contiguous (substr m str) t1
left_matches = search_helper str t0
right_matches = map search_after_match left_matches
merged_matches = map (uncurry fold_merge) (zip left_matches right_matches)
in mconcat merged_matches
search_helper str (RxTree Star _ t0 t1) = let all_pos = search_helper str Empty
chain_matches = map (\m -> search_first_recursive m str t0) all_pos
in chain_matches
search_helper_contiguous :: String -> RxTree -> [Match]
search_helper_contiguous str tree = let matches = search_helper str tree
in takeWhile (\m -> from m == 0) matches
search_first_recursive :: Match -> String -> RxTree -> Match
--search_first_recursive m str tree | D.traceShow (m, str, tree) False = undefined
search_first_recursive m [] _ = m
search_first_recursive m str tree = let left = substr m str
first_m = fmap (merge_matches m) (head_maybe $ search_helper_contiguous left tree)
recurse_m = fmap search_first_recursive first_m
final_m = recurse_m <*> (Just str) <*> (Just tree)
in M.fromMaybe m final_m
sort_matches :: [Match] -> [Match] -> [Match]
--sort_matches ls rs = L.sortOn from (ls ++ rs)
sort_matches ls [] = ls
sort_matches [] rs = rs
sort_matches (l:ls) (r:rs) = case (from l) <= (from r) of
True -> l : (sort_matches ls (r:rs))
False -> r : (sort_matches (l:ls) rs)
merge_matches :: Match -> Match -> Match
merge_matches m1 m2 | (from m2) == 0 = let combined_to = (to m1) + (to m2)
in Match (from m1) combined_to
| otherwise = m1
fold_merge :: Match -> [Match] -> [Match]
fold_merge _ [] = []
fold_merge m (m0:ms) | C.assert (from m0 == 0) False = undefined
fold_merge m (m0:ms) = (merge_matches m m0) : (fold_merge m ms)
substr :: Match -> String -> String
substr m str = drop (to m) str
head_maybe :: [a] -> Maybe a
head_maybe [] = Nothing
head_maybe l = Just $ head l
-----------------------------------------------------------------------------------------------------------------------
show_tree :: RxTree -> String
show_tree t = show_helper t ""
show_helper :: RxTree -> String -> String
show_helper Empty indent = indent ++ "Empty"
show_helper (Atom c) indent = indent ++ "Atom " ++ (show c)
show_helper (RxTree op exp t0 t1) indent = let new_indent = indent ++ " "
header = indent ++ "RxTree " ++ (show op) ++ " subexpr=" ++ (show exp) ++ "\n"
t0_str = (show_helper t0 new_indent) ++ "\n"
t1_str = (show_helper t1 new_indent)
in header ++ t0_str ++ t1_str
show_match :: String -> (Maybe Match) -> String
show_match _ Nothing = "<no_match>"
show_match str (Just m) = let width = (to m) - (from m)
fragment = (take width) $ (drop $ from m) str
in case fragment == "" of
True -> "<empty_match>"
otherwise -> fragment
test_parse_rx :: IO [()]
test_parse_rx = let cases = [ "", "abc", "a|b", "ab|cd", "(ab)|(cd)", "a|bc|d", "()", "(a)", "((a))", "(a)(b)", "(ab)(cd)", "a(b|c)", "ab(cd(e|f)g)h",
"(ab|)c",
"a*", "ab*", "(ab)*", "a(bc)*", "abc*" ]
regexes = map parse_rx cases
print_pair = \str rx -> T.printf "###### '%s' ######\n%v\n\n" str (show_tree rx)
prints = zipWith print_pair cases regexes
in sequence prints
test_search_rx :: IO [()]
test_search_rx = let strings = ["", "a", "a", "ab", "ab", "ab", "xabx", "xbx", "aaa", "abc" , "aab", "xaxaax", "abc" , "xabbaabx", "xabybccdfhy" ]
rx_strs = ["", "a", "b", "yx", "ax", "ab", "ab", "a|b", "a*" , "ac*" , "a*" , "a*" , "(b|c|a)*", "aaa*b" , "a*b(g|c*d(e|f))h" ]
expects = ["", "a", "", "", "", "ab", "ab", "b", "aaa", "a" , "aa" , "" , "abc" , "aab" , "bccdfh" ]
regexes = map parse_rx rx_strs
results = map (uncurry search) (zip strings regexes)
print_one_test = \str rx m_m expect -> T.printf "###### '%s' =~ /%s/ ######\n'%s' (expected: '%s')\n\n" str rx (show_match str m_m) expect
prints = L.zipWith4 print_one_test strings rx_strs results expects
in sequence prints
-----------------------------------------------------------------------------------------------------------------------
main = do
--(rx_str:str:_) <- getArgs
print $ (show $ search_helper "xabc" (parse_rx "(x|y|)(c|a)"))
-- test_parse_rx
--test_search_rx
T.printf "done\n"
|
candide-guevara/programming_challenges
|
haskell_learning/regular_expression.hs
|
gpl-2.0
| 8,662
| 0
| 14
| 2,863
| 2,627
| 1,368
| 1,259
| 124
| 2
|
{-
Copyright (C) 2006-2010 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.XML
Copyright : Copyright (C) 2006-2010 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Functions for escaping and formatting XML.
-}
module Text.Pandoc.XML ( stripTags,
escapeCharForXML,
escapeStringForXML,
inTags,
selfClosingTag,
inTagsSimple,
inTagsIndented,
toEntities,
fromEntities ) where
import Text.Pandoc.Pretty
import Data.Char (ord, isAscii, isSpace)
import Text.HTML.TagSoup.Entity (lookupEntity)
-- | Remove everything between <...>
stripTags :: String -> String
stripTags ('<':xs) =
let (_,rest) = break (=='>') xs
in if null rest
then ""
else stripTags (tail rest) -- leave off >
stripTags (x:xs) = x : stripTags xs
stripTags [] = []
-- | Escape one character as needed for XML.
escapeCharForXML :: Char -> String
escapeCharForXML x = case x of
'&' -> "&"
'<' -> "<"
'>' -> ">"
'"' -> """
c -> [c]
-- | Escape string as needed for XML. Entity references are not preserved.
escapeStringForXML :: String -> String
escapeStringForXML = concatMap escapeCharForXML
-- | Return a text object with a string of formatted XML attributes.
attributeList :: [(String, String)] -> Doc
attributeList = hcat . map
(\(a, b) -> text (' ' : escapeStringForXML a ++ "=\"" ++
escapeStringForXML b ++ "\""))
-- | Put the supplied contents between start and end tags of tagType,
-- with specified attributes and (if specified) indentation.
inTags:: Bool -> String -> [(String, String)] -> Doc -> Doc
inTags isIndented tagType attribs contents =
let openTag = char '<' <> text tagType <> attributeList attribs <>
char '>'
closeTag = text "</" <> text tagType <> char '>'
in if isIndented
then openTag $$ nest 2 contents $$ closeTag
else openTag <> contents <> closeTag
-- | Return a self-closing tag of tagType with specified attributes
selfClosingTag :: String -> [(String, String)] -> Doc
selfClosingTag tagType attribs =
char '<' <> text tagType <> attributeList attribs <> text " />"
-- | Put the supplied contents between start and end tags of tagType.
inTagsSimple :: String -> Doc -> Doc
inTagsSimple tagType = inTags False tagType []
-- | Put the supplied contents in indented block btw start and end tags.
inTagsIndented :: String -> Doc -> Doc
inTagsIndented tagType = inTags True tagType []
-- | Escape all non-ascii characters using numerical entities.
toEntities :: String -> String
toEntities [] = ""
toEntities (c:cs)
| isAscii c = c : toEntities cs
| otherwise = "&#" ++ show (ord c) ++ ";" ++ toEntities cs
-- Unescapes XML entities
fromEntities :: String -> String
fromEntities ('&':xs) =
case lookupEntity ent of
Just c -> c : fromEntities rest
Nothing -> '&' : fromEntities xs
where (ent, rest) = case break (\c -> isSpace c || c == ';') xs of
(zs,';':ys) -> (zs,ys)
_ -> ("",xs)
fromEntities (x:xs) = x : fromEntities xs
fromEntities [] = []
|
castaway/pandoc
|
src/Text/Pandoc/XML.hs
|
gpl-2.0
| 4,184
| 0
| 15
| 1,154
| 831
| 439
| 392
| 63
| 5
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module Routing where
import Network.Wai (Request(..))
import Network.HTTP.Types.Method(StdMethod, parseMethod, Method, renderStdMethod)
import Data.List(find)
import Data.ByteString(ByteString)
import Data.ByteString.Char8(split,null)
import Routing.Class(Route(MkRoute),Path,PathPattern,RawPathParam,RawPathParams,toParamGivenAction, RouteNotFoundError(PathNotFound,PathFoundButMethodUnmatch,UnknownMethod), RawPathParamsError(BadRouteDefinition, BadParamTypes),RoutingError(RouteNotFound,BadPathParams))
import Class.String(toString, toByteString)
import Data.Maybe(fromJust,isJust)
import Data.Word(Word8)
import Data.Text(Text)
import System.IO(putStrLn)
import qualified Controllers.ChannelsController as ChannelsC
import qualified Controllers.HomeController as HomeC
import qualified Controllers.InstallController as InstallC
import qualified Controllers.ProgramsController as ProgramsC
import qualified Controllers.ReservationsController as ReservationsC
import Routing.Class(Route(MkRoute),Path,PathPattern,PathParamList(..), toActionWrapper)
import Routing.Types(Resource(listAction ,getAction ,modifyAction ,createAction ,destroyAction))
import Network.HTTP.Types.Method(StdMethod(GET,POST,HEAD,PUT,DELETE,TRACE,CONNECT,OPTIONS,PATCH))
import Controller.Types(Action,status,ControllerResponse)
import Class.String((+++))
import Controller(defaultControllerResponse, responseBadRequest, doIfValidInputJSON,ToBody(toBody), responsePathNotFound, responseNotAllowedMethod, responseUnsupportedMethod, response500)
import Network.HTTP.Types (status200, status201, status400, status404)
import Data.Aeson(Value,(.=),object)
import Controller.Types(ParamGivenAction,responseToValue,body)
import Network.Wai (Request(..))
--import Routing.Class(RoutingError(RouteNotFound,BadPathParams))
import Network.HTTP.Types.Method(StdMethod, parseMethod)
import Routing.Class(Route(MkRoute),Path,PathPattern,RawPathParam,RawPathParams,toParamGivenAction, RouteNotFoundError(PathNotFound,PathFoundButMethodUnmatch,UnknownMethod))
matchStdMethods :: Route -> StdMethod -> Bool
matchStdMethods (MkRoute methods _ _ ) method = elem method methods
matchPathElements :: [String] -> [String] -> Maybe RawPathParams -> Maybe RawPathParams
matchPathElements _ _ Nothing = Nothing -- protect error by fromJust
matchPathElements [] (y:ys) _ = Nothing -- mismatch count of elements
matchPathElements (x:xs) [] _ = Nothing -- mismatch count of elements
matchPathElements ptn@(x@(':':sym):xs) pathelems@(y:ys) params = matchPathElements xs ys $ Just $ (fromJust params) ++ [(sym, y)]
matchPathElements ptn@(x:xs) pathelems@(y:ys) params =
if x == y
then matchPathElements xs ys params -- match and do next
else Nothing -- unmatch
matchPathElements [] [] x = x -- finished
-- matchPathElements _ _ _ = Nothing -- error
pathToPieces :: Path -> [String]
pathToPieces path = Prelude.map toString $ filter (not . Data.ByteString.Char8.null) $ Data.ByteString.Char8.split '/' $ toByteString path
getMaybeRawPathParamsFromPatternAndPath :: PathPattern -> Path -> Maybe RawPathParams
getMaybeRawPathParamsFromPatternAndPath ptn path =
matchPathElements ptn_pieces' path_pieces' (Just [])
where
ptn_pieces' = pathToPieces ptn
path_pieces' = pathToPieces path
-- Nothing means unmatch path
getMaybeRawPathParams :: Route -> Path -> Maybe RawPathParams
getMaybeRawPathParams (MkRoute _ ptn _ ) path = getMaybeRawPathParamsFromPatternAndPath ptn path
matchPath :: Path -> Route -> Bool
matchPath p r = isJust $ getMaybeRawPathParams r p
getRawPathParams :: Route -> Path -> RawPathParams
getRawPathParams r p = case getMaybeRawPathParams r p of
Just params -> params
Nothing -> []
findPathMatchedRoutes :: Path -> [Route] -> [(Route, RawPathParams)]
findPathMatchedRoutes path [] = []
findPathMatchedRoutes path (r:rs) = case getMaybeRawPathParams r path of
Just p -> [(r, p)] ++ findPathMatchedRoutes path rs
Nothing -> findPathMatchedRoutes path rs
findMethodMatchedRoute :: StdMethod -> [(Route, RawPathParams)] -> Maybe (Route, RawPathParams)
findMethodMatchedRoute _ [] = Nothing
findMethodMatchedRoute stdmethod ((route@(MkRoute methods ptn actionWrapper),params):xs) =
if matchStdMethods route stdmethod
then Just (route, params)
else findMethodMatchedRoute stdmethod xs
findRoute :: StdMethod -> Path -> Either RouteNotFoundError (Route, RawPathParams)
findRoute stdmethod path =
case findPathMatchedRoutes path routingMap of
[] -> Left PathNotFound
xs -> case find (\(route, params) -> matchStdMethods route stdmethod) xs of
Just x -> Right x
Nothing ->
Left $ PathFoundButMethodUnmatch $ Prelude.concat $ Prelude.map (showRoute' . fst) xs
where
showRoute' :: Route -> String
showRoute' (MkRoute methods ptn _ ) = Prelude.concat [show methods, " ", toString ptn]
notFound, badRequest :: Action ()
notFound conn method req _ = return $ defaultControllerResponse {
status = status404
}
badRequest conn method req _ = return $ defaultControllerResponse {
status = status400
}
_GET_ = [GET]
_POST_ = [POST]
_PATCH_ = [PATCH,PUT]
_DELETE_ = [DELETE]
_ALL_ = [minBound .. maxBound] :: [StdMethod]
(@>>) :: (PathParamList a) => ([StdMethod], PathPattern) -> Action a -> Route
(@>>) (stdmethods, pathpattern) action = MkRoute stdmethods pathpattern $ toActionWrapper action
readResource :: PathPattern -> Resource -> [Route]
readResource p rs = [
( _GET_ , p +++ "/list" ) @>> listAction rs
,( _GET_, p +++ "/:id" ) @>> getAction rs
,( _PATCH_, p +++ "/:id" ) @>> modifyAction rs
,( _POST_, p +++ "" ) @>> createAction rs
,( _DELETE_, p +++ "/:id" ) @>> destroyAction rs
]
routingMap :: [Route]
routingMap =
(readResource "/channels" ChannelsC.resource ) ++
(readResource "/programs" ProgramsC.resource ) ++
(readResource "/reservations" ReservationsC.resource ) ++
[
( _GET_, "/install/index" ) @>> notFound -- InstallC.index
,( _GET_, "/install/channels" ) @>> notFound -- InstallC.resultDetectChannels
,( _GET_, "/install/step1" ) @>> notFound -- (InstallC.step 1)
,( _GET_, "/install/step2" ) @>> notFound -- (InstallC.step 2)
,( _GET_, "/install/step3" ) @>> notFound -- (InstallC.step 3)
,( _GET_, "/multi" ) @>> multi
,( _ALL_, "*" ) @>> notFound -- not found error
]
multi :: Action ()
multi _ method conn req = doIfValidInputJSON req $ impl' []
where
path' = rawPathInfo req :: ByteString
impl' :: [IO (Text, ControllerResponse)] -> [Text] -> IO ControllerResponse
impl' ys [] = do
xs <- sequence ys
return $ defaultControllerResponse {
body = toBody $ object $ Prelude.map (\(k,v) -> k .= (responseToValue v)) xs
}
impl' ys (x:xs) = do
case runImpl method (toByteString x) of
Right (_, action, _) -> do
cres <- action method conn req
impl' (ys ++ [return (x,cres)]) xs
Left err -> return err
routingErrorToControllerResponse :: RoutingError -> Path -> Method -> ControllerResponse
routingErrorToControllerResponse (RouteNotFound PathNotFound) path method = responsePathNotFound path
routingErrorToControllerResponse (RouteNotFound (PathFoundButMethodUnmatch msg)) path method = responseNotAllowedMethod path (show method)
routingErrorToControllerResponse (RouteNotFound UnknownMethod) path method = responseUnsupportedMethod path
routingErrorToControllerResponse (BadPathParams (BadParamTypes keys)) path method = responseBadRequest $ (show keys) ++ " are bad type"
routingErrorToControllerResponse (BadPathParams BadRouteDefinition) path method = response500 "BadRouteDefinition!"
run :: Request -> Either ControllerResponse (StdMethod, ParamGivenAction, Route)
run req =
case parseMethod $ requestMethod req of
Left method -> Left $ routingErrorToControllerResponse (RouteNotFound UnknownMethod) path' method
Right stdmethod -> runImpl stdmethod path'
where
path' = rawPathInfo req
runImpl :: StdMethod -> ByteString -> Either ControllerResponse (StdMethod, ParamGivenAction, Route)
runImpl stdmethod path =
case findRoute stdmethod path of
Right (route@(MkRoute methods ptn actionWrapper), rawPathParams) ->
case toParamGivenAction actionWrapper rawPathParams of
Left x -> Left $ routingErrorToControllerResponse (BadPathParams x) path (renderStdMethod stdmethod)
Right action -> Right (stdmethod, action, route)
Left x -> Left $ routingErrorToControllerResponse (RouteNotFound x) path (renderStdMethod stdmethod)
|
shinjiro-itagaki/shinjirecs
|
shinjirecs-api/src/Routing.hs
|
gpl-3.0
| 8,876
| 0
| 19
| 1,499
| 2,539
| 1,417
| 1,122
| 147
| 3
|
module Test.Utils.GeometryData where
import GameLogic.Base.Geometry
point1 = point 0 (-10) 0
point2 = point 3 (-3) 0
point3 = point (-10) 0 0
point4 = point 5 (-3) 0
point5 = point (-10) (-3) 0
point6 = point 5 0 0
rect1 = rectBound point2 point6
rect2 = rectBound point5 point6
|
graninas/The-Amoeba-World
|
src/Amoeba/Test/Utils/GeometryData.hs
|
gpl-3.0
| 281
| 0
| 7
| 53
| 135
| 73
| 62
| 10
| 1
|
-- this is from ghc/syslib-ghc originally,
-- but i made some changes, marked by ???????
module Pretty (
Pretty,
ppNil, ppStr, ppPStr, ppChar, ppInt, ppInteger,
ppFloat, ppDouble,
ppSP, pp'SP, ppLbrack, ppRbrack, ppLparen, ppRparen,
ppSemi, ppComma, ppEquals,
ppBracket, ppParens, ppQuote,
ppBesideSP, -- this wasn't exported originally, why ???????????
ppCat, ppBeside, ppBesides, ppAbove, ppAboves,
ppNest, ppSep, ppHang, ppInterleave, ppIntersperse,
ppShow, speakNth,
-- abstract type, to complete the interface...
PrettyRep(..), Delay
) where
import Ratio
import CharSeq
ppNil :: Pretty
ppSP, pp'SP, ppLbrack, ppRbrack, ppLparen, ppRparen, ppSemi, ppComma, ppEquals :: Pretty
ppStr :: [Char] -> Pretty
ppPStr :: String -> Pretty
ppChar :: Char -> Pretty
ppInt :: Int -> Pretty
ppInteger :: Integer -> Pretty
ppDouble :: Double -> Pretty
ppFloat :: Float -> Pretty
ppRational :: Rational -> Pretty
ppBracket :: Pretty -> Pretty -- put brackets around it
ppParens :: Pretty -> Pretty -- put parens around it
ppBeside :: Pretty -> Pretty -> Pretty
ppBesides :: [Pretty] -> Pretty
ppBesideSP :: Pretty -> Pretty -> Pretty
ppCat :: [Pretty] -> Pretty -- i.e., ppBesidesSP
ppAbove :: Pretty -> Pretty -> Pretty
ppAboves :: [Pretty] -> Pretty
ppInterleave :: Pretty -> [Pretty] -> Pretty
ppIntersperse :: Pretty -> [Pretty] -> Pretty -- no spaces between, no ppSep
ppSep :: [Pretty] -> Pretty
ppHang :: Pretty -> Int -> Pretty -> Pretty
ppNest :: Int -> Pretty -> Pretty
ppShow :: Int -> Pretty -> [Char]
type Pretty = Int -- The width to print in
-> Bool -- True => vertical context
-> PrettyRep
data PrettyRep
= MkPrettyRep CSeq -- The text
(Delay Int) -- No of chars in last line
Bool -- True if empty object
Bool -- Fits on a single line in specified width
data Delay a = MkDelay a
forceDel (MkDelay _) r = r
forceBool True r = r
forceBool False r = r
forceInfo ll emp sl r = forceDel ll (forceBool emp (forceBool sl r))
ppShow width p
= case (p width False) of
MkPrettyRep seq ll emp sl -> cShow seq
ppNil width is_vert = MkPrettyRep cNil (MkDelay 0) True (width >= 0)
-- Doesn't fit if width < 0, otherwise, ppNil
-- will make ppBesides always return True.
ppStr s width is_vert = MkPrettyRep (cStr s) (MkDelay ls) False (width >= ls)
where ls = length s
ppPStr s width is_vert = MkPrettyRep (cPStr s) (MkDelay ls) False (width >= ls)
where ls = length s
ppChar c width is_vert = MkPrettyRep (cCh c) (MkDelay 1) False (width >= 1)
ppInt n width is_vert = MkPrettyRep (cStr s) (MkDelay ls) False (width >= ls)
where s = show n; ls = length s
ppInteger n = ppStr (show n)
ppDouble n = ppStr (show n)
ppFloat n = ppStr (show n)
ppRational n = ppStr (show (fromRationalX n)) -- _showRational 30 n)
ppSP = ppChar ' '
pp'SP = ppStr ", "
ppLbrack = ppChar '['
ppRbrack = ppChar ']'
ppLparen = ppChar '('
ppRparen = ppChar ')'
ppSemi = ppChar ';'
ppComma = ppChar ','
ppEquals = ppChar '='
ppBracket p = ppBeside ppLbrack (ppBeside p ppRbrack)
ppParens p = ppBeside ppLparen (ppBeside p ppRparen)
ppQuote p = ppBeside (ppChar '`') (ppBeside p (ppChar '\''))
ppInterleave sep ps = ppSep (pi ps)
where
pi [] = []
pi [x] = [x]
pi (x:xs) = (ppBeside x sep) : pi xs
ppIntersperse sep ps = ppBesides (pi ps)
where
pi [] = []
pi [x] = [x]
pi (x:xs) = (ppBeside x sep) : pi xs
ppBeside p1 p2 width is_vert
= case (p1 width False) of
MkPrettyRep seq1 (MkDelay ll1) emp1 sl1 ->
MkPrettyRep (seq1 `cAppend` (cIndent ll1 seq2))
(MkDelay (ll1 + ll2))
(emp1 && emp2)
((width >= 0) && (sl1 && sl2))
-- This sequence of (&&)'s ensures that ppBeside
-- returns a False for sl as soon as possible.
where -- NB: for case alt
seq2 = forceInfo x_ll2 emp2 sl2 x_seq2
MkDelay ll2 = x_ll2
MkPrettyRep x_seq2 x_ll2 emp2 sl2 = p2 (width-ll1) False
-- ToDo: if emp{1,2} then we really
-- should be passing on "is_vert" to p{2,1}.
ppBesides [] = ppNil
ppBesides ps = foldr1 ppBeside ps
ppBesideSP p1 p2 width is_vert
= case (p1 width False) of
MkPrettyRep seq1 (MkDelay ll1) emp1 sl1 ->
MkPrettyRep (seq1 `cAppend` (sp `cAppend` (cIndent li seq2)))
(MkDelay (li + ll2))
(emp1 && emp2)
((width >= wi) && (sl1 && sl2))
where -- NB: for case alt
seq2 = forceInfo x_ll2 emp2 sl2 x_seq2
MkDelay ll2 = x_ll2
MkPrettyRep x_seq2 x_ll2 emp2 sl2 = p2 (width-li) False
li, wi :: Int
li = if emp1 then 0 else ll1+1
wi = if emp1 then 0 else 1
sp = if emp1 || emp2 then cNil else (cCh ' ')
ppCat [] = ppNil
ppCat ps = foldr1 ppBesideSP ps
ppAbove p1 p2 width is_vert
= case (p1 width True) of
MkPrettyRep seq1 (MkDelay ll1) emp1 sl1 ->
MkPrettyRep (seq1 `cAppend` (nl `cAppend` seq2))
(MkDelay ll2)
-- ToDo: make ll depend on empties?
(emp1 && emp2)
False
where -- NB: for case alt
nl = if emp1 || emp2 then cNil else cNL
seq2 = forceInfo x_ll2 emp2 sl2 x_seq2
MkDelay ll2 = x_ll2 -- Don't "optimise" this away!
MkPrettyRep x_seq2 x_ll2 emp2 sl2 = p2 width True
-- ToDo: ditto about passing is_vert if empties
ppAboves [] = ppNil
ppAboves ps = foldr1 ppAbove ps
ppNest n p width False = p width False
ppNest n p width True
= case (p (width-n) True) of
MkPrettyRep seq (MkDelay ll) emp sl ->
MkPrettyRep (cIndent n seq) (MkDelay (ll+n)) emp sl
ppHang p1 n p2 width is_vert -- This is a little bit stricter than it could
-- be made with a little more effort.
-- Eg the output always starts with seq1
= case (p1 width False) of
MkPrettyRep seq1 (MkDelay ll1) emp1 sl1 ->
if emp1 then
p2 width is_vert
else
if (ll1 <= n) || sl2 then -- very ppBesideSP'ish
-- Hang it if p1 shorter than indent or if it doesn't fit
MkPrettyRep (seq1 `cAppend` ((cCh ' ') `cAppend` (cIndent (ll1+1) seq2)))
(MkDelay (ll1 + 1 + ll2))
False
(sl1 && sl2)
else
-- Nest it (pretty ppAbove-ish)
MkPrettyRep (seq1 `cAppend` (cNL `cAppend` (cIndent n seq2')))
(MkDelay ll2') -- ToDo: depend on empties
False
False
where -- NB: for case alt
seq2 = forceInfo x_ll2 emp2 sl2 x_seq2
MkDelay ll2 = x_ll2
MkPrettyRep x_seq2 x_ll2 emp2 sl2 = p2 (width-(ll1+1)) False
-- ToDo: more "is_vert if empty" stuff
seq2' = forceInfo x_ll2' emp2' sl2' x_seq2'
MkDelay ll2' = x_ll2' -- Don't "optimise" this away!
MkPrettyRep x_seq2' x_ll2' emp2' sl2' = p2 (width-n) False -- ToDo: True?
ppSep [] width is_vert = ppNil width is_vert
ppSep [p] width is_vert = p width is_vert
{-
-- CURRENT, but BAD. Quadratic behaviour on the perfectly reasonable
-- ppSep [a, ppSep[b, ppSep [c, ... ]]]
ppSep ps width is_vert
= case (ppCat ps width is_vert) of
MkPrettyRep seq x_ll emp sl ->
if sl then -- Fits on one line
MkPrettyRep seq x_ll emp sl
else
ppAboves ps width is_vert -- Takes several lines
-}
-- a different attempt:
ppSep ps @ (p : q : qs) width is_vert =
let (as, bs) = splitAt (length ps `div` 2) ps
in
case (ppSep as width False, ppSep bs width False) of
( MkPrettyRep seq1 x_ll1 emp1 sl1 , MkPrettyRep seq2 x_ll2 emp2 sl2 ) ->
if {- sl1 && -} sl2 && (ll1 + ll2 < width)
then MkPrettyRep
(seq1 `cAppend` (cCh ' ' `cAppend` (cIndent (ll1 + 1) seq2)))
(MkDelay (ll1 + 1 + ll2))
(emp1 && emp2)
sl1
else MkPrettyRep
(seq1 `cAppend` (cNL `cAppend` seq2))
x_ll2
(emp1 && emp2)
False
where MkDelay ll1 = x_ll1; MkDelay ll2 = x_ll2
speakNth :: Int -> Pretty
speakNth 1 = ppStr "first"
speakNth 2 = ppStr "second"
speakNth 3 = ppStr "third"
speakNth 4 = ppStr "fourth"
speakNth 5 = ppStr "fifth"
speakNth 6 = ppStr "sixth"
speakNth n = ppBesides [ ppInt n, ppStr st_nd_rd_th ]
where
st_nd_rd_th | n_rem_10 == 1 = "st"
| n_rem_10 == 2 = "nd"
| n_rem_10 == 3 = "rd"
| otherwise = "th"
n_rem_10 = n `rem` 10
-- from Lennart
fromRationalX :: (RealFloat a) => Rational -> a
fromRationalX = error "Pretty.fromRationalX"
{-
fromRationalX r =
let
h = ceiling (huge `asTypeOf` x)
b = toInteger (floatRadix x)
x = fromRat 0 r
fromRat e0 r' =
let d = denominator r'
n = numerator r'
in if d > h then
let e = integerLogBase b (d `div` h) + 1
in fromRat (e0-e) (n % (d `div` (b^e)))
else if abs n > h then
let e = integerLogBase b (abs n `div` h) + 1
in fromRat (e0+e) ((n `div` (b^e)) % d)
else
scaleFloat e0 (fromRational r')
in x
-}
-- Compute the discrete log of i in base b.
-- Simplest way would be just divide i by b until it's smaller then b, but that would
-- be very slow! We are just slightly more clever.
integerLogBase :: Integer -> Integer -> Int
integerLogBase b i =
if i < b then
0
else
-- Try squaring the base first to cut down the number of divisions.
let l = 2 * integerLogBase (b*b) i
doDiv :: Integer -> Int -> Int
doDiv j k = if j < b then k else doDiv (j `div` b) (k+1)
in
doDiv (i `div` (b^l)) l
------------
-- Compute smallest and largest floating point values.
{-
tiny :: (RealFloat a) => a
tiny =
let (l, _) = floatRange x
x = encodeFloat 1 (l-1)
in x
-}
huge :: (RealFloat a) => a
huge =
undefined
{-
let (_, u) = floatRange x
d = floatDigits x
x = encodeFloat (floatRadix x ^ d - 1) (u - d)
in x
-}
|
jwaldmann/rx
|
src/Pretty.hs
|
gpl-3.0
| 9,468
| 181
| 22
| 2,398
| 3,050
| 1,632
| 1,418
| 196
| 4
|
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Optimization.Dataflow.GlobalCommonSubexpressions
Description : Eliminates global common subexpressions.
Copyright : 2015, Tay Phuong Ho
License : GPL-3
-}
module Optimization.Dataflow.GlobalCommonSubexpressions (
globalCommonSubexpressions
)
where
import Interface.TAC (
Command (..), Variable,
getUseVariables, getDefVariables, renameVariables
)
import qualified Interface.TAC as TAC
import Prelude (
Show, Eq,
FilePath, IO, Int, Maybe (..),
fst, snd, sum, zip, show, compare, min, max,
($), (.), (==), (++), (||), (+),
String, (&&), not, Ord, zipWith, head, maxBound, (-), Bool(..)
)
import Data.Functor (
(<$>)
)
import Data.Foldable (
foldl'
)
import Data.Maybe (
fromJust
)
import Data.List (
filter, nub,
isInfixOf, last, nub
)
import Data.List.Split (
splitOn
)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Graph.Inductive (
Gr, Context,
lab, gmap, nmap,
nodes, edges
)
import Control.Monad.State (
State,
evalState, get, put, return
)
import qualified Data.String.Utils as String
-- $| This is just a string.
type Expression = String
globalCommonSubexpressions :: Gr ([Command], Set Variable, Set Variable) () -> Gr [Command] ()
globalCommonSubexpressions = nmap removeKillUse . usedExpressions . init3 . postponableExpressions . init2. availableExpressions . init1 . anticipatedExpressions . init0 . nmap calculateKillUse
where
calculateKillUse :: ([Command], Set Variable, Set Variable)
-> ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression)
calculateKillUse (cmds, def, use) = (cmds, def, use, exprs, eUsed, eKilled)
where
(exprs, eUsed, eKilled) = foldl' foldFunc ([], Set.empty, Set.empty) cmds
foldFunc (exprs, eUsed, eKilled) cmd = let exprs' = exprs ++ [expr] in if expr == "" then (exprs', eUsed, eKilled) else (exprs', eUsed', eKilled')
where
expr = let text = (show cmd)
subexpr = last $ splitOn " = " text
in if isInfixOf " = " text && (isInfixOf "+" text || isInfixOf "-" text || isInfixOf "*" text || isInfixOf "/" text || isInfixOf "%" text) then subexpr else ""
eUsed' = (Set.singleton expr) `Set.union` eUsed
eKilled' = if Set.null $ (Set.fromList $ getUseVariables cmd) `Set.intersection` def then eKilled else (Set.singleton expr) `Set.union` eKilled
removeKillUse :: ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression)
-> [Command]
removeKillUse (cmds, _, _, _, _, _, _, _, _, _, _) = cmds
eAll
:: Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression)
()
-> Set Expression
eAll gr = Set.unions $
(((\(_,_,_,_,i,_,_,_,_,_,_) -> i) . fromJust . lab gr) <$> nodes gr)
eAll'
:: Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression)
()
-> Set Expression
eAll' gr = Set.unions $
(((\(_,_,_,_,i,_) -> i) . fromJust . lab gr) <$> nodes gr)
init0
:: Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression)
()
-> Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression)
()
init0 gr = gmap (\(aIn, n, (cmds, def, use, exprs, eUsed, eKilled), aOut) -> let initialization = eAll' gr in (aIn, n, (cmds, def, use, exprs, eUsed, eKilled, initialization, Set.empty, Set.empty, Set.empty, Set.empty), aOut)) gr
init1, init2, init3
:: Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression)
()
-> Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression)
()
init1 gr = gmap (\(aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn, _, _, _, _), aOut) -> let initialization = eAll gr in (aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn, Set.empty, initialization, Set.empty, Set.empty), aOut)) gr
init2 gr = gmap (\(aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn, availableIn, _, _, _), aOut) -> let initialization = eAll gr in (aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn, availableIn, Set.empty, initialization, Set.empty), aOut)) gr
init3 gr = gmap (\(aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn, availableIn, postponableIn, _, _), aOut) -> (aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn, availableIn, postponableIn, Set.empty, Set.empty), aOut)) gr
anticipatedExpressions, availableExpressions, postponableExpressions, usedExpressions
:: Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression)
()
-> Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression)
()
anticipatedExpressions gr = dataFlow gr anticipated
availableExpressions gr = dataFlow gr available
postponableExpressions gr = dataFlow gr postponable
usedExpressions gr = eliminate (dataFlow gr used)
anticipated, available, postponable, used, eliminate
:: Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression)
()
-> Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression)
()
anticipated gr = gmap equations gr
where
equations :: Context ([Command], Set Variable, Set Variable
, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression) ()
-> Context ([Command], Set Variable, Set Variable
, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression) ()
equations (aIn, n, (cmds, def, use, exprs, eUsed, eKilled, _, _, e4, e5, e6), aOut) =
(aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn', anticipatedOut', e4, e5, e6), aOut)
where
anticipatedIn' = if n == -1 then Set.empty else eUsed `Set.union` (anticipatedOut' `Set.difference` eKilled)
anticipatedOut' = intersections $
(((\(_,_,_,_,_,_,i,_,_,_,_) -> i) . fromJust . lab gr . snd) <$> aOut)
available gr = gmap equations gr
where
equations :: Context ([Command], Set Variable, Set Variable
, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression) ()
-> Context ([Command], Set Variable, Set Variable
, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression) ()
equations (aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn, _, _, e5, e6), aOut) =
(aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn, availableIn', availableOut', e5, e6), aOut)
where
availableIn' = intersections $
(((\(_,_,_,_,_,_,_,_,i,_,_) -> i) . fromJust . lab gr . fst) <$> aIn' n gr)--Set.singleton $ show $ length aOut
availableOut' = if n == 0 then Set.empty else (anticipatedIn `Set.union` availableIn') `Set.difference` eKilled
postponable gr = gmap equations gr
where
equations :: Context ([Command], Set Variable, Set Variable
, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression) ()
-> Context ([Command], Set Variable, Set Variable
, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression) ()
equations (aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn, availableIn, _, _, e6), aOut) =
(aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn, availableIn, postponableIn', postponableOut', e6), aOut)
where
postponableIn' = intersections $
(((\(_,_,_,_,_,_,_,_,_,i,_) -> i) . fromJust . lab gr . fst) <$> aIn' n gr)
postponableOut' = if n == 0 then Set.empty else (earliest `Set.union` postponableIn') `Set.difference` eUsed
earliest = anticipatedIn `Set.difference` availableIn
used gr = gmap equations gr
where
equations :: Context ([Command], Set Variable, Set Variable
, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression) ()
-> Context ([Command], Set Variable, Set Variable
, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression) ()
equations (aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn, availableIn, postponableIn, _, _), aOut) =
(aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn, availableIn, postponableIn, usedIn', usedOut'), aOut)
where
usedIn' = if n == -1 then Set.empty else (eUsed `Set.union` usedOut') `Set.difference` latest
usedOut' = Set.unions $
(((\(_,_,_,_,_,_,_,_,_,i,_) -> i) . fromJust . lab gr . snd) <$> aOut)
earliest = anticipatedIn `Set.difference` availableIn
latest = Set.intersection (earliest `Set.union` postponableIn) $
Set.union eUsed $ Set.difference all $
intersections $ (((\(_,_,_,_,_,_,anticipatedIn',availableIn',postponableIn',_,_) -> let earliest' = anticipatedIn' `Set.difference` availableIn' in earliest' `Set.union` postponableIn') . fromJust . lab gr . snd) <$> aOut)
all = eAll gr
eliminate gr = gmap equations gr
where
equations :: Context ([Command], Set Variable, Set Variable
, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression) ()
-> Context ([Command], Set Variable, Set Variable
, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression) ()
equations (aIn, n, (cmds, def, use, exprs, eUsed, eKilled, anticipatedIn, availableIn, postponableIn, usedIn, usedOut), aOut) =
(aIn, n, (cmds', def, use, exprs, eUsed, eKilled, anticipatedIn, availableIn, postponableIn, usedIn, usedOut), aOut)
where
cmds' = let (pre, post) = foldl' replace ([], []) $ zipWith (\ cmd expr -> (cmd, expr)) cmds exprs in (nub pre) ++ post
var expr = expr --let infix_ = if isInfixOf ":double" expr then ":double" else ":int" in (String.replace infix_ "" expr) ++ infix_
earliest = anticipatedIn `Set.difference` availableIn
latest = Set.intersection (earliest `Set.union` postponableIn) $
Set.union eUsed $ Set.difference all $
intersections $ (((\(_,_,_,_,_,_,anticipatedIn',availableIn',postponableIn',_,_) -> let earliest' = anticipatedIn' `Set.difference` availableIn' in earliest' `Set.union` postponableIn') . fromJust . lab gr . snd) <$> aOut)
all = eAll gr
replace :: ([Command], [Command]) -> (Command, Expression) -> ([Command], [Command])
replace (pre, post) (cmd, expr) | Set.member expr $ Set.intersection latest usedOut = (pre ++ [renameVariables cmd (head $ getDefVariables cmd) (var expr)], replace' post (cmd, expr))
replace (pre, post) (cmd, expr) = (pre, replace' post (cmd, expr))
replace' :: [Command] -> (Command, Expression) -> [Command]
replace' post (cmd, expr) | Set.member expr $ Set.intersection eUsed $ Set.union usedOut $ Set.difference all latest = post ++ [TAC.Copy (head $ getDefVariables cmd) (TAC.Variable $ var expr)]
replace' post (cmd, _) = post ++ [cmd]
aIn' n gr = filter (\(_,w) -> w == n) (edges gr)
dataFlow
:: Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression)
()
-> (Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression)
()
-> Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression)
())
-> Gr ([Command], Set Variable, Set Variable, [Expression], Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression, Set Expression)
()
dataFlow gr transfer = let next = transfer gr in if gr == next then gr else dataFlow next transfer
intersections :: (Ord a) => [Set a] -> Set a
intersections [] = Set.empty
intersections [a] = a
intersections (a:aa) = foldl' Set.intersection a aa
|
Potregon/while
|
src/Optimization/Dataflow/GlobalCommonSubexpressions.hs
|
gpl-3.0
| 14,134
| 0
| 24
| 3,366
| 5,365
| 3,042
| 2,323
| 171
| 10
|
{-
This file is part of HNH.
HNH 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.
HNH 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 HNH. If not, see <http://www.gnu.org/licenses/>.
Copyright 2010 Francisco Ferreira
-}
module Token
(
HasntToken(..)
)
where
data HasntToken
=
-- Special Characters
LeftParen -- (
| RightParen -- )
| Comma -- ,
| SemiColon -- ;
| LeftSq -- [
| RightSq -- ]
| BackQuote -- `
| LeftCurly -- {
| RightCurly -- }
| Underscore -- _
-- Reserved Words
| CaseToken
| DataToken
| DefaultToken
| ElseToken
| IfToken
| InToken
| InfixToken
| InfixlToken
| InfixrToken
| LetToken
| OfToken
| ThenToken
| TypeToken
-- Reserved Operands
| ColonOp -- :
| DoubleColonOp -- ::
| EqualsOp -- =
| BackSlashOp -- \ One back slash
| BarOp -- |
| RightArrowOp -- ->
| TildeOp -- ~
| TildeDotOp -- ~.
-- Variable and Contructor names
| VariableName String
| ConstructorName String
| VariableSymbol String
-- Literals
| IntegerLiteral Int
| FloatLiteral Double
| StringLiteral String
| CharLiteral String -- TODO should change to Char ?
-- CatchAll for errors
| Unexpected String
-- EOF token
| EOFToken
deriving (Eq, Show)
|
fferreira/hnh
|
Token.hs
|
gpl-3.0
| 1,920
| 14
| 6
| 636
| 205
| 139
| 66
| 45
| 0
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
--------------------------------------------------------------------------------
-- |
-- Module : Tct.Method.DP.Simplification
-- Copyright : (c) Martin Avanzini <martin.avanzini@uibk.ac.at>,
-- Georg Moser <georg.moser@uibk.ac.at>,
-- Andreas Schnabl <andreas.schnabl@uibk.ac.at>,
-- License : LGPL (see COPYING)
--
-- Maintainer : Martin Avanzini <martin.avanzini@uibk.ac.at>
-- Stability : unstable
-- Portability : unportable
--
-- This module provides various fast transformations that simplify
-- dependency pair problems.
--------------------------------------------------------------------------------
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
module Tct.Method.DP.Simplification
(
-- * Remove Weak Suffixes
removeWeakSuffix
, RemoveWeakSuffixProof (..)
, removeWeakSuffixProcessor
, RemoveWeakSuffix
-- * Remove Tails
, removeHeads
, RemoveHeadProof (..)
, removeHeadProcessor
, RemoveHead
-- * Simplify Dependency Pair Right-Hand-Sides
, simpDPRHS
, SimpRHSProof (..)
, simpDPRHSProcessor
, SimpRHS
-- * Trivial DP Problems
, trivial
, TrivialProof (..)
, trivialProcessor
, Trivial
-- * Removing of InapplicableRules
, removeInapplicable
, RemoveInapplicableProof (..)
, removeInapplicableProcessor
, RemoveInapplicable
-- * Knowledge Propagation
, simpPE
, simpPEOn
, withPEOn
, SimpPEProof (..)
, simpPEProcessor
, SimpPE
-- , inline
-- , inlineProcessor
-- , Inline
)
where
import qualified Data.Set as Set
import Data.List (partition, find)
import Data.Maybe (catMaybes)
import Text.PrettyPrint.HughesPJ hiding (empty)
import Control.Monad (mplus)
import qualified Termlib.FunctionSymbol as F
import qualified Termlib.Signature as Sig
import qualified Termlib.Variable as V
import qualified Termlib.Problem as Prob
import qualified Termlib.Trs as Trs
import Termlib.Rule (Rule (..),)
import qualified Termlib.Term as Term
-- import qualified Termlib.Substitution as Subst
import Termlib.Term (properSubterms, functionSymbols)
import Termlib.Trs.PrettyPrint (pprintNamedTrs, pprintTrs)
import Termlib.Utils hiding (block)
import Data.Maybe (isJust, fromMaybe)
import qualified Data.Graph.Inductive.Graph as Graph
import qualified Tct.Certificate as Cert
import qualified Tct.Processor.Transformations as T
import qualified Tct.Processor as P
import Tct.Processor.Args as A
import Tct.Processor.Args.Instances
import Tct.Utils.PPrint
import Tct.Utils.Enum (enumeration')
import Tct.Method.DP.Utils
import Tct.Method.DP.DependencyGraph as DG hiding (Trivial)
import Tct.Method.RuleSelector as RS
import qualified Tct.Utils.Xml as Xml
import qualified Tct.Utils.Xml.Encoding as XmlE
----------------------------------------------------------------------
-- Remove Head
data RemoveHead = RemoveHead
data RemoveHeadProof = RHProof { rhRemoveds :: [(NodeId, DGNode)]
, rhGraph :: DG -- ^ Employed weak dependency graph.
, rhSig :: F.Signature
, rhVars :: V.Variables}
| RHError DPError
instance T.TransformationProof RemoveHead where
answer = T.answerFromSubProof
pprintTProof _ _ (RHError e) _ = pprint e
pprintTProof _ _ p _ | null rems = text "No dependency pair could be removed."
| otherwise =
text "Consider the dependency graph"
$+$ text ""
$+$ indent (pprint (wdg, sig, vars))
$+$ text ""
$+$ paragraph ("Following roots of the dependency graph are removed, as the considered set of starting terms is closed under reduction with respect to these rules (modulo compound contexts).")
$+$ text ""
$+$ indent (pprintTrs ppRule [r | (_, (_, r)) <- rems])
$+$ text ""
where
vars = rhVars p
sig = rhSig p
wdg = rhGraph p
rems = rhRemoveds p
ppRule r = pprint (r, sig, vars)
tproofToXml _ _ (RHError e) = ("removeHead", [errorToXml e])
tproofToXml _ _ p =
( "removeHead"
, [ DG.toXml (dg, sig, vs)
, Xml.elt "removedHeads" [] [ XmlE.rule r (Just n) sig vs
| (n, (_, r)) <- rems]
]
)
where
sig = rhSig p
vs = rhVars p
dg = rhGraph p
rems = rhRemoveds p
instance T.Transformer RemoveHead where
name RemoveHead = "removehead"
description RemoveHead = ["Removes roots from the dependency graph that lead to starting terms only."]
type ArgumentsOf RemoveHead = Unit
type ProofOf RemoveHead = RemoveHeadProof
arguments RemoveHead = Unit
transform _ prob
| not $ Trs.isEmpty $ Prob.strictTrs prob = return $ T.NoProgress $ RHError $ ContainsStrictRule
| not $ Prob.isDPProblem prob = return $ T.NoProgress $ RHError $ NonDPProblemGiven
| null heads = return $ T.NoProgress proof
| otherwise = return $ T.Progress proof (enumeration' [prob'])
where wdg = estimatedDependencyGraph defaultApproximation prob
sig = Prob.signature prob
vars = Prob.variables prob
st = Prob.startTerms prob
ds = Prob.defineds st
cs = Prob.constrs st
heads = [(n,cn) | (n,cn@(_,rl)) <- withNodeLabels' wdg $ roots wdg
, isBasicC $ rhs rl ]
isBasicC (Term.Var _) = True
isBasicC (Term.Fun f ts)
| F.isCompound sig f = all isBasicC ts
| f `Set.member` ds = Set.unions [Term.functionSymbols ti | ti <- ts ] `Set.isSubsetOf` cs
| otherwise = False
proof = RHProof { rhRemoveds = heads
, rhGraph = wdg
, rhSig = sig
, rhVars = vars }
prob' = prob { Prob.strictDPs = Prob.strictDPs prob Trs.\\ Trs.fromRules [ rl | (_,(StrictDP,rl)) <- heads]
, Prob.weakDPs = Prob.weakDPs prob Trs.\\ Trs.fromRules [ rl | (_,(WeakDP,rl)) <- heads] }
removeHeadProcessor :: T.Transformation RemoveHead P.AnyProcessor
removeHeadProcessor = T.Transformation RemoveHead
-- | Removes unnecessary roots from the dependency graph.
removeHeads :: T.TheTransformer RemoveHead
removeHeads = T.Transformation RemoveHead `T.withArgs` ()
----------------------------------------------------------------------
-- Remove Tail
data RemoveWeakSuffix = RemoveWeakSuffix
data RemoveWeakSuffixProof = RTProof { removables :: [(NodeId, DGNode)] -- ^ Tail Nodes of the dependency graph.
, cgraph :: CDG -- ^ Employed congruence graph.
, graph :: DG -- ^ Employed weak dependency graph.
, signature :: F.Signature
, variables :: V.Variables}
| RTError DPError
instance T.TransformationProof RemoveWeakSuffix where
answer = T.answerFromSubProof
pprintTProof _ _ (RTError e) _ = pprint e
pprintTProof _ _ p _
| null remls = paragraph "The dependency graph contains no sub-graph of weak DPs closed under successors."
| otherwise =
paragraph "The following weak DPs constitute a sub-graph of the DG that is closed under successors. The DPs are removed."
$+$ text ""
$+$ pprint (Trs.fromRules [ r | (_,(_,r)) <- remls ], sig,vars)
where vars = variables p
sig = signature p
remls = removables p
onlyWeaks :: CDGNode -> Bool
onlyWeaks = not . any ((==) StrictDP . fst . snd) . theSCC
instance T.Transformer RemoveWeakSuffix where
name RemoveWeakSuffix = "removetails"
description RemoveWeakSuffix = [unwords [ "Removes trailing paths that do not need to be oriented."
, "Only applicable if the strict component is empty."]
]
type ArgumentsOf RemoveWeakSuffix = Unit
type ProofOf RemoveWeakSuffix = RemoveWeakSuffixProof
arguments RemoveWeakSuffix = Unit
transform _ prob
| not $ Trs.isEmpty $ Prob.strictTrs prob = return $ T.NoProgress $ RTError $ ContainsStrictRule
| not $ Prob.isDPProblem prob = return $ T.NoProgress $ RTError $ NonDPProblemGiven
| null labTails = return $ T.NoProgress proof
| otherwise = return $ T.Progress proof (enumeration' [prob'])
where labTails = concatMap mkPairs $ Set.toList $ computeTails initials Set.empty
where initials = [ n | (n,cn) <- withNodeLabels' cwdg $ leafs cwdg
, onlyWeaks cn ]
ls = Trs.fromRules $ map (snd . snd) labTails
computeTails [] lfs = lfs
computeTails (n:ns) lfs | n `Set.member` lfs = computeTails ns lfs
| otherwise = computeTails (ns++preds) lfs'
where (lpreds, _, cn, lsucs) = Graph.context cwdg n
sucs = map snd lsucs
preds = map snd lpreds
lfs' = if Set.fromList sucs `Set.isSubsetOf` lfs && (onlyWeaks cn)
then Set.insert n lfs
else lfs
mkPairs n = theSCC $ lookupNodeLabel' cwdg n
wdg = estimatedDependencyGraph defaultApproximation prob
cwdg = toCongruenceGraph wdg
sig = Prob.signature prob
vars = Prob.variables prob
proof = RTProof { removables = labTails
, graph = wdg
, cgraph = cwdg
, signature = sig
, variables = vars }
prob' = prob { Prob.strictDPs = Prob.strictDPs prob Trs.\\ ls
, Prob.weakDPs = Prob.weakDPs prob Trs.\\ ls }
removeWeakSuffixProcessor :: T.Transformation RemoveWeakSuffix P.AnyProcessor
removeWeakSuffixProcessor = T.Transformation RemoveWeakSuffix
-- | Removes trailing weak paths.
-- A dependency pair is on a trailing weak path if it is from the weak components and all sucessors in the dependency graph
-- are on trailing weak paths.
--
-- Only applicable on DP-problems as obtained by 'dependencyPairs' or 'dependencyTuples'. Also
-- not applicable when @strictTrs prob \= Trs.empty@.
removeWeakSuffix :: T.TheTransformer RemoveWeakSuffix
removeWeakSuffix = T.Transformation RemoveWeakSuffix `T.withArgs` ()
--------------------------------------------------------------------------------
--- Simplify DP-RHSs
data SimpRHS = SimpRHS
data SimpRHSProof = SRHSProof { srhsReplacedRules :: [Rule] -- ^ Rules that could be simplified.
, srhsDG :: DG -- ^ Employed dependency graph.
, srhsSig :: F.Signature
, srhsVars :: V.Variables}
| SRHSError DPError
instance T.TransformationProof SimpRHS where
answer = T.answerFromSubProof
pprintTProof _ _ (SRHSError e) _ = pprint e
pprintTProof _ _ p _
| null repls = text "No rule was simplified"
| otherwise =
paragraph "Due to missing edges in the dependency-graph, the right-hand sides of following rules could be simplified:"
$+$ text ""
$+$ indent (pprint (Trs.fromRules repls, sig, vars))
where
vars = srhsVars p
sig = srhsSig p
repls = srhsReplacedRules p
tproofToXml _ _ (SRHSError e) = ("simpRHS", [errorToXml e])
tproofToXml _ _ p =
( "simpRHS"
, [ DG.toXml (dg, sig, vars)
, Xml.elt "simplified" [] [ XmlE.rule r Nothing sig vars
| r <- srhsReplacedRules p]
]
)
where
vars = srhsVars p
dg = srhsDG p
sig = srhsSig p
instance T.Transformer SimpRHS where
name _ = "simpDPRHS"
type ArgumentsOf SimpRHS = Unit
type ProofOf SimpRHS = SimpRHSProof
arguments _ = Unit
description _ = [unwords [ "Simplify right hand sides of dependency pairs by removing marked subterms "
, "whose root symbols are undefined."
, "Only applicable if the strict component is empty."
]
]
transform _ prob
| not (Trs.isEmpty strs) = return $ T.NoProgress $ SRHSError ContainsStrictRule
| not $ Prob.isDPProblem prob = return $ T.NoProgress $ SRHSError $ NonDPProblemGiven
| progr = return $ T.Progress proof (enumeration' [prob'])
| otherwise = return $ T.NoProgress proof
where proof = SRHSProof { srhsReplacedRules = [rule | (_, _, rule, Just _) <- elims]
, srhsDG = wdg
, srhsSig = sig
, srhsVars = Prob.variables prob }
strs = Prob.strictTrs prob
(c,sig) = Sig.runSignature (F.fresh (F.defaultAttribs "c" 0) { F.symIsCompound = True }) (Prob.signature prob)
wdg = estimatedDependencyGraph defaultApproximation prob
progr = any (\ (_,_,_,mr) -> isJust mr) elims
elims = [(n, s, rule, elim n rule) | (n,(s,rule)) <- lnodes wdg]
where elim n (Rule l r@(Term.Fun f rs))
| F.isCompound sig f = elim' n l rs
| otherwise = elim' n l [r]
elim n (Rule l r) = elim' n l [r]
elim' n l rs | length rs == length rs' = Nothing
| otherwise = Just $ Rule l (Term.Fun c rs')
where rs' = [ ri | (i,ri) <- zip [1..] rs
, any (\ (_,_, j) -> i == j) succs ]
succs = lsuccessors wdg n
prob' = Prob.withFreshCompounds prob { Prob.strictDPs = toTrs stricts
, Prob.weakDPs = toTrs weaks
, Prob.signature = sig }
where (stricts, weaks) = partition (\ (_, s, _, _) -> s == StrictDP) elims
toTrs l = Trs.fromRules [ fromMaybe r mr | (_,_,r,mr) <- l ]
simpDPRHSProcessor :: T.Transformation SimpRHS P.AnyProcessor
simpDPRHSProcessor = T.Transformation SimpRHS
-- | Simplifies right-hand sides of dependency pairs.
-- Removes r_i from right-hand side @c_n(r_1,...,r_n)@ if no instance of
-- r_i can be rewritten.
--
-- Only applicable on DP-problems as obtained by 'dependencyPairs' or 'dependencyTuples'. Also
-- not applicable when @strictTrs prob \= Trs.empty@.
simpDPRHS :: T.TheTransformer SimpRHS
simpDPRHS = T.Transformation SimpRHS `T.withArgs` ()
--------------------------------------------------------------------------------
--- 'Knowledge propagation'
data SimpPE p = SimpPE
data SimpPESelection =
SimpPESelection { skpNode :: NodeId -- ^ Node of selected rule in the dependency graph
, skpRule :: Rule -- ^ Selected rule
, skpPredecessors :: [(NodeId,Rule)]-- ^ Predecessors of rules
}
data SimpPEProof p =
SimpPEProof { skpDG :: DG
, skpSelections :: [SimpPESelection]
, skpSig :: F.Signature
, skpVars :: V.Variables}
| SimpPEPProof { skpDG :: DG
, skpSig :: F.Signature
, skpPProof :: P.PartialProof (P.ProofOf p)
, skpPProc :: P.InstanceOf p
, skpSelections :: [SimpPESelection]
, skpVars :: V.Variables}
| SimpPEErr DPError
instance P.Processor p => T.TransformationProof (SimpPE p) where
answer proof =
case T.transformationProof proof of
SimpPEErr _ -> P.MaybeAnswer
SimpPEProof {} -> T.answerFromSubProof proof
tproof@SimpPEPProof{} ->
case u1 `Cert.add` u2 of
Cert.Unknown -> P.MaybeAnswer
u -> P.CertAnswer $ Cert.certified ( Cert.constant, u)
where ub p = Cert.upperBound $ P.certificate p
u1 = ub $ skpPProof tproof
u2 = ub $ T.answerFromSubProof proof
pprintTProof _ _ (SimpPEErr e) _ = pprint e
pprintTProof _ _ p@(SimpPEProof {}) _
| null sel = text "Predecessor estimation is not applicable on selected rules."
| otherwise =
paragraph (show $
text "We estimate the number of application of"
<+> ppEstimated
<+> text "by applications of"
<+> text "Pre" <> parens (ppEstimated) <+> text "=" <+> ppPredecessors <> text "."
<+> text "Here rules are labeled as follows:")
$+$ text ""
$+$ indent (pprintLabeledRules "DPs" sig vars ldps)
where
vars = skpVars p
sig = skpSig p
ldps = [(n,r) | (n, (_, r)) <- lnodes $ skpDG p]
sel = skpSelections p
ppNS = pprintNodeSet . snub
ppEstimated = ppNS [skpNode s | s <- sel]
ppPredecessors = ppNS $ [ n | s <- sel, (n,_) <- skpPredecessors s]
pprintTProof _ _ p@(SimpPEPProof {}) _ =
ppSub
$+$ text ""
$+$ if null sel
then paragraph "The strictly oriented rules are moved into the weak component."
else paragraph "We return to the main proof. Consider the set of all dependency pairs"
$+$ text ""
$+$ pprintLabeledRules "" sig vars [(n,r) | (n, (_, r)) <- lnodes dg]
$+$ text ""
$+$ paragraph (show $ text "Processor"
<+> text pName
<+> text "induces the complexity certificate "
<+> pprint ans
<+> text "on application of dependency pairs"
<+> pprintNodeSet (Set.toList orientedNodes) <> text "."
<+> text "These cover all (indirect) predecessors of dependency pairs"
<+> pprintNodeSet (Set.toList knownNodes) <> text ","
<+> text "their number of application is equally bounded."
<+> text "The dependency pairs are shifted into the weak component.")
where vars = skpVars p
sig = skpSig p
dg = skpDG p
sel = skpSelections p
pproof = skpPProof p
ans = P.answer pproof
pName = "'" ++ P.instanceName (skpPProc p) ++ "'"
dps = Trs.fromRules $ P.ppRemovableDPs pproof
ldps = [(n,r) | (n, (_, r)) <- lnodes dg, Trs.member dps r]
trs = Trs.fromRules $ P.ppRemovableTrs pproof
orientedNodes = Set.fromList [ n | (n,_) <- ldps]
knownNodes = orientedNodes `Set.union` Set.fromList [ skpNode s | s <- sel]
ppSub | not $ P.progressed pproof = paragraph $ "Application of processor " ++ pName ++ " failed."
| otherwise =
paragraph ("We use the processor "
++ pName
++ " to orient following rules strictly. ")
$+$ text ""
$+$ pprintLabeledRules "DPs" sig vars ldps
$+$ pprintNamedTrs sig vars "Trs" trs
$+$ text ""
$+$ block' "Sub-proof" [P.pprintProof pproof P.ProofOutput]
tproofToXml _ _ (SimpPEErr e) = ("simpPE", [errorToXml e])
tproofToXml _ _ p@(SimpPEProof {}) =
( "simpPE"
, [ DG.toXml (dg, sig, vars)
, Xml.elt "pe" [] $ concat
[ [ XmlE.rule r (Just n) sig vars
, Xml.elt "predecessors" [] [ XmlE.rule s (Just m) sig vars | (m,s) <- rs ]
]
| SimpPESelection n r rs <- skpSelections p ]
]
)
where
vars = skpVars p
sig = skpSig p
dg = skpDG p
tproofToXml _ _ p@(SimpPEPProof {}) =
( "simpPE"
, [ DG.toXml (dg, sig, vars)
, Xml.elt "pe" [] $ concat
[ [ XmlE.rule r (Just n) sig vars
, Xml.elt "predecessors" [] [ XmlE.rule s (Just m) sig vars | (m,s) <- rs ]
]
| SimpPESelection n r rs <- skpSelections p ]
, P.toXml (skpPProof p)
]
)
where
vars = skpVars p
sig = skpSig p
dg = skpDG p
instance (P.Processor p) => T.Transformer (SimpPE p) where
name _ = "simpPE"
type ArgumentsOf (SimpPE p) = Arg (Assoc (RS.ExpressionSelector)) :+: Arg (Maybe (Proc p))
type ProofOf (SimpPE p) = SimpPEProof p
arguments _ =
opt { A.name = "select"
, A.defaultValue = RS.selAllOf RS.selDPs
, A.description = "Determines which rules to select. Per default all dependency pairs are selected for knowledge propagation."
}
:+: opt { A.name = "relative-processor"
, A.defaultValue = Nothing
, A.description = "If given, used to orient predecessors of selected rules."
}
description SimpPE = [unwords [ "Moves a strict dependency into the weak component"
, "if all predecessors in the dependency graph are strict"
, "and there is no edge from the rule to itself."
, "Only applicable if the strict component is empty."]
]
transform inst prob
| not $ Prob.isDPProblem prob = return $ T.NoProgress $ SimpPEErr $ NonDPProblemGiven
| otherwise = transform' mpinst
where wdg = estimatedDependencyGraph defaultApproximation prob
selector :+: mpinst = T.transformationArgs inst
-- strs = Prob.strictTrs prob
sdps = Prob.strictDPs prob
wdps = Prob.weakDPs prob
mkSel n rl preds = SimpPESelection { skpNode = n
, skpRule = rl
, skpPredecessors = [ (m,rlm) | (m, (_,rlm), _) <- preds] }
transform' Nothing | null selected = return $ T.NoProgress proof
| otherwise = return $ T.Progress proof (enumeration' [prob'])
where selected = select (sort candidates) []
select [] sel = sel
select (c:cs) sel = select cs sel'
where sel' | any (c `isPredecessorOf`) sel = sel
| otherwise = c:sel
s1 `isPredecessorOf` s2 = skpNode s2 `elem` reachablesBfs wdg [skpNode s1]
sort cs = reverse $ catMaybes [ find (\ c -> skpNode c == n) cs | n <- topsort wdg]
initialDPs = fst $ RS.rules $ RS.rsSelect (RS.selFirstAlternative selector) prob
candidates = [ mkSel n rl preds
| (n,(StrictDP, rl)) <- lnodes wdg
, Trs.member initialDPs rl
, let preds = lpredecessors wdg n
, all (\ (m,(strictness,_),_) -> m /= n && strictness == StrictDP) preds ]
proof :: T.ProofOf (SimpPE p)
proof = SimpPEProof { skpDG = wdg
, skpSelections = selected
, skpSig = Prob.signature prob
, skpVars = Prob.variables prob}
shiftStrict = Trs.fromRules [r | s <- selected , (_,r) <- skpPredecessors s ]
shiftWeak = Trs.fromRules [ skpRule s | s <- selected ]
prob' = prob { Prob.strictDPs = (sdps Trs.\\ shiftWeak) `Trs.union` shiftStrict
, Prob.weakDPs = (wdps `Trs.union` shiftWeak) Trs.\\ shiftStrict }
transform' (Just pinst) = do
pp <- P.solvePartial pinst (withPredecessors $ RS.rsSelect selector prob) prob
return $ mkProof pinst pp
where withPredecessors (P.SelectDP d) = P.BigOr $ P.SelectDP d : preds
where preds =
case lookupNode wdg (StrictDP, d) `mplus` lookupNode wdg (WeakDP, d) of
Just n -> [ withPreds n (Set.singleton n)]
Nothing -> []
withPredecessors (P.SelectTrs ss) = P.SelectTrs ss
withPredecessors (P.BigOr ss) = P.BigOr [withPredecessors s | s <- ss]
withPredecessors (P.BigAnd ss) = P.BigAnd [withPredecessors s | s <- ss]
withPreds n seen = bigAnd [ if n' `Set.member` seen
then P.SelectDP r'
else P.BigOr [P.SelectDP r', withPreds n' (n' `Set.insert` seen) ]
| (n',r') <- preds ]
where preds = snub [ (n', r') | (n',(_,r'),_) <- lpredecessors wdg n]
bigAnd [a] = a
bigAnd as = P.BigAnd as
mkProof :: P.Processor p => P.InstanceOf p -> P.PartialProof (P.ProofOf p) -> T.Result (SimpPE p)
mkProof proc p | progressed = T.Progress proof (enumeration' [prob'])
| otherwise = T.NoProgress proof
where proof = SimpPEPProof { skpDG = wdg
, skpSelections = propagated
, skpSig = Prob.signature prob
, skpPProof = p
, skpPProc = proc
, skpVars = Prob.variables prob}
(known, propagated) = propagate (Trs.fromRules $ P.ppRemovableDPs p) []
propagate seen props
| null newp = (seen, props)
| otherwise = propagate (newr `Trs.union` seen) (newp ++ props)
where newr = Trs.fromRules [ skpRule s | s <- newp]
newp = [ mkSel n rl preds
| (n,(_, rl)) <- lnodes wdg
, not (Trs.member seen rl)
, let preds = lpredecessors wdg n
, all (\ (_,(_,rl'),_) -> Trs.member seen rl') preds]
shiftWeak = sdps `Trs.intersect` known
progressed = P.progressed p && not (Trs.isEmpty shiftWeak)
prob' = prob { Prob.strictDPs = (sdps Trs.\\ shiftWeak)
, Prob.weakDPs = (wdps `Trs.union` shiftWeak) }
simpPEProcessor :: T.Transformation (SimpPE P.AnyProcessor) P.AnyProcessor
simpPEProcessor = T.Transformation SimpPE
-- | Moves a strict dependency into the weak component
-- if all predecessors in the dependency graph are strict
-- and there is no edge from the rule to itself.
simpPE :: T.TheTransformer (SimpPE P.AnyProcessor)
simpPE = T.Transformation SimpPE `T.withArgs` (RS.selAllOf RS.selDPs :+: Nothing)
simpPEOn :: RS.ExpressionSelector -> T.TheTransformer (SimpPE P.AnyProcessor)
simpPEOn rs = T.Transformation SimpPE `T.withArgs` (rs :+: Nothing)
withPEOn :: P.Processor p => P.InstanceOf p -> RS.ExpressionSelector -> T.TheTransformer (SimpPE p)
inst `withPEOn` rs = T.Transformation SimpPE `T.withArgs` (rs :+: Just inst)
----------------------------------------------------------------------
-- Trivial
data Trivial = Trivial
data TrivialProof = TrivialProof { trivialCDG :: CDG -- ^ Employed congruence graph.
, trivialDG :: DG -- ^ Employed dg
, trivialSig :: F.Signature
, trivialVars :: V.Variables}
| TrivialError DPError
| TrivialFail
instance T.TransformationProof Trivial where
answer _ = P.CertAnswer $ Cert.certified (Cert.constant, Cert.constant)
pprintTProof _ _ (TrivialError e) _ = pprint e
pprintTProof _ _ TrivialFail _ = text "The DP problem is not trivial."
pprintTProof _ _ _ _ =
paragraph "The dependency graph contains no loops, we remove all dependency pairs."
tproofToXml _ _ (TrivialError err) = ("trivial", [errorToXml err])
tproofToXml _ _ p = ("trivial", [DG.toXml (dg, sig, vars)])
where
dg = trivialDG p
sig = trivialSig p
vars = trivialVars p
instance T.Transformer Trivial where
name Trivial = "trivial"
description Trivial = [unwords [ "Checks wether the DP problem is trivial, i.e. the dependency graph contains no loops."
, "Only applicable if the strict component is empty."]
]
type ArgumentsOf Trivial = Unit
type ProofOf Trivial = TrivialProof
arguments Trivial = Unit
transform _ prob
| not $ Trs.isEmpty $ Prob.strictTrs prob = return $ T.NoProgress $ TrivialError $ ContainsStrictRule
| not $ Prob.isDPProblem prob = return $ T.NoProgress $ TrivialError $ NonDPProblemGiven
| cyclic = return $ T.NoProgress $ proof
| Trs.isEmpty $ Prob.dpComponents prob = return $ T.NoProgress $ TrivialError $ NotApplicable $ text "contains no DPs"
| otherwise = return $ T.Progress proof (enumeration' [prob'])
where cyclic = any (isCyclicNode cwdg) (nodes cwdg)
wdg = estimatedDependencyGraph defaultApproximation prob
cwdg = toCongruenceGraph wdg
sig = Prob.signature prob
vars = Prob.variables prob
proof = TrivialProof { trivialCDG = cwdg
, trivialSig = sig
, trivialDG = wdg
, trivialVars = vars }
prob' = prob { Prob.strictDPs = Trs.empty
, Prob.weakDPs = Trs.empty }
trivialProcessor :: T.Transformation Trivial P.AnyProcessor
trivialProcessor = T.Transformation Trivial
-- | Checks whether the DP problem is trivial, i.e., does not contain any cycles.
--
-- Only applicable on DP-problems as obtained by 'dependencyPairs' or 'dependencyTuples'. Also
-- not applicable when @strictTrs prob \= Trs.empty@.
trivial :: T.TheTransformer Trivial
trivial = T.Transformation Trivial `T.withArgs` ()
----------------------------------------------------------------------
-- Inapplicable
data RemoveInapplicable = RemoveInapplicable
data RemoveInapplicableProof =
RemoveInapplicableProof { riWDG :: DG -- ^ Employed dependency graph.
, riInitials :: [(NodeId,Rule)] -- ^ Nodes that start a dependency derivation
, riReachable :: [(NodeId,Rule)] -- ^ Nodes reachable from initial nodes
, riNonReachable :: [(NodeId,Rule)] -- ^ Nodes /not/ reachable from initial nodes
, riSig :: F.Signature
, riVars :: V.Variables}
| RemoveInapplicableError DPError
| RemoveInapplicableFail
instance T.TransformationProof RemoveInapplicable where
answer = T.answerFromSubProof
pprintTProof _ _ (RemoveInapplicableError e) _ = pprint e
pprintTProof _ _ RemoveInapplicableFail _ = text "The DP problem could not be simplified."
pprintTProof _ _ p _ =
text "Consider the dependency graph:"
$+$ text ""
$+$ indent (pprint (wdg,sig,vars))
$+$ text ""
$+$ paragraph (show $
if null (riReachable p)
then text "No dependency pair can be employed in a derivation starting from a marked basic term."
else text "Only the nodes"
<+> pprintNodeSet (map fst $ riReachable p)
<+> text "are reachable from nodes"
<+> pprintNodeSet (map fst $ riInitials p)
<+> text "that start derivation from marked basic terms."
<+> text "The nodes not reachable are removed from the problem.")
where
vars = riVars p
sig = riSig p
wdg = riWDG p
tproofToXml _ _ (RemoveInapplicableError err) = ("removeinapplicable", [errorToXml err])
tproofToXml _ _ RemoveInapplicableFail = ("removeinapplicable", [])
tproofToXml _ _ p =
("removeinapplicable"
, [ DG.toXml (wdg,sig,vars)
, Xml.elt "initial" [ ] [ XmlE.rule r (Just i) sig vars | (i,r) <- riInitials p]
, Xml.elt "reachable" [ ] [ XmlE.rule r (Just i) sig vars | (i,r) <- riReachable p]
, Xml.elt "nonreachable" [ ] [ XmlE.rule r (Just i) sig vars | (i,r) <- riNonReachable p]
]
)
where
vars = riVars p
sig = riSig p
wdg = riWDG p
instance T.Transformer RemoveInapplicable where
name RemoveInapplicable = "removeInapplicable"
description RemoveInapplicable = [unwords [ "Removes rules that are not applicable in DP derivations."] ]
type ArgumentsOf RemoveInapplicable = Unit
type ProofOf RemoveInapplicable = RemoveInapplicableProof
arguments RemoveInapplicable = Unit
transform _ prob
| not $ Prob.isDPProblem prob = return $ T.NoProgress $ RemoveInapplicableError $ NonDPProblemGiven
| null lunreachables = return $ T.NoProgress RemoveInapplicableFail
| otherwise = return $ T.Progress proof (enumeration' [prob'])
where
constrs = Prob.constrs $ Prob.startTerms prob
linitials = [ tr | tr@(_, (_,r)) <- lns
, all (\ ti -> functionSymbols ti `Set.isSubsetOf` constrs) (properSubterms $ lhs r) ]
reachables = reachablesDfs wdg (map fst linitials)
lreachables = withNodeLabels' wdg reachables
lunreachables = [ ln | ln <- lns , not $ (fst ln) `Set.member` rs ]
where rs = Set.fromList reachables
prob' = prob { Prob.strictDPs = Trs.fromRules [ r | (_,(StrictDP, r)) <- lreachables ]
, Prob.weakDPs = Trs.fromRules [ r | (_,(WeakDP,r)) <- lreachables ] }
proof = RemoveInapplicableProof { riWDG = wdg
, riSig = sig
, riInitials = toRS linitials
, riReachable = toRS lreachables
, riNonReachable = toRS lunreachables
, riVars = vars }
toRS ns = [(n,r) | (n,(_,r)) <- ns]
wdg = estimatedDependencyGraph defaultApproximation prob
lns = lnodes wdg
sig = Prob.signature prob
vars = Prob.variables prob
removeInapplicableProcessor :: T.Transformation RemoveInapplicable P.AnyProcessor
removeInapplicableProcessor = T.Transformation RemoveInapplicable
-- | Removes inapplicable rules in DP deriviations.
--
-- Currently we check whether the left-hand side is non-basic,
-- and there exists no incoming edge except from the same rule.
removeInapplicable :: T.TheTransformer RemoveInapplicable
removeInapplicable = T.Transformation RemoveInapplicable `T.withArgs` ()
|
mzini/TcT
|
source/Tct/Method/DP/Simplification.hs
|
gpl-3.0
| 37,169
| 0
| 23
| 13,904
| 8,901
| 4,744
| 4,157
| 589
| 1
|
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid 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.
--
-- grid 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 grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.LevelPuzzle.LevelPuzzleWorld.OutputState.Plain
(
OutputState (..),
makeOutputState,
) where
import MyPrelude
import Game.MEnv
data OutputState =
OutputState
{
outputstateCompleteColorIx :: !UInt,
outputstateCompleteColorIx' :: !UInt,
outputstateCompleteAlpha :: !Float,
outputstateCompleteTick :: !Tick,
outputstateSpecialCompleteTick :: !Tick
--outputstate
}
makeOutputState :: MEnv' OutputState
makeOutputState = do
return OutputState
{
outputstateCompleteColorIx = 0,
outputstateCompleteColorIx' = 0,
outputstateCompleteAlpha = 0.0,
outputstateCompleteTick = 0.0,
outputstateSpecialCompleteTick = 0.0
}
|
karamellpelle/grid
|
source/Game/LevelPuzzle/LevelPuzzleWorld/OutputState/Plain.hs
|
gpl-3.0
| 1,548
| 0
| 9
| 377
| 144
| 95
| 49
| 31
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- Copyright (C) 2012 John Millikin <jmillikin@gmail.com>
--
-- 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
-- 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 <http://www.gnu.org/licenses/>.
module Main
( tests
, main
) where
import Control.Monad.IO.Class (liftIO)
import qualified Data.Text as Text
import Test.Chell
import CPython
import CPython.Types.Module
suite_ProgramProperties :: Suite
suite_ProgramProperties = suite "program-properties"
test_ProgramName
test_PythonHome
test_ProgramName :: Test
test_ProgramName = assertions "program-name" $ do
do
name <- liftIO getProgramName
$expect (Text.isPrefixOf "python" name)
do
before <- liftIO getProgramName
liftIO (setProgramName "")
after <- liftIO getProgramName
$expect (equal before after)
do
liftIO (setProgramName "cpython-tests")
after <- liftIO getProgramName
$expect (equal after "cpython-tests")
test_PythonHome :: Test
test_PythonHome = assertions "python-home" $ do
do
defaultHome <- liftIO getPythonHome
$expect (equal defaultHome Nothing)
do
liftIO (setPythonHome (Just "/python/home"))
newHome <- liftIO getPythonHome
$expect (equal newHome (Just "/python/home"))
do
liftIO (setPythonHome Nothing)
newHome <- liftIO getPythonHome
$expect (equal newHome Nothing)
suite_Types :: Suite
suite_Types = suite "types"
suite_Module
suite_Module :: Suite
suite_Module = suite "module"
test_ImportModule
test_ImportModule :: Test
test_ImportModule = assertions "importModule" $ do
_ <- liftIO (importModule "os")
return ()
tests :: [Suite]
tests =
[ suite_ProgramProperties
, suite_Types
]
main :: IO ()
main = do
CPython.initialize
Test.Chell.defaultMain tests
CPython.finalize
|
jmillikin/haskell-cpython
|
tests/Tests.hs
|
gpl-3.0
| 2,319
| 22
| 14
| 412
| 499
| 246
| 253
| 60
| 1
|
module Point where
import Direction
import System.Random
newtype Point = Point { point :: (Int, Int) } deriving (Eq, Ord)
instance Show Point where
show (Point (x,y)) = "(" ++ (show x) ++ "," ++ (show y) ++ ")"
instance Num Point where
fromInteger 0 = Point (0,0)
fromInteger x' =
let x = fromIntegral x'
r = ((floor (((sqrt.fromIntegral) x)::Double)) + 1) `div` 2
ring_start = (2 * r - 1)^(2::Int)
top_bnd = ring_start + (2 * r + 1)
rgt_bnd = ring_start + (4 * r + 1)
bot_bnd = ring_start + (6 * r + 1)
offset = x - ring_start in
if x < top_bnd
then Point (-r + offset,r)
else if x < rgt_bnd
then Point (r, top_bnd - x + r - 1)
else if x < bot_bnd
then Point (r - (x - rgt_bnd) - 1, -r)
else Point (-r, x - bot_bnd - 1)
(Point (x1,y1)) + (Point (x2,y2)) = (Point ((x1 + x2), (y1 + y2)))
(Point (x1,y1)) * (Point (x2,y2)) = (Point ((x1 * x2), (y1 * y2))) -- This makes no sense
(Point (x1,y1)) - (Point (x2,y2)) = (Point ((x1 - x2), (y1 - y2)))
abs (Point (x,y)) = (Point (abs x, abs y))
signum (Point (x,y)) = (Point (signum x, signum y))
instance Real Point where
toRational = toRational.toInteger
instance Enum Point where
toEnum = fromInteger.fromIntegral
fromEnum = fromIntegral.toInteger
instance Integral Point where
quotRem (Point (x1,y1)) (Point (x2,y2)) = -- do you have a better idea?
(Point (quot x1 x2, quot y1 y2),
Point (rem x1 x2, rem y1 y2))
toInteger (Point (0,0)) = 0
toInteger (Point (x,y)) =
let x' = fromIntegral x
y' = fromIntegral y
ring = max (abs x') (abs y')
off = (2 * ring - 1)^(2::Int) in
if ring == y'
then x' + ring + off
else if ring == (abs y')
then (4 * ring) + off - x'
else if x > 0
then (2 * ring) + x' - y' + off
else (5 * ring) + y' - (2 * x') + off
instance Random Point where
randomR _ _ = undefined
random g =
let (l, g') = random g
(r, g'') = random g' in
(Point (l, r), g'')
zeroPoint :: Point
zeroPoint = Point (0,0)
move :: Point -> Direction -> Point
move (Point (x,y)) North = Point (x, y - 1)
move (Point (x,y)) NorthEast = Point (x + 1, y - 1)
move (Point (x,y)) East = Point (x + 1, y)
move (Point (x,y)) SouthEast = Point (x + 1, y + 1)
move (Point (x,y)) South = Point (x, y + 1)
move (Point (x,y)) SouthWest = Point (x - 1, y + 1)
move (Point (x,y)) West = Point (x - 1, y)
move (Point (x,y)) NorthWest = Point (x - 1, y - 1)
neighbors :: Point -> [Point]
neighbors p = map (move p) [North .. NorthWest]
-- TODO: Write this concisely.
directionTo :: Point -> Point -> Maybe Direction
directionTo (Point (a, b)) (Point (c, d)) =
if (a < c)
then if (b < d)
then Just NorthEast
else if (b > d)
then Just NorthWest
else Just North
else if (a > c)
then if (b < d)
then Just SouthEast
else if (b > d)
then Just SouthWest
else Just South
else if (b < d)
then Just East
else if (b > d)
then Just West
else Nothing
|
bhickey/catamad
|
src/Point.hs
|
gpl-3.0
| 3,247
| 0
| 19
| 1,062
| 1,639
| 893
| 746
| 88
| 9
|
module System.DevUtils.Base.Data.Map (
kvListToMap
) where
import qualified Data.Map as M
kvListToMap :: (Ord a) => [(a,b)] -> M.Map a b
kvListToMap xl = M.fromList xl
|
adarqui/DevUtils-Base
|
src/System/DevUtils/Base/Data/Map.hs
|
gpl-3.0
| 171
| 0
| 8
| 29
| 69
| 41
| 28
| 5
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Classroom.Courses.CourseWorkMaterials.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a course work material. This request must be made by the
-- Developer Console project of the [OAuth client
-- ID](https:\/\/support.google.com\/cloud\/answer\/6158849) used to create
-- the corresponding course work material item. This method returns the
-- following error codes: * \`PERMISSION_DENIED\` if the requesting
-- developer project did not create the corresponding course work material,
-- if the requesting user is not permitted to delete the requested course
-- or for access errors. * \`FAILED_PRECONDITION\` if the requested course
-- work material has already been deleted. * \`NOT_FOUND\` if no course
-- exists with the requested ID.
--
-- /See:/ <https://developers.google.com/classroom/ Google Classroom API Reference> for @classroom.courses.courseWorkMaterials.delete@.
module Network.Google.Resource.Classroom.Courses.CourseWorkMaterials.Delete
(
-- * REST Resource
CoursesCourseWorkMaterialsDeleteResource
-- * Creating a Request
, coursesCourseWorkMaterialsDelete
, CoursesCourseWorkMaterialsDelete
-- * Request Lenses
, ccwmdXgafv
, ccwmdUploadProtocol
, ccwmdCourseId
, ccwmdAccessToken
, ccwmdUploadType
, ccwmdId
, ccwmdCallback
) where
import Network.Google.Classroom.Types
import Network.Google.Prelude
-- | A resource alias for @classroom.courses.courseWorkMaterials.delete@ method which the
-- 'CoursesCourseWorkMaterialsDelete' request conforms to.
type CoursesCourseWorkMaterialsDeleteResource =
"v1" :>
"courses" :>
Capture "courseId" Text :>
"courseWorkMaterials" :>
Capture "id" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Deletes a course work material. This request must be made by the
-- Developer Console project of the [OAuth client
-- ID](https:\/\/support.google.com\/cloud\/answer\/6158849) used to create
-- the corresponding course work material item. This method returns the
-- following error codes: * \`PERMISSION_DENIED\` if the requesting
-- developer project did not create the corresponding course work material,
-- if the requesting user is not permitted to delete the requested course
-- or for access errors. * \`FAILED_PRECONDITION\` if the requested course
-- work material has already been deleted. * \`NOT_FOUND\` if no course
-- exists with the requested ID.
--
-- /See:/ 'coursesCourseWorkMaterialsDelete' smart constructor.
data CoursesCourseWorkMaterialsDelete =
CoursesCourseWorkMaterialsDelete'
{ _ccwmdXgafv :: !(Maybe Xgafv)
, _ccwmdUploadProtocol :: !(Maybe Text)
, _ccwmdCourseId :: !Text
, _ccwmdAccessToken :: !(Maybe Text)
, _ccwmdUploadType :: !(Maybe Text)
, _ccwmdId :: !Text
, _ccwmdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CoursesCourseWorkMaterialsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccwmdXgafv'
--
-- * 'ccwmdUploadProtocol'
--
-- * 'ccwmdCourseId'
--
-- * 'ccwmdAccessToken'
--
-- * 'ccwmdUploadType'
--
-- * 'ccwmdId'
--
-- * 'ccwmdCallback'
coursesCourseWorkMaterialsDelete
:: Text -- ^ 'ccwmdCourseId'
-> Text -- ^ 'ccwmdId'
-> CoursesCourseWorkMaterialsDelete
coursesCourseWorkMaterialsDelete pCcwmdCourseId_ pCcwmdId_ =
CoursesCourseWorkMaterialsDelete'
{ _ccwmdXgafv = Nothing
, _ccwmdUploadProtocol = Nothing
, _ccwmdCourseId = pCcwmdCourseId_
, _ccwmdAccessToken = Nothing
, _ccwmdUploadType = Nothing
, _ccwmdId = pCcwmdId_
, _ccwmdCallback = Nothing
}
-- | V1 error format.
ccwmdXgafv :: Lens' CoursesCourseWorkMaterialsDelete (Maybe Xgafv)
ccwmdXgafv
= lens _ccwmdXgafv (\ s a -> s{_ccwmdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ccwmdUploadProtocol :: Lens' CoursesCourseWorkMaterialsDelete (Maybe Text)
ccwmdUploadProtocol
= lens _ccwmdUploadProtocol
(\ s a -> s{_ccwmdUploadProtocol = a})
-- | Identifier of the course. This identifier can be either the
-- Classroom-assigned identifier or an alias.
ccwmdCourseId :: Lens' CoursesCourseWorkMaterialsDelete Text
ccwmdCourseId
= lens _ccwmdCourseId
(\ s a -> s{_ccwmdCourseId = a})
-- | OAuth access token.
ccwmdAccessToken :: Lens' CoursesCourseWorkMaterialsDelete (Maybe Text)
ccwmdAccessToken
= lens _ccwmdAccessToken
(\ s a -> s{_ccwmdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ccwmdUploadType :: Lens' CoursesCourseWorkMaterialsDelete (Maybe Text)
ccwmdUploadType
= lens _ccwmdUploadType
(\ s a -> s{_ccwmdUploadType = a})
-- | Identifier of the course work material to delete. This identifier is a
-- Classroom-assigned identifier.
ccwmdId :: Lens' CoursesCourseWorkMaterialsDelete Text
ccwmdId = lens _ccwmdId (\ s a -> s{_ccwmdId = a})
-- | JSONP
ccwmdCallback :: Lens' CoursesCourseWorkMaterialsDelete (Maybe Text)
ccwmdCallback
= lens _ccwmdCallback
(\ s a -> s{_ccwmdCallback = a})
instance GoogleRequest
CoursesCourseWorkMaterialsDelete
where
type Rs CoursesCourseWorkMaterialsDelete = Empty
type Scopes CoursesCourseWorkMaterialsDelete =
'["https://www.googleapis.com/auth/classroom.courseworkmaterials"]
requestClient CoursesCourseWorkMaterialsDelete'{..}
= go _ccwmdCourseId _ccwmdId _ccwmdXgafv
_ccwmdUploadProtocol
_ccwmdAccessToken
_ccwmdUploadType
_ccwmdCallback
(Just AltJSON)
classroomService
where go
= buildClient
(Proxy ::
Proxy CoursesCourseWorkMaterialsDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-classroom/gen/Network/Google/Resource/Classroom/Courses/CourseWorkMaterials/Delete.hs
|
mpl-2.0
| 6,885
| 0
| 18
| 1,441
| 798
| 473
| 325
| 118
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.FloodlightActivities.Generatetag
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Generates a tag for a floodlight activity.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.floodlightActivities.generatetag@.
module Network.Google.Resource.DFAReporting.FloodlightActivities.Generatetag
(
-- * REST Resource
FloodlightActivitiesGeneratetagResource
-- * Creating a Request
, floodlightActivitiesGeneratetag
, FloodlightActivitiesGeneratetag
-- * Request Lenses
, fagFloodlightActivityId
, fagProFileId
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.floodlightActivities.generatetag@ method which the
-- 'FloodlightActivitiesGeneratetag' request conforms to.
type FloodlightActivitiesGeneratetagResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"floodlightActivities" :>
"generatetag" :>
QueryParam "floodlightActivityId" (Textual Int64) :>
QueryParam "alt" AltJSON :>
Post '[JSON] FloodlightActivitiesGenerateTagResponse
-- | Generates a tag for a floodlight activity.
--
-- /See:/ 'floodlightActivitiesGeneratetag' smart constructor.
data FloodlightActivitiesGeneratetag = FloodlightActivitiesGeneratetag'
{ _fagFloodlightActivityId :: !(Maybe (Textual Int64))
, _fagProFileId :: !(Textual Int64)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'FloodlightActivitiesGeneratetag' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fagFloodlightActivityId'
--
-- * 'fagProFileId'
floodlightActivitiesGeneratetag
:: Int64 -- ^ 'fagProFileId'
-> FloodlightActivitiesGeneratetag
floodlightActivitiesGeneratetag pFagProFileId_ =
FloodlightActivitiesGeneratetag'
{ _fagFloodlightActivityId = Nothing
, _fagProFileId = _Coerce # pFagProFileId_
}
-- | Floodlight activity ID for which we want to generate a tag.
fagFloodlightActivityId :: Lens' FloodlightActivitiesGeneratetag (Maybe Int64)
fagFloodlightActivityId
= lens _fagFloodlightActivityId
(\ s a -> s{_fagFloodlightActivityId = a})
. mapping _Coerce
-- | User profile ID associated with this request.
fagProFileId :: Lens' FloodlightActivitiesGeneratetag Int64
fagProFileId
= lens _fagProFileId (\ s a -> s{_fagProFileId = a})
. _Coerce
instance GoogleRequest
FloodlightActivitiesGeneratetag where
type Rs FloodlightActivitiesGeneratetag =
FloodlightActivitiesGenerateTagResponse
type Scopes FloodlightActivitiesGeneratetag =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient FloodlightActivitiesGeneratetag'{..}
= go _fagProFileId _fagFloodlightActivityId
(Just AltJSON)
dFAReportingService
where go
= buildClient
(Proxy ::
Proxy FloodlightActivitiesGeneratetagResource)
mempty
|
rueshyna/gogol
|
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/FloodlightActivities/Generatetag.hs
|
mpl-2.0
| 4,013
| 0
| 15
| 874
| 429
| 252
| 177
| 70
| 1
|
module Main where
import Control.Monad
import Control.Monad.State
import Data.Char
import Data.Word8
import Text.Parsec
import Text.Parsec.String
type Byte = Word8
data Tape = Tape [Byte] [Byte] deriving (Show)
left :: Tape -> Tape
left (Tape (x:xs) ys) = Tape xs (x:ys)
left t = t
right :: Tape -> Tape
right (Tape xs (y:ys)) = Tape (y:xs) ys
right t = t
cur :: Tape -> Byte
cur (Tape _ (y:_)) = y
set :: Byte -> Tape -> Tape
set b (Tape xs (_:ys)) = Tape xs (b:ys)
type BF = StateT Tape IO ()
data Cmd = IncP | DecP | IncB | DecB | Out | In Byte | Loop [Cmd] deriving (Show)
validBytes :: [Byte]
validBytes = [0..]
parseByte :: Parser Byte
parseByte = do let chars = fmap (chr . fromIntegral) validBytes
c <- oneOf chars
return . fromIntegral . ord $ c
parseCmd :: Parser Cmd
parseCmd = choice [ char '>' >> return IncP
, char '<' >> return DecP
, char '+' >> return IncB
, char '-' >> return DecB
, char '.' >> return Out
, char ',' >> parseByte >>= return . In
, between (char '[') (char ']') (many1 parseCmd) >>= return . Loop
]
type Prog = [Cmd]
parseSep :: Parser ()
parseSep = void space <|> void endOfLine
parseProg :: Parser Prog
parseProg = between (optional parseSep) (optional parseSep) parseCmd `manyTill` eof
run :: Cmd -> BF
run cmd = case cmd of
IncP -> get >>= put . right
DecP -> get >>= put . left
IncB -> get >>= put . ((1 + ) . cur >>= set)
DecB -> get >>= put . (subtract 1 . cur >>= set)
Out -> get >>= liftIO . putChar . chr . fromIntegral . cur
In b -> get >>= put . set b
Loop cmds -> get >>= (\t -> put t >> unless (cur t == 0) (exec cmds >> run (Loop cmds)))
exec :: Prog -> BF
exec prog = forM_ prog run
main :: IO ()
main = do s <- getContents
prog <- either (error . show) return (parse parseProg "" s)
evalStateT (exec prog) $ Tape (repeat 0) (repeat 0)
|
vikraman/brainf-k
|
Main.hs
|
unlicense
| 2,065
| 0
| 17
| 647
| 910
| 470
| 440
| 55
| 7
|
module Main where
import TransputerSimulator as TS
import Transputer as T
import qualified Data.ByteString.Char8 as BC
transputer :: Transputer
transputer = T.Transputer {
_registers = T.Registers {
_iptr = 0, _wptr = 0, _areg = 0, _breg = 0, _creg = 0, _oreg = 0,
_sreg = T.StatusRegisters {
_errorFlag = False,
_moveBit = False,
_haltOnErr = False,
_gotoSnp = False,
_ioBit = False,
_timeIns = False,
_timeDel = False,
_distAndIns = False
}
},
_memory = BC.pack "",
_programEnd = 5,
_id = 1
}
main :: IO ()
main = do
TS.printUsage
putStrLn $ show transputer
putStrLn $ show (TS.step transputer)
|
rossng/transputer-simulator
|
app/Main.hs
|
apache-2.0
| 932
| 0
| 11
| 438
| 212
| 130
| 82
| 25
| 1
|
{-# LANGUAGE TemplateHaskell, DeriveFunctor #-}
{-| Some common Ganeti types.
This holds types common to both core work, and to htools. Types that
are very core specific (e.g. configuration objects) should go in
'Ganeti.Objects', while types that are specific to htools in-memory
representation should go into 'Ganeti.HTools.Types'.
-}
{-
Copyright (C) 2012, 2013, 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Types
( AllocPolicy(..)
, allocPolicyFromRaw
, allocPolicyToRaw
, InstanceStatus(..)
, instanceStatusFromRaw
, instanceStatusToRaw
, DiskTemplate(..)
, diskTemplateToRaw
, diskTemplateFromRaw
, diskTemplateMovable
, TagKind(..)
, tagKindToRaw
, tagKindFromRaw
, NonNegative
, fromNonNegative
, mkNonNegative
, Positive
, fromPositive
, mkPositive
, Negative
, fromNegative
, mkNegative
, NonEmpty
, fromNonEmpty
, mkNonEmpty
, NonEmptyString
, QueryResultCode
, IPv4Address
, mkIPv4Address
, IPv4Network
, mkIPv4Network
, IPv6Address
, mkIPv6Address
, IPv6Network
, mkIPv6Network
, MigrationMode(..)
, migrationModeToRaw
, VerifyOptionalChecks(..)
, verifyOptionalChecksToRaw
, DdmSimple(..)
, DdmFull(..)
, ddmFullToRaw
, CVErrorCode(..)
, cVErrorCodeToRaw
, Hypervisor(..)
, hypervisorFromRaw
, hypervisorToRaw
, OobCommand(..)
, oobCommandToRaw
, OobStatus(..)
, oobStatusToRaw
, StorageType(..)
, storageTypeToRaw
, EvacMode(..)
, evacModeToRaw
, FileDriver(..)
, fileDriverToRaw
, InstCreateMode(..)
, instCreateModeToRaw
, RebootType(..)
, rebootTypeToRaw
, ExportMode(..)
, exportModeToRaw
, IAllocatorTestDir(..)
, iAllocatorTestDirToRaw
, IAllocatorMode(..)
, iAllocatorModeToRaw
, NICMode(..)
, nICModeToRaw
, JobStatus(..)
, jobStatusToRaw
, jobStatusFromRaw
, FinalizedJobStatus(..)
, finalizedJobStatusToRaw
, JobId
, fromJobId
, makeJobId
, makeJobIdS
, RelativeJobId
, JobIdDep(..)
, JobDependency(..)
, absoluteJobDependency
, getJobIdFromDependency
, OpSubmitPriority(..)
, opSubmitPriorityToRaw
, parseSubmitPriority
, fmtSubmitPriority
, OpStatus(..)
, opStatusToRaw
, opStatusFromRaw
, ELogType(..)
, eLogTypeToRaw
, ReasonElem
, ReasonTrail
, StorageUnit(..)
, StorageUnitRaw(..)
, StorageKey
, addParamsToStorageUnit
, diskTemplateToStorageType
, VType(..)
, vTypeFromRaw
, vTypeToRaw
, NodeRole(..)
, nodeRoleToRaw
, roleDescription
, DiskMode(..)
, diskModeToRaw
, BlockDriver(..)
, blockDriverToRaw
, AdminState(..)
, adminStateFromRaw
, adminStateToRaw
, AdminStateSource(..)
, adminStateSourceFromRaw
, adminStateSourceToRaw
, StorageField(..)
, storageFieldToRaw
, DiskAccessMode(..)
, diskAccessModeToRaw
, LocalDiskStatus(..)
, localDiskStatusFromRaw
, localDiskStatusToRaw
, localDiskStatusName
, ReplaceDisksMode(..)
, replaceDisksModeToRaw
, RpcTimeout(..)
, rpcTimeoutFromRaw -- FIXME: no used anywhere
, rpcTimeoutToRaw
, HotplugTarget(..)
, hotplugTargetToRaw
, HotplugAction(..)
, hotplugActionToRaw
, SshKeyType(..)
, sshKeyTypeToRaw
, Private(..)
, showPrivateJSObject
, Secret(..)
, showSecretJSObject
, revealValInJSObject
, redacted
, HvParams
, OsParams
, OsParamsPrivate
, TimeStampObject(..)
, UuidObject(..)
, ForthcomingObject(..)
, SerialNoObject(..)
, TagsObject(..)
) where
import Control.Monad (liftM)
import qualified Text.JSON as JSON
import Text.JSON (JSON, readJSON, showJSON)
import Data.Ratio (numerator, denominator)
import System.Time (ClockTime)
import qualified Ganeti.ConstantUtils as ConstantUtils
import Ganeti.JSON (Container, HasStringRepr(..))
import qualified Ganeti.THH as THH
import Ganeti.THH.Field (TagSet)
import Ganeti.Utils
-- * Generic types
-- | Type that holds a non-negative value.
newtype NonNegative a = NonNegative { fromNonNegative :: a }
deriving (Show, Eq, Ord)
-- | Smart constructor for 'NonNegative'.
mkNonNegative :: (Monad m, Num a, Ord a, Show a) => a -> m (NonNegative a)
mkNonNegative i | i >= 0 = return (NonNegative i)
| otherwise = fail $ "Invalid value for non-negative type '" ++
show i ++ "'"
instance (JSON.JSON a, Num a, Ord a, Show a) => JSON.JSON (NonNegative a) where
showJSON = JSON.showJSON . fromNonNegative
readJSON v = JSON.readJSON v >>= mkNonNegative
-- | Type that holds a positive value.
newtype Positive a = Positive { fromPositive :: a }
deriving (Show, Eq, Ord)
-- | Smart constructor for 'Positive'.
mkPositive :: (Monad m, Num a, Ord a, Show a) => a -> m (Positive a)
mkPositive i | i > 0 = return (Positive i)
| otherwise = fail $ "Invalid value for positive type '" ++
show i ++ "'"
instance (JSON.JSON a, Num a, Ord a, Show a) => JSON.JSON (Positive a) where
showJSON = JSON.showJSON . fromPositive
readJSON v = JSON.readJSON v >>= mkPositive
-- | Type that holds a negative value.
newtype Negative a = Negative { fromNegative :: a }
deriving (Show, Eq, Ord)
-- | Smart constructor for 'Negative'.
mkNegative :: (Monad m, Num a, Ord a, Show a) => a -> m (Negative a)
mkNegative i | i < 0 = return (Negative i)
| otherwise = fail $ "Invalid value for negative type '" ++
show i ++ "'"
instance (JSON.JSON a, Num a, Ord a, Show a) => JSON.JSON (Negative a) where
showJSON = JSON.showJSON . fromNegative
readJSON v = JSON.readJSON v >>= mkNegative
-- | Type that holds a non-null list.
newtype NonEmpty a = NonEmpty { fromNonEmpty :: [a] }
deriving (Show, Eq, Ord)
-- | Smart constructor for 'NonEmpty'.
mkNonEmpty :: (Monad m) => [a] -> m (NonEmpty a)
mkNonEmpty [] = fail "Received empty value for non-empty list"
mkNonEmpty xs = return (NonEmpty xs)
instance (JSON.JSON a) => JSON.JSON (NonEmpty a) where
showJSON = JSON.showJSON . fromNonEmpty
readJSON v = JSON.readJSON v >>= mkNonEmpty
-- | A simple type alias for non-empty strings.
type NonEmptyString = NonEmpty Char
type QueryResultCode = Int
newtype IPv4Address = IPv4Address { fromIPv4Address :: String }
deriving (Show, Eq, Ord)
-- FIXME: this should check that 'address' is a valid ip
mkIPv4Address :: Monad m => String -> m IPv4Address
mkIPv4Address address =
return IPv4Address { fromIPv4Address = address }
instance JSON.JSON IPv4Address where
showJSON = JSON.showJSON . fromIPv4Address
readJSON v = JSON.readJSON v >>= mkIPv4Address
newtype IPv4Network = IPv4Network { fromIPv4Network :: String }
deriving (Show, Eq, Ord)
-- FIXME: this should check that 'address' is a valid ip
mkIPv4Network :: Monad m => String -> m IPv4Network
mkIPv4Network address =
return IPv4Network { fromIPv4Network = address }
instance JSON.JSON IPv4Network where
showJSON = JSON.showJSON . fromIPv4Network
readJSON v = JSON.readJSON v >>= mkIPv4Network
newtype IPv6Address = IPv6Address { fromIPv6Address :: String }
deriving (Show, Eq, Ord)
-- FIXME: this should check that 'address' is a valid ip
mkIPv6Address :: Monad m => String -> m IPv6Address
mkIPv6Address address =
return IPv6Address { fromIPv6Address = address }
instance JSON.JSON IPv6Address where
showJSON = JSON.showJSON . fromIPv6Address
readJSON v = JSON.readJSON v >>= mkIPv6Address
newtype IPv6Network = IPv6Network { fromIPv6Network :: String }
deriving (Show, Eq, Ord)
-- FIXME: this should check that 'address' is a valid ip
mkIPv6Network :: Monad m => String -> m IPv6Network
mkIPv6Network address =
return IPv6Network { fromIPv6Network = address }
instance JSON.JSON IPv6Network where
showJSON = JSON.showJSON . fromIPv6Network
readJSON v = JSON.readJSON v >>= mkIPv6Network
-- * Ganeti types
-- | Instance disk template type. The disk template is a name for the
-- constructor of the disk configuration 'DiskLogicalId' used for
-- serialization, configuration values, etc.
$(THH.declareLADT ''String "DiskTemplate"
[ ("DTDiskless", "diskless")
, ("DTFile", "file")
, ("DTSharedFile", "sharedfile")
, ("DTPlain", "plain")
, ("DTBlock", "blockdev")
, ("DTDrbd8", "drbd")
, ("DTRbd", "rbd")
, ("DTExt", "ext")
, ("DTGluster", "gluster")
])
$(THH.makeJSONInstance ''DiskTemplate)
instance THH.PyValue DiskTemplate where
showValue = show . diskTemplateToRaw
instance HasStringRepr DiskTemplate where
fromStringRepr = diskTemplateFromRaw
toStringRepr = diskTemplateToRaw
-- | Predicate on disk templates indicating if instances based on this
-- disk template can freely be moved (to any node in the node group).
diskTemplateMovable :: DiskTemplate -> Bool
-- Note: we deliberately do not use wildcard pattern to force an
-- update of this function whenever a new disk template is added.
diskTemplateMovable DTDiskless = True
diskTemplateMovable DTFile = False
diskTemplateMovable DTSharedFile = True
diskTemplateMovable DTPlain = False
diskTemplateMovable DTBlock = False
diskTemplateMovable DTDrbd8 = False
diskTemplateMovable DTRbd = True
diskTemplateMovable DTExt = True
diskTemplateMovable DTGluster = True
-- | Data type representing what items the tag operations apply to.
$(THH.declareLADT ''String "TagKind"
[ ("TagKindInstance", "instance")
, ("TagKindNode", "node")
, ("TagKindGroup", "nodegroup")
, ("TagKindCluster", "cluster")
, ("TagKindNetwork", "network")
])
$(THH.makeJSONInstance ''TagKind)
-- | The Group allocation policy type.
--
-- Note that the order of constructors is important as the automatic
-- Ord instance will order them in the order they are defined, so when
-- changing this data type be careful about the interaction with the
-- desired sorting order.
$(THH.declareLADT ''String "AllocPolicy"
[ ("AllocPreferred", "preferred")
, ("AllocLastResort", "last_resort")
, ("AllocUnallocable", "unallocable")
])
$(THH.makeJSONInstance ''AllocPolicy)
-- | The Instance real state type.
$(THH.declareLADT ''String "InstanceStatus"
[ ("StatusDown", "ADMIN_down")
, ("StatusOffline", "ADMIN_offline")
, ("ErrorDown", "ERROR_down")
, ("ErrorUp", "ERROR_up")
, ("NodeDown", "ERROR_nodedown")
, ("NodeOffline", "ERROR_nodeoffline")
, ("Running", "running")
, ("UserDown", "USER_down")
, ("WrongNode", "ERROR_wrongnode")
])
$(THH.makeJSONInstance ''InstanceStatus)
-- | Migration mode.
$(THH.declareLADT ''String "MigrationMode"
[ ("MigrationLive", "live")
, ("MigrationNonLive", "non-live")
])
$(THH.makeJSONInstance ''MigrationMode)
-- | Verify optional checks.
$(THH.declareLADT ''String "VerifyOptionalChecks"
[ ("VerifyNPlusOneMem", "nplusone_mem")
])
$(THH.makeJSONInstance ''VerifyOptionalChecks)
-- | Cluster verify error codes.
$(THH.declareLADT ''String "CVErrorCode"
[ ("CvECLUSTERCFG", "ECLUSTERCFG")
, ("CvECLUSTERCERT", "ECLUSTERCERT")
, ("CvECLUSTERCLIENTCERT", "ECLUSTERCLIENTCERT")
, ("CvECLUSTERFILECHECK", "ECLUSTERFILECHECK")
, ("CvECLUSTERDANGLINGNODES", "ECLUSTERDANGLINGNODES")
, ("CvECLUSTERDANGLINGINST", "ECLUSTERDANGLINGINST")
, ("CvEINSTANCEBADNODE", "EINSTANCEBADNODE")
, ("CvEINSTANCEDOWN", "EINSTANCEDOWN")
, ("CvEINSTANCELAYOUT", "EINSTANCELAYOUT")
, ("CvEINSTANCEMISSINGDISK", "EINSTANCEMISSINGDISK")
, ("CvEINSTANCEFAULTYDISK", "EINSTANCEFAULTYDISK")
, ("CvEINSTANCEWRONGNODE", "EINSTANCEWRONGNODE")
, ("CvEINSTANCESPLITGROUPS", "EINSTANCESPLITGROUPS")
, ("CvEINSTANCEPOLICY", "EINSTANCEPOLICY")
, ("CvEINSTANCEUNSUITABLENODE", "EINSTANCEUNSUITABLENODE")
, ("CvEINSTANCEMISSINGCFGPARAMETER", "EINSTANCEMISSINGCFGPARAMETER")
, ("CvENODEDRBD", "ENODEDRBD")
, ("CvENODEDRBDVERSION", "ENODEDRBDVERSION")
, ("CvENODEDRBDHELPER", "ENODEDRBDHELPER")
, ("CvENODEFILECHECK", "ENODEFILECHECK")
, ("CvENODEHOOKS", "ENODEHOOKS")
, ("CvENODEHV", "ENODEHV")
, ("CvENODELVM", "ENODELVM")
, ("CvENODEN1", "ENODEN1")
, ("CvENODENET", "ENODENET")
, ("CvENODEOS", "ENODEOS")
, ("CvENODEORPHANINSTANCE", "ENODEORPHANINSTANCE")
, ("CvENODEORPHANLV", "ENODEORPHANLV")
, ("CvENODERPC", "ENODERPC")
, ("CvENODESSH", "ENODESSH")
, ("CvENODEVERSION", "ENODEVERSION")
, ("CvENODESETUP", "ENODESETUP")
, ("CvENODETIME", "ENODETIME")
, ("CvENODEOOBPATH", "ENODEOOBPATH")
, ("CvENODEUSERSCRIPTS", "ENODEUSERSCRIPTS")
, ("CvENODEFILESTORAGEPATHS", "ENODEFILESTORAGEPATHS")
, ("CvENODEFILESTORAGEPATHUNUSABLE", "ENODEFILESTORAGEPATHUNUSABLE")
, ("CvENODESHAREDFILESTORAGEPATHUNUSABLE",
"ENODESHAREDFILESTORAGEPATHUNUSABLE")
, ("CvENODEGLUSTERSTORAGEPATHUNUSABLE",
"ENODEGLUSTERSTORAGEPATHUNUSABLE")
, ("CvEGROUPDIFFERENTPVSIZE", "EGROUPDIFFERENTPVSIZE")
, ("CvEEXTAGS", "EEXTAGS")
])
$(THH.makeJSONInstance ''CVErrorCode)
-- | Dynamic device modification, just add/remove version.
$(THH.declareLADT ''String "DdmSimple"
[ ("DdmSimpleAdd", "add")
, ("DdmSimpleAttach", "attach")
, ("DdmSimpleRemove", "remove")
, ("DdmSimpleDetach", "detach")
])
$(THH.makeJSONInstance ''DdmSimple)
-- | Dynamic device modification, all operations version.
--
-- TODO: DDM_SWAP, DDM_MOVE?
$(THH.declareLADT ''String "DdmFull"
[ ("DdmFullAdd", "add")
, ("DdmFullAttach", "attach")
, ("DdmFullRemove", "remove")
, ("DdmFullDetach", "detach")
, ("DdmFullModify", "modify")
])
$(THH.makeJSONInstance ''DdmFull)
-- | Hypervisor type definitions.
$(THH.declareLADT ''String "Hypervisor"
[ ("Kvm", "kvm")
, ("XenPvm", "xen-pvm")
, ("Chroot", "chroot")
, ("XenHvm", "xen-hvm")
, ("Lxc", "lxc")
, ("Fake", "fake")
])
$(THH.makeJSONInstance ''Hypervisor)
instance THH.PyValue Hypervisor where
showValue = show . hypervisorToRaw
instance HasStringRepr Hypervisor where
fromStringRepr = hypervisorFromRaw
toStringRepr = hypervisorToRaw
-- | Oob command type.
$(THH.declareLADT ''String "OobCommand"
[ ("OobHealth", "health")
, ("OobPowerCycle", "power-cycle")
, ("OobPowerOff", "power-off")
, ("OobPowerOn", "power-on")
, ("OobPowerStatus", "power-status")
])
$(THH.makeJSONInstance ''OobCommand)
-- | Oob command status
$(THH.declareLADT ''String "OobStatus"
[ ("OobStatusCritical", "CRITICAL")
, ("OobStatusOk", "OK")
, ("OobStatusUnknown", "UNKNOWN")
, ("OobStatusWarning", "WARNING")
])
$(THH.makeJSONInstance ''OobStatus)
-- | Storage type.
$(THH.declareLADT ''String "StorageType"
[ ("StorageFile", "file")
, ("StorageSharedFile", "sharedfile")
, ("StorageGluster", "gluster")
, ("StorageLvmPv", "lvm-pv")
, ("StorageLvmVg", "lvm-vg")
, ("StorageDiskless", "diskless")
, ("StorageBlock", "blockdev")
, ("StorageRados", "rados")
, ("StorageExt", "ext")
])
$(THH.makeJSONInstance ''StorageType)
-- | Storage keys are identifiers for storage units. Their content varies
-- depending on the storage type, for example a storage key for LVM storage
-- is the volume group name.
type StorageKey = String
-- | Storage parameters
type SPExclusiveStorage = Bool
-- | Storage units without storage-type-specific parameters
data StorageUnitRaw = SURaw StorageType StorageKey
-- | Full storage unit with storage-type-specific parameters
data StorageUnit = SUFile StorageKey
| SUSharedFile StorageKey
| SUGluster StorageKey
| SULvmPv StorageKey SPExclusiveStorage
| SULvmVg StorageKey SPExclusiveStorage
| SUDiskless StorageKey
| SUBlock StorageKey
| SURados StorageKey
| SUExt StorageKey
deriving (Eq)
instance Show StorageUnit where
show (SUFile key) = showSUSimple StorageFile key
show (SUSharedFile key) = showSUSimple StorageSharedFile key
show (SUGluster key) = showSUSimple StorageGluster key
show (SULvmPv key es) = showSULvm StorageLvmPv key es
show (SULvmVg key es) = showSULvm StorageLvmVg key es
show (SUDiskless key) = showSUSimple StorageDiskless key
show (SUBlock key) = showSUSimple StorageBlock key
show (SURados key) = showSUSimple StorageRados key
show (SUExt key) = showSUSimple StorageExt key
instance JSON StorageUnit where
showJSON (SUFile key) = showJSON (StorageFile, key, []::[String])
showJSON (SUSharedFile key) = showJSON (StorageSharedFile, key, []::[String])
showJSON (SUGluster key) = showJSON (StorageGluster, key, []::[String])
showJSON (SULvmPv key es) = showJSON (StorageLvmPv, key, [es])
showJSON (SULvmVg key es) = showJSON (StorageLvmVg, key, [es])
showJSON (SUDiskless key) = showJSON (StorageDiskless, key, []::[String])
showJSON (SUBlock key) = showJSON (StorageBlock, key, []::[String])
showJSON (SURados key) = showJSON (StorageRados, key, []::[String])
showJSON (SUExt key) = showJSON (StorageExt, key, []::[String])
-- FIXME: add readJSON implementation
readJSON = fail "Not implemented"
-- | Composes a string representation of storage types without
-- storage parameters
showSUSimple :: StorageType -> StorageKey -> String
showSUSimple st sk = show (storageTypeToRaw st, sk, []::[String])
-- | Composes a string representation of the LVM storage types
showSULvm :: StorageType -> StorageKey -> SPExclusiveStorage -> String
showSULvm st sk es = show (storageTypeToRaw st, sk, [es])
-- | Mapping from disk templates to storage types.
diskTemplateToStorageType :: DiskTemplate -> StorageType
diskTemplateToStorageType DTExt = StorageExt
diskTemplateToStorageType DTFile = StorageFile
diskTemplateToStorageType DTSharedFile = StorageSharedFile
diskTemplateToStorageType DTDrbd8 = StorageLvmVg
diskTemplateToStorageType DTPlain = StorageLvmVg
diskTemplateToStorageType DTRbd = StorageRados
diskTemplateToStorageType DTDiskless = StorageDiskless
diskTemplateToStorageType DTBlock = StorageBlock
diskTemplateToStorageType DTGluster = StorageGluster
-- | Equips a raw storage unit with its parameters
addParamsToStorageUnit :: SPExclusiveStorage -> StorageUnitRaw -> StorageUnit
addParamsToStorageUnit _ (SURaw StorageBlock key) = SUBlock key
addParamsToStorageUnit _ (SURaw StorageDiskless key) = SUDiskless key
addParamsToStorageUnit _ (SURaw StorageExt key) = SUExt key
addParamsToStorageUnit _ (SURaw StorageFile key) = SUFile key
addParamsToStorageUnit _ (SURaw StorageSharedFile key) = SUSharedFile key
addParamsToStorageUnit _ (SURaw StorageGluster key) = SUGluster key
addParamsToStorageUnit es (SURaw StorageLvmPv key) = SULvmPv key es
addParamsToStorageUnit es (SURaw StorageLvmVg key) = SULvmVg key es
addParamsToStorageUnit _ (SURaw StorageRados key) = SURados key
-- | Node evac modes.
--
-- This is part of the 'IAllocator' interface and it is used, for
-- example, in 'Ganeti.HTools.Loader.RqType'. However, it must reside
-- in this module, and not in 'Ganeti.HTools.Types', because it is
-- also used by 'Ganeti.Constants'.
$(THH.declareLADT ''String "EvacMode"
[ ("ChangePrimary", "primary-only")
, ("ChangeSecondary", "secondary-only")
, ("ChangeAll", "all")
])
$(THH.makeJSONInstance ''EvacMode)
-- | The file driver type.
$(THH.declareLADT ''String "FileDriver"
[ ("FileLoop", "loop")
, ("FileBlktap", "blktap")
, ("FileBlktap2", "blktap2")
])
$(THH.makeJSONInstance ''FileDriver)
-- | The instance create mode.
$(THH.declareLADT ''String "InstCreateMode"
[ ("InstCreate", "create")
, ("InstImport", "import")
, ("InstRemoteImport", "remote-import")
])
$(THH.makeJSONInstance ''InstCreateMode)
-- | Reboot type.
$(THH.declareLADT ''String "RebootType"
[ ("RebootSoft", "soft")
, ("RebootHard", "hard")
, ("RebootFull", "full")
])
$(THH.makeJSONInstance ''RebootType)
-- | Export modes.
$(THH.declareLADT ''String "ExportMode"
[ ("ExportModeLocal", "local")
, ("ExportModeRemote", "remote")
])
$(THH.makeJSONInstance ''ExportMode)
-- | IAllocator run types (OpTestIAllocator).
$(THH.declareLADT ''String "IAllocatorTestDir"
[ ("IAllocatorDirIn", "in")
, ("IAllocatorDirOut", "out")
])
$(THH.makeJSONInstance ''IAllocatorTestDir)
-- | IAllocator mode. FIXME: use this in "HTools.Backend.IAlloc".
$(THH.declareLADT ''String "IAllocatorMode"
[ ("IAllocatorAlloc", "allocate")
, ("IAllocatorAllocateSecondary", "allocate-secondary")
, ("IAllocatorMultiAlloc", "multi-allocate")
, ("IAllocatorReloc", "relocate")
, ("IAllocatorNodeEvac", "node-evacuate")
, ("IAllocatorChangeGroup", "change-group")
])
$(THH.makeJSONInstance ''IAllocatorMode)
-- | Network mode.
$(THH.declareLADT ''String "NICMode"
[ ("NMBridged", "bridged")
, ("NMRouted", "routed")
, ("NMOvs", "openvswitch")
, ("NMPool", "pool")
])
$(THH.makeJSONInstance ''NICMode)
-- | The JobStatus data type. Note that this is ordered especially
-- such that greater\/lesser comparison on values of this type makes
-- sense.
$(THH.declareLADT ''String "JobStatus"
[ ("JOB_STATUS_QUEUED", "queued")
, ("JOB_STATUS_WAITING", "waiting")
, ("JOB_STATUS_CANCELING", "canceling")
, ("JOB_STATUS_RUNNING", "running")
, ("JOB_STATUS_CANCELED", "canceled")
, ("JOB_STATUS_SUCCESS", "success")
, ("JOB_STATUS_ERROR", "error")
])
$(THH.makeJSONInstance ''JobStatus)
-- | Finalized job status.
$(THH.declareLADT ''String "FinalizedJobStatus"
[ ("JobStatusCanceled", "canceled")
, ("JobStatusSuccessful", "success")
, ("JobStatusFailed", "error")
])
$(THH.makeJSONInstance ''FinalizedJobStatus)
-- | The Ganeti job type.
newtype JobId = JobId { fromJobId :: Int }
deriving (Show, Eq, Ord)
-- | Builds a job ID.
makeJobId :: (Monad m) => Int -> m JobId
makeJobId i | i >= 0 = return $ JobId i
| otherwise = fail $ "Invalid value for job ID ' " ++ show i ++ "'"
-- | Builds a job ID from a string.
makeJobIdS :: (Monad m) => String -> m JobId
makeJobIdS s = tryRead "parsing job id" s >>= makeJobId
-- | Parses a job ID.
parseJobId :: (Monad m) => JSON.JSValue -> m JobId
parseJobId (JSON.JSString x) = makeJobIdS $ JSON.fromJSString x
parseJobId (JSON.JSRational _ x) =
if denominator x /= 1
then fail $ "Got fractional job ID from master daemon?! Value:" ++ show x
-- FIXME: potential integer overflow here on 32-bit platforms
else makeJobId . fromIntegral . numerator $ x
parseJobId x = fail $ "Wrong type/value for job id: " ++ show x
instance JSON.JSON JobId where
showJSON = JSON.showJSON . fromJobId
readJSON = parseJobId
-- | Relative job ID type alias.
type RelativeJobId = Negative Int
-- | Job ID dependency.
data JobIdDep = JobDepRelative RelativeJobId
| JobDepAbsolute JobId
deriving (Show, Eq, Ord)
instance JSON.JSON JobIdDep where
showJSON (JobDepRelative i) = showJSON i
showJSON (JobDepAbsolute i) = showJSON i
readJSON v =
case JSON.readJSON v::JSON.Result (Negative Int) of
-- first try relative dependency, usually most common
JSON.Ok r -> return $ JobDepRelative r
JSON.Error _ -> liftM JobDepAbsolute (parseJobId v)
-- | From job ID dependency and job ID, compute the absolute dependency.
absoluteJobIdDep :: (Monad m) => JobIdDep -> JobId -> m JobIdDep
absoluteJobIdDep (JobDepAbsolute jid) _ = return $ JobDepAbsolute jid
absoluteJobIdDep (JobDepRelative rjid) jid =
liftM JobDepAbsolute . makeJobId $ fromJobId jid + fromNegative rjid
-- | Job Dependency type.
data JobDependency = JobDependency JobIdDep [FinalizedJobStatus]
deriving (Show, Eq, Ord)
instance JSON JobDependency where
showJSON (JobDependency dep status) = showJSON (dep, status)
readJSON = liftM (uncurry JobDependency) . readJSON
-- | From job dependency and job id compute an absolute job dependency.
absoluteJobDependency :: (Monad m) => JobDependency -> JobId -> m JobDependency
absoluteJobDependency (JobDependency jdep fstats) jid =
liftM (flip JobDependency fstats) $ absoluteJobIdDep jdep jid
-- | From a job dependency get the absolute job id it depends on,
-- if given absolutely.
getJobIdFromDependency :: JobDependency -> [JobId]
getJobIdFromDependency (JobDependency (JobDepAbsolute jid) _) = [jid]
getJobIdFromDependency _ = []
-- | Valid opcode priorities for submit.
$(THH.declareIADT "OpSubmitPriority"
[ ("OpPrioLow", 'ConstantUtils.priorityLow)
, ("OpPrioNormal", 'ConstantUtils.priorityNormal)
, ("OpPrioHigh", 'ConstantUtils.priorityHigh)
])
$(THH.makeJSONInstance ''OpSubmitPriority)
-- | Parse submit priorities from a string.
parseSubmitPriority :: (Monad m) => String -> m OpSubmitPriority
parseSubmitPriority "low" = return OpPrioLow
parseSubmitPriority "normal" = return OpPrioNormal
parseSubmitPriority "high" = return OpPrioHigh
parseSubmitPriority str = fail $ "Unknown priority '" ++ str ++ "'"
-- | Format a submit priority as string.
fmtSubmitPriority :: OpSubmitPriority -> String
fmtSubmitPriority OpPrioLow = "low"
fmtSubmitPriority OpPrioNormal = "normal"
fmtSubmitPriority OpPrioHigh = "high"
-- | Our ADT for the OpCode status at runtime (while in a job).
$(THH.declareLADT ''String "OpStatus"
[ ("OP_STATUS_QUEUED", "queued")
, ("OP_STATUS_WAITING", "waiting")
, ("OP_STATUS_CANCELING", "canceling")
, ("OP_STATUS_RUNNING", "running")
, ("OP_STATUS_CANCELED", "canceled")
, ("OP_STATUS_SUCCESS", "success")
, ("OP_STATUS_ERROR", "error")
])
$(THH.makeJSONInstance ''OpStatus)
-- | Type for the job message type.
$(THH.declareLADT ''String "ELogType"
[ ("ELogMessage", "message")
, ("ELogMessageList", "message-list")
, ("ELogRemoteImport", "remote-import")
, ("ELogJqueueTest", "jqueue-test")
, ("ELogDelayTest", "delay-test")
])
$(THH.makeJSONInstance ''ELogType)
-- | Type of one element of a reason trail, of form
-- @(source, reason, timestamp)@.
type ReasonElem = (String, String, Integer)
-- | Type representing a reason trail.
type ReasonTrail = [ReasonElem]
-- | The VTYPES, a mini-type system in Python.
$(THH.declareLADT ''String "VType"
[ ("VTypeString", "string")
, ("VTypeMaybeString", "maybe-string")
, ("VTypeBool", "bool")
, ("VTypeSize", "size")
, ("VTypeInt", "int")
, ("VTypeFloat", "float")
])
$(THH.makeJSONInstance ''VType)
instance THH.PyValue VType where
showValue = THH.showValue . vTypeToRaw
-- * Node role type
$(THH.declareLADT ''String "NodeRole"
[ ("NROffline", "O")
, ("NRDrained", "D")
, ("NRRegular", "R")
, ("NRCandidate", "C")
, ("NRMaster", "M")
])
$(THH.makeJSONInstance ''NodeRole)
-- | The description of the node role.
roleDescription :: NodeRole -> String
roleDescription NROffline = "offline"
roleDescription NRDrained = "drained"
roleDescription NRRegular = "regular"
roleDescription NRCandidate = "master candidate"
roleDescription NRMaster = "master"
-- * Disk types
$(THH.declareLADT ''String "DiskMode"
[ ("DiskRdOnly", "ro")
, ("DiskRdWr", "rw")
])
$(THH.makeJSONInstance ''DiskMode)
-- | The persistent block driver type. Currently only one type is allowed.
$(THH.declareLADT ''String "BlockDriver"
[ ("BlockDrvManual", "manual")
])
$(THH.makeJSONInstance ''BlockDriver)
-- * Instance types
$(THH.declareLADT ''String "AdminState"
[ ("AdminOffline", "offline")
, ("AdminDown", "down")
, ("AdminUp", "up")
])
$(THH.makeJSONInstance ''AdminState)
$(THH.declareLADT ''String "AdminStateSource"
[ ("AdminSource", "admin")
, ("UserSource", "user")
])
$(THH.makeJSONInstance ''AdminStateSource)
instance THH.PyValue AdminStateSource where
showValue = THH.showValue . adminStateSourceToRaw
-- * Storage field type
$(THH.declareLADT ''String "StorageField"
[ ( "SFUsed", "used")
, ( "SFName", "name")
, ( "SFAllocatable", "allocatable")
, ( "SFFree", "free")
, ( "SFSize", "size")
])
$(THH.makeJSONInstance ''StorageField)
-- * Disk access protocol
$(THH.declareLADT ''String "DiskAccessMode"
[ ( "DiskUserspace", "userspace")
, ( "DiskKernelspace", "kernelspace")
])
$(THH.makeJSONInstance ''DiskAccessMode)
-- | Local disk status
--
-- Python code depends on:
-- DiskStatusOk < DiskStatusUnknown < DiskStatusFaulty
$(THH.declareILADT "LocalDiskStatus"
[ ("DiskStatusOk", 1)
, ("DiskStatusSync", 2)
, ("DiskStatusUnknown", 3)
, ("DiskStatusFaulty", 4)
])
localDiskStatusName :: LocalDiskStatus -> String
localDiskStatusName DiskStatusFaulty = "faulty"
localDiskStatusName DiskStatusOk = "ok"
localDiskStatusName DiskStatusSync = "syncing"
localDiskStatusName DiskStatusUnknown = "unknown"
-- | Replace disks type.
$(THH.declareLADT ''String "ReplaceDisksMode"
[ -- Replace disks on primary
("ReplaceOnPrimary", "replace_on_primary")
-- Replace disks on secondary
, ("ReplaceOnSecondary", "replace_on_secondary")
-- Change secondary node
, ("ReplaceNewSecondary", "replace_new_secondary")
, ("ReplaceAuto", "replace_auto")
])
$(THH.makeJSONInstance ''ReplaceDisksMode)
-- | Basic timeouts for RPC calls.
$(THH.declareILADT "RpcTimeout"
[ ("Urgent", 60) -- 1 minute
, ("Fast", 5 * 60) -- 5 minutes
, ("Normal", 15 * 60) -- 15 minutes
, ("Slow", 3600) -- 1 hour
, ("FourHours", 4 * 3600) -- 4 hours
, ("OneDay", 86400) -- 1 day
])
-- | Hotplug action.
$(THH.declareLADT ''String "HotplugAction"
[ ("HAAdd", "hotadd")
, ("HARemove", "hotremove")
, ("HAMod", "hotmod")
])
$(THH.makeJSONInstance ''HotplugAction)
-- | Hotplug Device Target.
$(THH.declareLADT ''String "HotplugTarget"
[ ("HTDisk", "disk")
, ("HTNic", "nic")
])
$(THH.makeJSONInstance ''HotplugTarget)
-- | SSH key type.
$(THH.declareLADT ''String "SshKeyType"
[ ("RSA", "rsa")
, ("DSA", "dsa")
, ("ECDSA", "ecdsa")
])
$(THH.makeJSONInstance ''SshKeyType)
-- * Private type and instances
redacted :: String
redacted = "<redacted>"
-- | A container for values that should be happy to be manipulated yet
-- refuses to be shown unless explicitly requested.
newtype Private a = Private { getPrivate :: a }
deriving (Eq, Ord, Functor)
instance (Show a, JSON.JSON a) => JSON.JSON (Private a) where
readJSON = liftM Private . JSON.readJSON
showJSON (Private x) = JSON.showJSON x
-- | "Show" the value of the field.
--
-- It would be better not to implement this at all.
-- Alas, Show OpCode requires Show Private.
instance Show a => Show (Private a) where
show _ = redacted
instance THH.PyValue a => THH.PyValue (Private a) where
showValue (Private x) = "Private(" ++ THH.showValue x ++ ")"
instance Applicative Private where
pure = Private
Private f <*> Private x = Private (f x)
instance Monad Private where
(Private x) >>= f = f x
return = Private
showPrivateJSObject :: (JSON.JSON a) =>
[(String, a)] -> JSON.JSObject (Private JSON.JSValue)
showPrivateJSObject value = JSON.toJSObject $ map f value
where f (k, v) = (k, Private $ JSON.showJSON v)
-- * Secret type and instances
-- | A container for values that behaves like Private, but doesn't leak the
-- value through showJSON
newtype Secret a = Secret { getSecret :: a }
deriving (Eq, Ord, Functor)
instance (Show a, JSON.JSON a) => JSON.JSON (Secret a) where
readJSON = liftM Secret . JSON.readJSON
showJSON = const . JSON.JSString $ JSON.toJSString redacted
instance Show a => Show (Secret a) where
show _ = redacted
instance THH.PyValue a => THH.PyValue (Secret a) where
showValue (Secret x) = "Secret(" ++ THH.showValue x ++ ")"
instance Applicative Secret where
pure = Secret
Secret f <*> Secret x = Secret (f x)
instance Monad Secret where
(Secret x) >>= f = f x
return = Secret
-- | We return "\<redacted\>" here to satisfy the idempotence of serialization
-- and deserialization, although this will impact the meaningfulness of secret
-- parameters within configuration tests.
showSecretJSObject :: (JSON.JSON a) =>
[(String, a)] -> JSON.JSObject (Secret JSON.JSValue)
showSecretJSObject value = JSON.toJSObject $ map f value
where f (k, _) = (k, Secret $ JSON.showJSON redacted)
revealValInJSObject :: JSON.JSObject (Secret JSON.JSValue)
-> JSON.JSObject (Private JSON.JSValue)
revealValInJSObject object = JSON.toJSObject . map f $ JSON.fromJSObject object
where f (k, v) = (k, Private $ getSecret v)
-- | The hypervisor parameter type. This is currently a simple map,
-- without type checking on key/value pairs.
type HvParams = Container JSON.JSValue
-- | The OS parameters type. This is, and will remain, a string
-- container, since the keys are dynamically declared by the OSes, and
-- the values are always strings.
type OsParams = Container String
type OsParamsPrivate = Container (Private String)
-- | Class of objects that have timestamps.
class TimeStampObject a where
cTimeOf :: a -> ClockTime
mTimeOf :: a -> ClockTime
-- | Class of objects that have an UUID.
class UuidObject a where
uuidOf :: a -> String
-- | Class of objects that can be forthcoming.
class ForthcomingObject a where
isForthcoming :: a -> Bool
-- | Class of object that have a serial number.
class SerialNoObject a where
serialOf :: a -> Int
-- | Class of objects that have tags.
class TagsObject a where
tagsOf :: a -> TagSet
|
mbakke/ganeti
|
src/Ganeti/Types.hs
|
bsd-2-clause
| 35,183
| 0
| 11
| 6,917
| 8,169
| 4,589
| 3,580
| 717
| 2
|
{-|
Copyright : (C) 2012-2016, University of Twente
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <christiaan.baaij@gmail.com>
Term representation in the CoreHW language: System F + LetRec + Case
-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-specialise #-}
module CLaSH.Core.Term
( Term (..)
, TmName
, LetBinding
, Pat (..)
)
where
-- External Modules
import Control.DeepSeq
import Data.Text (Text)
import GHC.Generics
import Unbound.Generics.LocallyNameless
import Unbound.Generics.LocallyNameless.Extra ()
-- Internal Modules
import CLaSH.Core.DataCon (DataCon)
import CLaSH.Core.Literal (Literal)
import {-# SOURCE #-} CLaSH.Core.Type (Type)
import CLaSH.Core.Var (Id, TyVar)
-- | Term representation in the CoreHW language: System F + LetRec + Case
data Term
= Var !Type !TmName -- ^ Variable reference
| Data !DataCon -- ^ Datatype constructor
| Literal !Literal -- ^ Literal
| Prim !Text !Type -- ^ Primitive
| Lam !(Bind Id Term) -- ^ Term-abstraction
| TyLam !(Bind TyVar Term) -- ^ Type-abstraction
| App !Term !Term -- ^ Application
| TyApp !Term !Type -- ^ Type-application
| Letrec !(Bind (Rec [LetBinding]) Term) -- ^ Recursive let-binding
| Case !Term !Type [Bind Pat Term] -- ^ Case-expression: subject, type of
-- alternatives, list of alternatives
deriving (Show,Generic,NFData)
-- | Term reference
type TmName = Name Term
-- | Binding in a LetRec construct
type LetBinding = (Id, Embed Term)
-- | Patterns in the LHS of a case-decomposition
data Pat
= DataPat !(Embed DataCon) !(Rebind [TyVar] [Id])
-- ^ Datatype pattern, '[TyVar]' bind existentially-quantified
-- type-variables of a DataCon
| LitPat !(Embed Literal)
-- ^ Literal pattern
| DefaultPat
-- ^ Default pattern
deriving (Eq,Show,Generic,NFData,Alpha)
instance Eq Term where
(==) = aeq
instance Ord Term where
compare = acompare
instance Alpha Term where
fvAny' c nfn (Var t n) = fmap (Var t) $ fvAny' c nfn n
fvAny' c nfn t = fmap to . gfvAny c nfn $ from t
aeq' c (Var _ n) (Var _ m) = aeq' c n m
aeq' _ (Prim t1 _) (Prim t2 _) = t1 == t2
aeq' c t1 t2 = gaeq c (from t1) (from t2)
acompare' c (Var _ n) (Var _ m) = acompare' c n m
acompare' _ (Prim t1 _) (Prim t2 _) = compare t1 t2
acompare' c t1 t2 = gacompare c (from t1) (from t2)
instance Subst Type Pat
instance Subst Term Pat
instance Subst Term Term where
isvar (Var _ x) = Just (SubstName x)
isvar _ = Nothing
instance Subst Type Term
|
ggreif/clash-compiler
|
clash-lib/src/CLaSH/Core/Term.hs
|
bsd-2-clause
| 3,081
| 0
| 12
| 958
| 747
| 402
| 345
| 94
| 0
|
import Prelude hiding (tail)
-- | A non-empty LIFO queue with O(log n) indexing.
--
-- Amortized operation for 'cons' is O(1), but in combination with 'tail' it
-- can be O(log n).
--
-- To achieve O(1) it's necessary to add redundancy so that for each nested
-- operation we have one non-nested.
data LogLIFO a = Value a | Zero (LogLIFO (a, a)) | One a (LogLIFO (a, a))
deriving (Read, Show, Eq, Ord)
singleton :: a -> LogLIFO a
singleton = Value
tail :: LogLIFO a -> (a, Maybe (LogLIFO a))
tail (Value x) = (x, Nothing)
tail (One x xs) = (x, Just $ Zero xs)
tail (Zero xs) = case tail xs of
((x, y), Nothing) -> (x, Just $ singleton y)
((x, y), Just ys) -> (x, Just $ One y ys)
cons :: a -> LogLIFO a -> LogLIFO a
cons x (Zero ys) = One x ys
cons x (One y ys) = Zero (cons (x, y) ys)
cons x (Value y) = Zero (Value (x, y))
(!) :: LogLIFO a -> Int -> Maybe a
Value x ! 0 = Just x
Value _ ! _ = Nothing
One x _ ! 0 = Just x
One _ xs ! n = recIndex xs (n - 1)
Zero xs ! n = recIndex xs n
recIndex :: LogLIFO (a, a) -> Int -> Maybe a
recIndex xs n = case xs ! (n `div` 2) of
Just (x, y) | even n -> Just x
| odd n -> Just y
_ -> Nothing
|
ppetr/functional-data-structures
|
LogLIFO.hs
|
bsd-2-clause
| 1,288
| 0
| 11
| 416
| 587
| 302
| 285
| 26
| 2
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTextBlockGroup.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:14
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QTextBlockGroup (
qTextBlockGroup_delete
,qTextBlockGroup_deleteLater
,qTextBlockGroup
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QTextBlockGroup ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QTextBlockGroup_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QTextBlockGroup_userMethod" qtc_QTextBlockGroup_userMethod :: Ptr (TQTextBlockGroup a) -> CInt -> IO ()
instance QuserMethod (QTextBlockGroupSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QTextBlockGroup_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QTextBlockGroup ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QTextBlockGroup_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QTextBlockGroup_userMethodVariant" qtc_QTextBlockGroup_userMethodVariant :: Ptr (TQTextBlockGroup a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QTextBlockGroupSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QTextBlockGroup_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
qTextBlockGroup_delete :: QTextBlockGroup a -> IO ()
qTextBlockGroup_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextBlockGroup_delete cobj_x0
foreign import ccall "qtc_QTextBlockGroup_delete" qtc_QTextBlockGroup_delete :: Ptr (TQTextBlockGroup a) -> IO ()
qTextBlockGroup_deleteLater :: QTextBlockGroup a -> IO ()
qTextBlockGroup_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextBlockGroup_deleteLater cobj_x0
foreign import ccall "qtc_QTextBlockGroup_deleteLater" qtc_QTextBlockGroup_deleteLater :: Ptr (TQTextBlockGroup a) -> IO ()
qTextBlockGroup :: (QTextDocument t1) -> IO (QTextBlockGroup ())
qTextBlockGroup (x1)
= withQTextBlockGroupResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup cobj_x1
foreign import ccall "qtc_QTextBlockGroup" qtc_QTextBlockGroup :: Ptr (TQTextDocument t1) -> IO (Ptr (TQTextBlockGroup ()))
instance QblockFormatChanged (QTextBlockGroup ()) ((QTextBlock t1)) where
blockFormatChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_blockFormatChanged_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTextBlockGroup_blockFormatChanged_h" qtc_QTextBlockGroup_blockFormatChanged_h :: Ptr (TQTextBlockGroup a) -> Ptr (TQTextBlock t1) -> IO ()
instance QblockFormatChanged (QTextBlockGroupSc a) ((QTextBlock t1)) where
blockFormatChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_blockFormatChanged_h cobj_x0 cobj_x1
instance QblockInserted (QTextBlockGroup ()) ((QTextBlock t1)) where
blockInserted x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_blockInserted_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTextBlockGroup_blockInserted_h" qtc_QTextBlockGroup_blockInserted_h :: Ptr (TQTextBlockGroup a) -> Ptr (TQTextBlock t1) -> IO ()
instance QblockInserted (QTextBlockGroupSc a) ((QTextBlock t1)) where
blockInserted x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_blockInserted_h cobj_x0 cobj_x1
instance QblockList (QTextBlockGroup ()) (()) where
blockList x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextBlockGroup_blockList cobj_x0 arr
foreign import ccall "qtc_QTextBlockGroup_blockList" qtc_QTextBlockGroup_blockList :: Ptr (TQTextBlockGroup a) -> Ptr (Ptr (TQTextBlock ())) -> IO CInt
instance QblockList (QTextBlockGroupSc a) (()) where
blockList x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextBlockGroup_blockList cobj_x0 arr
instance QblockRemoved (QTextBlockGroup ()) ((QTextBlock t1)) where
blockRemoved x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_blockRemoved_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTextBlockGroup_blockRemoved_h" qtc_QTextBlockGroup_blockRemoved_h :: Ptr (TQTextBlockGroup a) -> Ptr (TQTextBlock t1) -> IO ()
instance QblockRemoved (QTextBlockGroupSc a) ((QTextBlock t1)) where
blockRemoved x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_blockRemoved_h cobj_x0 cobj_x1
instance QsetFormat (QTextBlockGroup ()) ((QTextFormat t1)) where
setFormat x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_setFormat cobj_x0 cobj_x1
foreign import ccall "qtc_QTextBlockGroup_setFormat" qtc_QTextBlockGroup_setFormat :: Ptr (TQTextBlockGroup a) -> Ptr (TQTextFormat t1) -> IO ()
instance QsetFormat (QTextBlockGroupSc a) ((QTextFormat t1)) where
setFormat x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_setFormat cobj_x0 cobj_x1
instance QchildEvent (QTextBlockGroup ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextBlockGroup_childEvent" qtc_QTextBlockGroup_childEvent :: Ptr (TQTextBlockGroup a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QTextBlockGroupSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QTextBlockGroup ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTextBlockGroup_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QTextBlockGroup_connectNotify" qtc_QTextBlockGroup_connectNotify :: Ptr (TQTextBlockGroup a) -> CWString -> IO ()
instance QconnectNotify (QTextBlockGroupSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTextBlockGroup_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QTextBlockGroup ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextBlockGroup_customEvent" qtc_QTextBlockGroup_customEvent :: Ptr (TQTextBlockGroup a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QTextBlockGroupSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QTextBlockGroup ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTextBlockGroup_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QTextBlockGroup_disconnectNotify" qtc_QTextBlockGroup_disconnectNotify :: Ptr (TQTextBlockGroup a) -> CWString -> IO ()
instance QdisconnectNotify (QTextBlockGroupSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTextBlockGroup_disconnectNotify cobj_x0 cstr_x1
instance Qevent (QTextBlockGroup ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTextBlockGroup_event_h" qtc_QTextBlockGroup_event_h :: Ptr (TQTextBlockGroup a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QTextBlockGroupSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_event_h cobj_x0 cobj_x1
instance QeventFilter (QTextBlockGroup ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTextBlockGroup_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTextBlockGroup_eventFilter_h" qtc_QTextBlockGroup_eventFilter_h :: Ptr (TQTextBlockGroup a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QTextBlockGroupSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTextBlockGroup_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QTextBlockGroup ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTextBlockGroup_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QTextBlockGroup_receivers" qtc_QTextBlockGroup_receivers :: Ptr (TQTextBlockGroup a) -> CWString -> IO CInt
instance Qreceivers (QTextBlockGroupSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTextBlockGroup_receivers cobj_x0 cstr_x1
instance Qsender (QTextBlockGroup ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextBlockGroup_sender cobj_x0
foreign import ccall "qtc_QTextBlockGroup_sender" qtc_QTextBlockGroup_sender :: Ptr (TQTextBlockGroup a) -> IO (Ptr (TQObject ()))
instance Qsender (QTextBlockGroupSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextBlockGroup_sender cobj_x0
instance QtimerEvent (QTextBlockGroup ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextBlockGroup_timerEvent" qtc_QTextBlockGroup_timerEvent :: Ptr (TQTextBlockGroup a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QTextBlockGroupSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextBlockGroup_timerEvent cobj_x0 cobj_x1
|
uduki/hsQt
|
Qtc/Gui/QTextBlockGroup.hs
|
bsd-2-clause
| 11,000
| 0
| 14
| 1,710
| 3,232
| 1,638
| 1,594
| -1
| -1
|
{-| Provides utilities to parse Dhall comments
-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
module Dhall.Docs.Comment
( parseComments
, CommentParseError(..)
, DhallDocsText
, parseSingleDhallDocsComment
, unDhallDocsText
) where
import Control.Applicative (many, some, (<|>))
import Data.Functor (void)
import Data.List.NonEmpty (NonEmpty (..), (<|))
import Data.Text (Text)
import Dhall.Docs.Util
import Dhall.Parser (Parser (..))
import Text.Megaparsec (SourcePos, (<?>))
import qualified Data.Either
import qualified Data.Foldable
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Maybe as Maybe
import qualified Data.Text
import qualified Dhall.Parser.Token as Token
import qualified Text.Megaparsec
import qualified Text.Megaparsec.Pos as Megaparsec.Pos
-- | For explanation of this data-type see 'DhallComment'
data CommentType = DhallDocsComment | MarkedComment | RawComment
type ListOfSingleLineComments = NonEmpty (SourcePos, Text)
{-| Internal representation of Dhall comments. Text is always stripped from
whitespace from both the start and begin of the string
* If @a = 'DhallDocsComment'@ then comment is valid to extract its contents
and be rendered on documentation
* If @a = 'MarkedComment'@ then comment has the @|@ marker that
@dhall-docs@ will be aware of, but this comment may not be a @dhall-docs@
comment
* If @a = `RawComment`@ then the comment is a raw comment
-}
data DhallComment (a :: CommentType)
-- | A single block comment: starting from @{-@ and ending in @-}@
= BlockComment Text
{-| A group of subsequent single line comment, each one starting from @--@
and ending in the last character to the end of the line. Each one keeps
its 'SourcePos' to validate indentation.
A property of 'SingleLineComments' is that the 'sourceLine's in the
'NonEmpty (SourcePos, Text)' are in strictly-increasing order /and/
the difference between the 'sourceLine' of any adyacent pair is @1@.
Note that several @dhall-docs@ comments maybe inside a single 'SingleLineComments'
-}
| SingleLineComments ListOfSingleLineComments
deriving Show
-- | Extracted text from a valid @dhall-docs@ comment
newtype DhallDocsText = DhallDocsText Text
deriving Show
unDhallDocsText :: DhallDocsText -> Text
unDhallDocsText (DhallDocsText t) = t
-- | A mirror of "Dhall.Parser.Token".'Dhall.Parser.Token.lineComment' but
-- returning a 'DhallComment'
lineCommentParser :: Parser (NonEmpty (DhallComment 'RawComment))
lineCommentParser = do
(l : ls) <- some singleLine
pure $ NonEmpty.map SingleLineComments $ groupComments (l :| ls)
where
groupComments :: ListOfSingleLineComments -> NonEmpty ListOfSingleLineComments
groupComments ls = case NonEmpty.nonEmpty remaining of
Nothing -> g :| []
Just l -> g <| groupComments l
where
lineNumber = Megaparsec.Pos.unPos . Megaparsec.Pos.sourceLine
(g, remaining) = removeSubseq ls
removeSubseq :: ListOfSingleLineComments -> (ListOfSingleLineComments, [(SourcePos, Text)])
removeSubseq (x :| []) = (x :| [], [])
removeSubseq (x@(xPos, _) :| ys@(y@(yPos, _) : rest))
| lineNumber yPos - lineNumber xPos == 1
= let (subSeq, r) = removeSubseq (y :| rest) in (x <| subSeq, r)
| otherwise = (x :| [], ys)
singleLine = do
sourcePos <- Text.Megaparsec.getSourcePos
commentLine <- Token.lineComment
whitespace
pure (sourcePos, commentLine)
-- | Consume whitespace lines or lines that only have whitespaces *before* a comment
whitespace :: Parser ()
whitespace = Text.Megaparsec.skipMany (Text.Megaparsec.choice
[ void (Text.Megaparsec.takeWhile1P Nothing predicate)
, void (Token.text "\r\n")
] <?> "whitespace")
where
predicate c = c == ' ' || c == '\t' || c == '\n'
blockCommentParser :: Parser (DhallComment 'RawComment)
blockCommentParser = do
c <- Token.blockComment
whitespace
pure $ BlockComment c
-- | Parse all comments in a text fragment
parseComments :: String -> Text -> [DhallComment 'RawComment]
parseComments delta text = case result of
Left err -> error ("An error has occurred while parsing comments:\n "
<> Text.Megaparsec.errorBundlePretty err)
Right comments -> comments
where
parser = do
comments <- many $ do
whitespace
lineCommentParser <|> ((:| []) <$> blockCommentParser)
Text.Megaparsec.eof
pure $ concatMap NonEmpty.toList comments
result = Text.Megaparsec.parse (unParser parser) delta text
data CommentParseError
= MissingNewlineOnBlockComment
| BadSingleLineCommentsAlignment
| BadPrefixesOnSingleLineComments
| SeveralSubseqDhallDocsComments
deriving Show
-- | Checks if a 'RawComment' has the @dhall-docs@ marker
parseMarkedComment :: DhallComment 'RawComment -> Maybe (DhallComment 'MarkedComment)
parseMarkedComment (BlockComment comment)
| "{-|" `Data.Text.isPrefixOf` comment = Just $ BlockComment comment
| otherwise = Nothing
parseMarkedComment (SingleLineComments ls)
| any (("--|" `Data.Text.isPrefixOf`) . snd) ls = Just (SingleLineComments ls)
| otherwise = Nothing
-- | Knowing that there is a @dhall-docs@ marker inside the comment, this
-- checks if a 'MarkedComment' is a 'DhallDocsComment'. For 'SingleLineComments'
-- this also removes the prefix lines before the first marked comment
parseDhallDocsComment :: DhallComment 'MarkedComment -> Either CommentParseError (DhallComment 'DhallDocsComment)
parseDhallDocsComment (BlockComment comment) =
if any (`Data.Text.isPrefixOf` comment) ["{-|\n", "{-|\r\n"] then Right $ BlockComment comment
else Left MissingNewlineOnBlockComment
parseDhallDocsComment (SingleLineComments lineComments) =
fmap SingleLineComments $ checkAlignment lineComments >>= checkAmountOfMarkers >>= checkPrefixes
where
sourceCol = Text.Megaparsec.unPos . Text.Megaparsec.sourceColumn
checkAmountOfMarkers :: ListOfSingleLineComments -> Either CommentParseError ListOfSingleLineComments
checkAmountOfMarkers ls =
if numberOfMarkers > 1 then Left SeveralSubseqDhallDocsComments
else case newLines of
[] -> fileAnIssue "checkAmountOfMarkers failed with newLines = []"
l : remainder -> Right $ l :| remainder
where
commentLines = NonEmpty.toList ls
numberOfMarkers = length $ filter (Data.Text.isPrefixOf "--|" . snd) commentLines
(_, newLines) = break (Data.Text.isPrefixOf "--|" . snd) commentLines
checkAlignment :: ListOfSingleLineComments -> Either CommentParseError ListOfSingleLineComments
checkAlignment ls@((first, _) :| rest)
| all ((== sourceCol first) . sourceCol . fst) rest = Right ls
| otherwise = Left BadSingleLineCommentsAlignment
checkPrefixes :: ListOfSingleLineComments -> Either CommentParseError ListOfSingleLineComments
checkPrefixes ls@((_, first) :| rest)
| "--| " `Data.Text.isPrefixOf` first && all (p . snd) rest
= Right ls
| otherwise = Left BadPrefixesOnSingleLineComments
where
p t = Data.Text.isPrefixOf "-- " t || (Data.Text.compareLength t 2 == EQ && "--" == t)
parseDhallDocsText :: DhallComment 'DhallDocsComment -> DhallDocsText
parseDhallDocsText (BlockComment blockComment) =
case Data.Text.stripSuffix "-}" joinedText of
Nothing -> fileAnIssue ("Obtained 'Nothing' on extractText.stripSuffix with text: \"" <> joinedText <> "\"")
Just e -> DhallDocsText e
where
joinedText = Data.Text.strip $ Data.Text.unlines reIndentedLines
commentLines = tail $ Data.Text.lines blockComment
leadingSpaces = Data.Text.takeWhile isSpace
where
isSpace t = t == ' ' || t == '\t'
nonEmptyCommentLines = filter (not . Data.Text.null) commentLines
commonIndentation = Data.Text.length $
case map leadingSpaces nonEmptyCommentLines of
l : ls -> Data.Foldable.foldl' sharedPrefix l ls
[] -> ""
where
sharedPrefix ab ac =
case Data.Text.commonPrefixes ab ac of
Just (a, _, _) -> a
Nothing -> ""
reIndentedLines = map (Data.Text.drop commonIndentation) commentLines
parseDhallDocsText (SingleLineComments (fmap snd -> (first :| rest))) =
DhallDocsText $ Data.Text.unlines $ firstLine : map cleanRest rest
where
debugLines = Data.Text.unlines (first : rest)
firstLine = case Data.Text.stripPrefix "--| " first of
Nothing -> fileAnIssue $
"Error strippping \"--| \" prefix on parseDhallDocsText. " <>
"All comment lines are here:\n" <> debugLines
Just s -> s
cleanRest l = case Data.Text.stripPrefix "-- " l <|> Data.Text.stripPrefix "--" l of
Nothing -> fileAnIssue $
"Error strippping \"-- \" prefix on parseDhallDocsText. " <>
"All comment lines are here:\n" <> debugLines
Just s -> s
-- | Returns 'Nothing' when 'DhallDocsComment' was parsed or no error was detected
parseSingleDhallDocsComment :: String -> Text -> Maybe (Either [CommentParseError] DhallDocsText)
parseSingleDhallDocsComment delta text = do
let rawComments = parseComments delta text
let markedComments = Maybe.mapMaybe parseMarkedComment rawComments
let (errors_, dhallDocsComments) = Data.Either.partitionEithers $ map parseDhallDocsComment markedComments
let errors =
if length dhallDocsComments >= 2 then
SeveralSubseqDhallDocsComments : errors_
else
errors_
case (errors, dhallDocsComments) of
([] , []) -> Nothing
(_:_, _) -> Just $ Left errors
(_ , [a]) -> Just $ Right $ parseDhallDocsText a
(_ , _) -> fileAnIssue "Returned more than one comment at parseSingleDhallDocsComment"
|
Gabriel439/Haskell-Dhall-Library
|
dhall-docs/src/Dhall/Docs/Comment.hs
|
bsd-3-clause
| 10,157
| 0
| 17
| 2,279
| 2,245
| 1,195
| 1,050
| 164
| 6
|
module Codec.Grib (
module Codec.Grib.Parser,
module Codec.Grib.Types
) where
import Codec.Grib.Parser
import Codec.Grib.Types
|
snakamura/zeepaardje
|
Codec/Grib.hs
|
bsd-3-clause
| 136
| 0
| 5
| 22
| 34
| 23
| 11
| 5
| 0
|
{-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
------------------------------------------------------------------------------
-- |
-- Module: Database.PostgreSQL.Simple.ToField
-- Copyright: (c) 2011 MailRank, Inc.
-- (c) 2011-2012 Leon P Smith
-- License: BSD3
-- Maintainer: Leon P Smith <leon@melding-monads.com>
-- Stability: experimental
--
-- The 'ToField' typeclass, for rendering a parameter to a SQL query.
--
------------------------------------------------------------------------------
module Database.PostgreSQL.Simple.ToField
(
Action(..)
, ToField(..)
, toJSONField
, inQuotes
) where
import Blaze.ByteString.Builder (Builder, fromByteString, toByteString)
import Blaze.ByteString.Builder.Char8 (fromChar)
import Blaze.Text (integral, double, float)
import qualified Data.Aeson as JSON
import Data.ByteString (ByteString)
import Data.Int (Int8, Int16, Int32, Int64)
import Data.List (intersperse)
import Data.Monoid (mappend)
import Data.Time (Day, TimeOfDay, LocalTime, UTCTime, ZonedTime, NominalDiffTime)
import Data.Typeable (Typeable)
import Data.Word (Word, Word8, Word16, Word32, Word64)
import {-# SOURCE #-} Database.PostgreSQL.Simple.ToRow
import Database.PostgreSQL.Simple.Types
import qualified Blaze.ByteString.Builder.Char.Utf8 as Utf8
import qualified Data.ByteString as SB
import qualified Data.ByteString.Lazy as LB
import qualified Data.Text as ST
import qualified Data.Text.Encoding as ST
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Lazy.Builder as LT
import Data.UUID (UUID)
import qualified Data.UUID as UUID
import Data.Vector (Vector)
import qualified Data.Vector as V
import qualified Database.PostgreSQL.LibPQ as PQ
import Database.PostgreSQL.Simple.Time
import Data.Scientific (Scientific)
#if MIN_VERSION_scientific(0,3,0)
import Data.Text.Lazy.Builder.Scientific (scientificBuilder)
#else
import Data.Scientific (scientificBuilder)
#endif
-- | How to render an element when substituting it into a query.
data Action =
Plain Builder
-- ^ Render without escaping or quoting. Use for non-text types
-- such as numbers, when you are /certain/ that they will not
-- introduce formatting vulnerabilities via use of characters such
-- as spaces or \"@'@\".
| Escape ByteString
-- ^ Escape and enclose in quotes before substituting. Use for all
-- text-like types, and anything else that may contain unsafe
-- characters when rendered.
| EscapeByteA ByteString
-- ^ Escape binary data for use as a @bytea@ literal. Include surrounding
-- quotes. This is used by the 'Binary' newtype wrapper.
| EscapeIdentifier ByteString
-- ^ Escape before substituting. Use for all sql identifiers like
-- table, column names, etc. This is used by the 'Identifier' newtype
-- wrapper.
| Many [Action]
-- ^ Concatenate a series of rendering actions.
deriving (Typeable)
instance Show Action where
show (Plain b) = "Plain " ++ show (toByteString b)
show (Escape b) = "Escape " ++ show b
show (EscapeByteA b) = "EscapeByteA " ++ show b
show (EscapeIdentifier b) = "EscapeIdentifier " ++ show b
show (Many b) = "Many " ++ show b
-- | A type that may be used as a single parameter to a SQL query.
class ToField a where
toField :: a -> Action
-- ^ Prepare a value for substitution into a query string.
instance ToField Action where
toField a = a
{-# INLINE toField #-}
instance (ToField a) => ToField (Maybe a) where
toField Nothing = renderNull
toField (Just a) = toField a
{-# INLINE toField #-}
instance (ToField a) => ToField (In [a]) where
toField (In []) = Plain $ fromByteString "(null)"
toField (In xs) = Many $
Plain (fromChar '(') :
(intersperse (Plain (fromChar ',')) . map toField $ xs) ++
[Plain (fromChar ')')]
renderNull :: Action
renderNull = Plain (fromByteString "null")
instance ToField Null where
toField _ = renderNull
{-# INLINE toField #-}
instance ToField Default where
toField _ = Plain (fromByteString "default")
{-# INLINE toField #-}
instance ToField Bool where
toField True = Plain (fromByteString "true")
toField False = Plain (fromByteString "false")
{-# INLINE toField #-}
instance ToField Int8 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Int16 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Int32 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Int where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Int64 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Integer where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Word8 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Word16 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Word32 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Word where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField Word64 where
toField = Plain . integral
{-# INLINE toField #-}
instance ToField PQ.Oid where
toField = Plain . integral . \(PQ.Oid x) -> x
{-# INLINE toField #-}
instance ToField Float where
toField v | isNaN v || isInfinite v = Plain (inQuotes (float v))
| otherwise = Plain (float v)
{-# INLINE toField #-}
instance ToField Double where
toField v | isNaN v || isInfinite v = Plain (inQuotes (double v))
| otherwise = Plain (double v)
{-# INLINE toField #-}
instance ToField Scientific where
toField x = toField (LT.toLazyText (scientificBuilder x))
{-# INLINE toField #-}
instance ToField (Binary SB.ByteString) where
toField (Binary bs) = EscapeByteA bs
{-# INLINE toField #-}
instance ToField (Binary LB.ByteString) where
toField (Binary bs) = (EscapeByteA . SB.concat . LB.toChunks) bs
{-# INLINE toField #-}
instance ToField Identifier where
toField (Identifier bs) = EscapeIdentifier (ST.encodeUtf8 bs)
{-# INLINE toField #-}
instance ToField QualifiedIdentifier where
toField (QualifiedIdentifier (Just s) t) =
Many [ EscapeIdentifier (ST.encodeUtf8 s)
, Plain (fromChar '.')
, EscapeIdentifier (ST.encodeUtf8 t)
]
toField (QualifiedIdentifier Nothing t) =
EscapeIdentifier (ST.encodeUtf8 t)
{-# INLINE toField #-}
instance ToField SB.ByteString where
toField = Escape
{-# INLINE toField #-}
instance ToField LB.ByteString where
toField = toField . SB.concat . LB.toChunks
{-# INLINE toField #-}
instance ToField ST.Text where
toField = Escape . ST.encodeUtf8
{-# INLINE toField #-}
instance ToField [Char] where
toField = Escape . toByteString . Utf8.fromString
{-# INLINE toField #-}
instance ToField LT.Text where
toField = toField . LT.toStrict
{-# INLINE toField #-}
instance ToField UTCTime where
toField = Plain . inQuotes . utcTimeToBuilder
{-# INLINE toField #-}
instance ToField ZonedTime where
toField = Plain . inQuotes . zonedTimeToBuilder
{-# INLINE toField #-}
instance ToField LocalTime where
toField = Plain . inQuotes . localTimeToBuilder
{-# INLINE toField #-}
instance ToField Day where
toField = Plain . inQuotes . dayToBuilder
{-# INLINE toField #-}
instance ToField TimeOfDay where
toField = Plain . inQuotes . timeOfDayToBuilder
{-# INLINE toField #-}
instance ToField UTCTimestamp where
toField = Plain . inQuotes . utcTimestampToBuilder
{-# INLINE toField #-}
instance ToField ZonedTimestamp where
toField = Plain . inQuotes . zonedTimestampToBuilder
{-# INLINE toField #-}
instance ToField LocalTimestamp where
toField = Plain . inQuotes . localTimestampToBuilder
{-# INLINE toField #-}
instance ToField Date where
toField = Plain . inQuotes . dateToBuilder
{-# INLINE toField #-}
instance ToField NominalDiffTime where
toField = Plain . inQuotes . nominalDiffTimeToBuilder
{-# INLINE toField #-}
instance (ToField a) => ToField (PGArray a) where
toField xs = Many $
Plain (fromByteString "ARRAY[") :
(intersperse (Plain (fromChar ',')) . map toField $ fromPGArray xs) ++
[Plain (fromChar ']')]
-- Because the ARRAY[...] input syntax is being used, it is possible
-- that the use of type-specific separator characters is unnecessary.
instance (ToField a) => ToField (Vector a) where
toField = toField . PGArray . V.toList
instance ToField UUID where
toField = Plain . inQuotes . fromByteString . UUID.toASCIIBytes
instance ToField JSON.Value where
toField = toField . JSON.encode
-- | Convert a Haskell value to a JSON 'JSON.Value' using
-- 'JSON.toJSON' and convert that to a field using 'toField'.
--
-- This can be used as the default implementation for the 'toField'
-- method for Haskell types that have a JSON representation in
-- PostgreSQL.
toJSONField :: JSON.ToJSON a => a -> Action
toJSONField = toField . JSON.toJSON
-- | Surround a string with single-quote characters: \"@'@\"
--
-- This function /does not/ perform any other escaping.
inQuotes :: Builder -> Builder
inQuotes b = quote `mappend` b `mappend` quote
where quote = Utf8.fromChar '\''
interleaveFoldr :: (a -> [b] -> [b]) -> b -> [b] -> [a] -> [b]
interleaveFoldr f b bs as = foldr (\a bs -> b : f a bs) bs as
{-# INLINE interleaveFoldr #-}
instance ToRow a => ToField (Values a) where
toField (Values types rows) =
case rows of
[] -> case types of
[] -> error norows
(_:_) -> values $ typedRow (repeat (lit "null"))
types
[lit " LIMIT 0)"]
(_:_) -> case types of
[] -> values $ untypedRows rows [litC ')']
(_:_) -> values $ typedRows rows types [litC ')']
where
funcname = "Database.PostgreSQL.Simple.toField :: Values a -> Action"
norows = funcname ++ " either values or types must be non-empty"
emptyrow = funcname ++ " each row must contain at least one column"
lit = Plain . fromByteString
litC = Plain . fromChar
values x = Many (lit "(VALUES ": x)
typedField :: (Action, QualifiedIdentifier) -> [Action] -> [Action]
typedField (val,typ) rest = val : lit "::" : toField typ : rest
typedRow :: [Action] -> [QualifiedIdentifier] -> [Action] -> [Action]
typedRow (val:vals) (typ:typs) rest =
litC '(' :
typedField (val,typ) ( interleaveFoldr
typedField
(litC ',')
(litC ')' : rest)
(zip vals typs) )
typedRow _ _ _ = error emptyrow
untypedRow :: [Action] -> [Action] -> [Action]
untypedRow (val:vals) rest =
litC '(' : val :
interleaveFoldr
(:)
(litC ',')
(litC ')' : rest)
vals
untypedRow _ _ = error emptyrow
typedRows :: ToRow a => [a] -> [QualifiedIdentifier] -> [Action] -> [Action]
typedRows [] _ _ = error funcname
typedRows (val:vals) types rest =
typedRow (toRow val) types (multiRows vals rest)
untypedRows :: ToRow a => [a] -> [Action] -> [Action]
untypedRows [] _ = error funcname
untypedRows (val:vals) rest =
untypedRow (toRow val) (multiRows vals rest)
multiRows :: ToRow a => [a] -> [Action] -> [Action]
multiRows vals rest = interleaveFoldr
(untypedRow . toRow)
(litC ',')
rest
vals
|
avieth/postgresql-simple
|
src/Database/PostgreSQL/Simple/ToField.hs
|
bsd-3-clause
| 12,315
| 0
| 17
| 3,287
| 2,900
| 1,579
| 1,321
| 255
| 1
|
{-# LANGUAGE Rank2Types, OverloadedStrings #-}
module Main where
import Prelude hiding (putStr, putStrLn)
import ConstraintsGA
import ConstraintsGeneric
import GenericGameExperiments
import Matlab
import GraphNN
import MinimalNN
import NeuralNets
import ThreadLocal
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.Async
import Control.Monad
import Control.DeepSeq
import Control.Parallel.Strategies
import Data.Default
import Data.IORef
import Data.Timeout
import System.FilePath
useCachedDBN = False
searchTimeout = 1 # Minute
searchTimeoutMulti = 10 # Second
dbnGameCount = 100000
dbnGameProb = 0.01
dbnMatlabOpts = Just (def {dbnSizes = [500, 500, 500], numEpochs = 5, implementation = Matlab})
constraintSource = CS_Gameplay playerUseCoinstraints gameplayConstraints'0
playerUseCoinstraints = 5000
constraintsStage2Count = 500
allowedBad = round $ 0.10 * fromIntegral workSetSize
workSetSize = 300
singleNeuronTarget = 0.9
localSearch = 0.003
attemptsCount = 4
mkLayer :: [SingleNeuron] -> [[Int]] -> GNetwork
mkLayer neurons refs = let ws = [map ((\ [[w]] -> w ) . fst) neurons]
bs = [map ((\ [[b]] -> b ) . snd) neurons]
in mkGNetwork ws bs refs
getNeuronSize :: SingleNeuron -> Int
getNeuronSize ([[w]],_) = length w
main :: IO ()
main = runThrLocMainIO $ do
printTL "DBN read/train"
fn <- getDBNCachedOrNew useCachedDBN dbnGameCount dbnGameProb dbnMatlabOpts
-- let fn = "tmp-data/iybjioktvbdgmjocdtow/dbn.txt"
-- let fn = "tmp-data/iwssqgpqsryvajvoerqi/dbn.txt"
printTL ("DBN FN=",fn)
dbn <- getDBNFile fn
let dbnG = fromTNetwork dbn
printTL "Constraint generation"
constraints <- getConstraints constraintSource
let constraintsPacked = map (packConstraint dbn) $ concatMap (uncurry generateConstraintsSimpleAll) constraints
printTL ("Total coinstraint count", length constraintsPacked)
printTL "Evaluating packed constraints..."
print $ head constraintsPacked
(constraintsPacked `using` parList rdeepseq) `deepseq` printTL "Done."
printTL "Perform multiNeuronMinimalGAReprSearch"
threads <- getNumCapabilities
scoredNeurons <- multiNeuronMinimalGAReprSearch threads allowedBad workSetSize searchTimeoutMulti singleNeuronTarget constraintsPacked
let neurons = map fst scoredNeurons
printTL "Do few times: train last layer network & evaluate"
forM_ [1..attemptsCount] $ \ attempt -> do
let newLayer = mkLayer neurons [[0]] -- (neurons ++ mkBypass (getNeuronSize (head neurons)))
dbnBigger = appendGNetwork dbnG newLayer
constraintsPackedBigger = take constraintsStage2Count $
map (packConstraint dbnBigger) $
concatMap (uncurry generateConstraintsSimpleAll) constraints
printTL ("dbnBigger", dbnBigger)
printTL ("newLayer", newLayer, length neurons)
bestRef <- newIORef (undefined, neginf)
let wt thr'act = waitAnyCancel =<< withTimeout bestRef searchTimeout (mapM thr'act [1..threads])
(_, _bestGA) <- wt (\ thr -> async (singleNeuronMinimalGAReprSearch (searchCB bestRef) thr 1 constraintsPackedBigger Nothing))
(_, bestFinal) <- wt (\ thr -> async (singleNeuronLocalReprSearch (searchCB bestRef) bestRef localSearch 1 thr constraintsPackedBigger))
let finalNetwork = appendGNetwork dbnBigger (fromTNetwork (uncurry mkTNetwork (fst bestFinal)))
baseDir = takeDirectory fn
rndStr <- getRandomFileName
writeFile (baseDir </> "dbn-final-data-ggexp6-"++rndStr++".txt") $ show $ finalNetwork
wins <- evaluateLL finalNetwork (snd bestFinal)
writeFile (baseDir </> "dbn-final-info-ggexp6-"++rndStr++".txt") $ showExperimentConfig wins bestFinal
showExperimentConfig wins bestFinal = unlines $
["wins " ++ (show wins )
,"bestFinal " ++ (show bestFinal )
,"useCachedDBN " ++ (show useCachedDBN )
,"searchTimeout " ++ (show searchTimeout )
,"searchTimeoutMulti " ++ (show searchTimeoutMulti )
,"dbnGameCount " ++ (show dbnGameCount )
,"dbnGameProb " ++ (show dbnGameProb )
,"dbnMatlabOpts " ++ (show dbnMatlabOpts )
,"constraintSource " ++ (show constraintSource )
,"playerUseCoinstraints" ++ (show playerUseCoinstraints)
,"allowedBad " ++ (show allowedBad )
,"workSetSize " ++ (show workSetSize )
,"singleNeuronTarget " ++ (show singleNeuronTarget )
,"localSearch " ++ (show localSearch )
]
|
Tener/deeplearning-thesis
|
src/gg-exp6.hs
|
bsd-3-clause
| 4,705
| 0
| 21
| 1,078
| 1,188
| 617
| 571
| 93
| 1
|
module Data.AllTimetables where
import Data.OneLecture
{- |
'AllTimetables' represents all valid timetables as list.
-}
type AllTimetables = [[OneLecture]]
|
spirit-fhs/core
|
Data/AllTimetables.hs
|
bsd-3-clause
| 160
| 0
| 6
| 23
| 24
| 16
| 8
| 3
| 0
|
module Solr.Query.Param where
import Solr.Prelude
import Builder
import Solr.Query.Filter.Internal
import Solr.Query.Internal.Internal
-- | A query parameter.
data Param where
ParamFl :: Text -> Param
ParamFq :: Query query => FilterParams query -> query -> Param
ParamRows :: Int -> Param
ParamSort :: [(Text, SortWay)] -> Param
ParamStart :: Int -> Param
data SortWay
= Asc
| Desc
-- | The @\'fl\'@ query parameter.
fl :: Text -> Param
fl = ParamFl
-- | The @\'fq\'@ query parameter.
fq :: Query query => FilterParams query -> query -> Param
fq = ParamFq
-- | The @\'rows\'@ query parameter.
rows :: Int -> Param
rows = ParamRows
-- | The @\'sort\'@ query parameter.
sort :: [(Text, SortWay)] -> Param
sort = ParamSort
-- | The @\'start\'@ query parameter.
start :: Int -> Param
start = ParamStart
-- | Compile a 'Param' to a its ('Builder', 'Builder') equivalent.
compileParam :: Param -> (Builder, Builder)
compileParam = \case
ParamFl s -> ("fl", thaw' s)
ParamFq locals query -> ("fq", compileFilterQuery locals query)
ParamRows n -> ("rows", bshow n)
ParamSort ss -> ("sort", intersperse ',' (map compileSortParam ss))
ParamStart n -> ("start", bshow n)
compileSortParam :: (Text, SortWay) -> Builder
compileSortParam = \case
(s, Asc) -> thaw' s <> " asc"
(s, Desc) -> thaw' s <> " desc"
|
Sentenai/solr-query
|
src/Solr/Query/Param.hs
|
bsd-3-clause
| 1,379
| 0
| 11
| 298
| 397
| 223
| 174
| -1
| -1
|
{-# LANGUAGE QuasiQuotes, RecordWildCards, NamedFieldPuns #-}
{-# LANGUAGE FlexibleContexts #-}
module CHR2.Target.PostgreSQL where
import Data.String.Interpolate
import Data.Function
import Control.Monad
import Control.Monad.Error
import Control.Monad.RWS.Strict
import Control.Monad.State.Strict
import Control.Monad.Writer.Strict
import Control.Monad.Reader
import qualified Data.Text as T
import Data.Text(Text)
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import Data.Maybe
import Data.List
import Data.List.Split
import Database.Persist
import CHR2.AST.Untyped
import CHR2.Compile
-- * replace String
-- * replace ErrorT
-- CHR based thoughts
-- * Set constraint means id isn't required
-- * no needs for propogation history because no variables in stores
constrSchema :: String -> TableInfo -> String
constrSchema n TableInfo{..} =
[i|
DROP TABLE IF EXISTS "#{n}" CASCADE;
CREATE TABLE "#{n}" (
id SERIAL PRIMARY KEY,
#{sep ",\n " $ map hlp $ zip _tiTypes _tiCols}
);
|]
where
hlp (t,x) = [i|#{show x} #{sqlType t} NOT NULL|]
-- adds condition for avoiding same constraint in single rule
-- riHConstrTables :: M.Map Int (TableInfo,C),
needsPH :: RuleInfo -> Bool
needsPH _ = False -- TODO: aggregations may need it
isPRule :: RuleInfo -> Bool
isPRule RuleInfo{_riNegative} = null _riNegative
-- TODO: needs vars' resolution, since some may be bound to another vars
writeRulePreView :: RWM ()
writeRulePreView = do
ri@RuleInfo{..} <- ask
let vars = M.toList _riVarDef
let tables = M.toList _riHConstrTables
let flds = map (\ (x,_) -> [i|t$#{x}.id AS t$#{x}$id|]) tables
++ map (\(n,(v:_)) -> [i|#{sqlValStr v} AS #{n}|]) vars
let
-- propagation history in separate table
phc =
[i|chr$ph.ruleId = #{_riId}|] :
map (\(x,_) -> [i|t$#{x}.id = chr$ph$c#{x}|]) tables
phcond = if isPRule ri then
if needsPH ri then [[i|
NOT EXISTS (SELECT 1 FROM chr$ph WHERE #{sep " AND " $ phc})|]]
else let phc = concat
$ intersperse " OR "
$ map (\(x,_) -> [i|t$#{x}.chr$ph$c#{x} <> 't'|])
tables
in [[i|(#{phc})|]]
else []
when (isPRule ri && not (needsPH ri)) $
mapM_ (\(x,(_,C _ a _)) ->
tellLine
[i|ALTER TABLE #{a} ADD COLUMN chr$ph$c#{x} BOOLEAN DEFAULT 'f';|]
) tables
tell [i|
CREATE VIEW pr$#{_riName} AS SELECT\n|]
tell $ ind 1 $ sep ", " flds
tell "\n\tFROM "
tell $ sep ", " $ map (\ (x,(_,(C _ a _))) -> [i|#{a} t$#{x}|]) tables
let cond = (concat
$ map (\(n, e) ->
map (\ (l,r) -> [i|#{l} = #{r}|]) $ pairs $ map sqlValStr e
) vars)
++ _riCond ++ phcond
unless (null cond) $ do
tell $ "\n\tWHERE "
tell $ sep " AND " cond
tell ";"
where
pairs = map (\ (l:r:_) -> (l,r)) . filter ((> 1) . length) . tails
emptyUnless :: Bool -> [a] -> [a]
emptyUnless True v = v
emptyUnless False _ = []
condStr [] = ""
condStr n = [i|WHERE #{sep " AND " n}|]
writeRuleView :: RWM ()
writeRuleView = do
RuleInfo{..} <- ask
tell [i|
CREATE VIEW r$#{_riName} AS SELECT * FROM pr$#{_riName};|]
tellLine n = tell "\n" >> tell n
writeSolveScript :: RWM ()
writeSolveScript = do
ri@RuleInfo{..} <- ask
tellLine [i|
CREATE OR REPLACE FUNCTION step$#{_riName}() RETURNS INTEGER AS $$|]
tellLine [i|
DECLARE
result INTEGER;
BEGIN
CREATE TEMP TABLE t$#{_riName}
-- ON COMMIT PRESERVE ROWS
AS SELECT * FROM r$#{_riName};|]
-- DELETES
mapM_ (\c@(x,(C _ n _)) -> do
tell [i|
DELETE FROM #{n}
USING t$#{_riName} tmp
WHERE id = tmp.t$#{x}$id;|]
) _riNegative
when (isPRule ri) $ do
let (col,val) = unzip
$ map (\(x,_) -> ([i|,c#{x}|], [i|,t$#{x}$id|])) _riPositive
if needsPH ri then
tell [i|
INSERT INTO chr$ph(ruleId#{concat col})
SELECT '#{_riId}'#{concat val}
FROM t$#{_riName};|]
else
mapM_ (\(x,C _ tn _) -> tell [i|
UPDATE #{tn} SET chr$ph$c#{x} = 'y'
FROM t$#{_riName}
WHERE #{tn}.id = t$#{_riName}.t$#{x}$id;|]) _riPositive
tellLine "-- COMMIT;"
-- BATCHES: TODO
mapM_ (\ BatchInfo{..} -> do
tellLine "-- BEGIN;"
-- TODO: this probably should be interleaved in order they appear
mapM_ (\(isChr,(C _ n args)) ->
if isChr then do
TableInfo{..} <- getTableInfo n
tell [i|
INSERT INTO #{n}(#{sep ", " $ map show _tiCols})
SELECT #{sep ", " $ map termToSql args} FROM t$#{_riName};|]
else do
return ()
) _biConstrs
tellLine "-- COMMIT;"
) _riBatches
tellLine [i|
result := (SELECT count(*) FROM t$#{_riName});
DROP TABLE t$#{_riName};
RETURN result;
END;
$$ LANGUAGE plpgsql;|]
return ()
translateEnv :: M ()
translateEnv = do
tellLine "---------------- SOLVE STEPS -------------------"
translateConstrs
translateRules
translateConstrs :: M ()
translateConstrs = tell =<<
asks (concat . map (uncurry constrSchema) . M.toList . _tables)
toVariable :: Term -> Maybe String
toVariable (Var _ n) = Just n
toVariable _ = Nothing
translateRules :: M ()
translateRules = do
ri <- return . map snd . M.toList
=<< analyzeRules
let mxp = maximum $ map (length . _riPositive)
$ filter (null . _riNegative) ri
let names = map _riName ri
tell [i|
DROP TABLE IF EXISTS chr$ph;
CREATE TABLE chr$ph (
ruleId INTEGER,
#{sep ",\n " $
map (\j -> "c" ++ show j ++ " INTEGER") [0..mxp-1]});|]
let step s = mapM_ (runRWM s) ri
step writeRulePreView
step writeRuleView
tellLine "---------------- SOLVE STEPS -------------------"
step writeSolveScript
let decls = concat $ map (\x -> [i|
#{x}$exit BOOLEAN;|]) names
let calls = concat $ map (\x -> [i|
#{x}$exit := step$#{x}() = 0;|]) names
let exitCond = sep " AND " $ map (\x -> [i|#{x}$exit|]) names
tell [i|
CREATE OR REPLACE FUNCTION simple$solver() RETURNS BOOLEAN AS $$
DECLARE#{decls}
BEGIN
LOOP#{calls}
IF #{exitCond} THEN
EXIT;
END IF;
END LOOP;
RETURN TRUE;
END;
$$ LANGUAGE plpgsql;
|]
publishScript :: Env -> IO ()
publishScript e@Env{..} = do
r <- runM e translateEnv
case r of
Right (v,w) -> writeFile (_name ++ "_migrate.sql") w
Left e -> fail e
-- FROM Database.Persist.Postgresql
showSqlType :: SqlType -> String
showSqlType SqlString = "VARCHAR"
showSqlType SqlInt32 = "INT4"
showSqlType SqlInt64 = "INT8"
showSqlType SqlReal = "DOUBLE PRECISION"
showSqlType (SqlNumeric s prec) = concat [ "NUMERIC(", (show s), ",", (show prec), ")" ]
showSqlType SqlDay = "DATE"
showSqlType SqlTime = "TIME"
showSqlType SqlDayTime = "TIMESTAMP WITH TIME ZONE"
showSqlType SqlBlob = "BYTEA"
showSqlType SqlBool = "BOOLEAN"
sqlType :: Ty -> String
sqlType (SqlTy t) = showSqlType t
|
awto/chr2sql
|
CHR2/Target/PostgreSQL.hs
|
bsd-3-clause
| 7,117
| 0
| 22
| 1,905
| 1,897
| 1,027
| 870
| 155
| 3
|
module Main where
import Reddit
import Reddit.Types.Flair
import Reddit.Types.Options
import Reddit.Types.Subreddit
import Reddit.Types.User
import Control.Applicative ((<$>))
import Control.Arrow ((&&&))
import Data.List (sortBy)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import Data.Ord (Down(..), comparing)
import Data.Text (Text)
import System.Environment (getArgs)
import qualified Data.Map as Map
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
main :: IO ()
main = do
args <- map Text.pack <$> getArgs
case args of
username : password : subreddit : [] -> do
res <- runRedditWithRateLimiting username password $
getAllFlairs (R subreddit) Nothing
case res of
Left err -> print err
Right fs -> do
Text.putStrLn $ formatFlairs $ countFlairs fs
Text.putStrLn ""
Text.putStrLn $ textShow (length fs) <> " users have chosen flair"
_ -> putStrLn "Usage: flair-counter USERNAME PASSWORD SUBREDDIT"
getAllFlairs :: SubredditName -> Maybe UserID -> Reddit [Flair]
getAllFlairs sub u = do
res <-
nest $ getFlairList' (Options (After <$> u) (Just 1000)) sub
case res of
Left _ -> getAllFlairs sub u
Right (FlairList fs n _) ->
case n of
Just _ -> do
more <- getAllFlairs sub n
return $ fs ++ more
Nothing -> return fs
countFlairs :: [Flair] -> [(Text, Integer)]
countFlairs = Map.toList . Map.fromListWith (+) . map (Text.strip . fromMaybe "" . cssClass &&& const 1)
formatFlairs :: [(Text, Integer)] -> Text
formatFlairs =
Text.unlines .
map (\(a,b) -> a <> " | " <> textShow b) .
sortBy (comparing (Down . snd))
textShow :: Show a => a -> Text
textShow = Text.pack . show
|
intolerable/flair-counter
|
Main.hs
|
bsd-3-clause
| 1,758
| 0
| 21
| 401
| 644
| 340
| 304
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
{-|
'Snap.Extension.Timer.Timer' is an implementation of the 'MonadTimer'
interface defined in 'Snap.Extension.Timer'.
As always, to use, add 'TimerState' to your application's state, along with an
instance of 'HasTimerState' for your application's state, making sure to use a
'timerInitializer' in your application's 'Initializer', and then you're ready to go.
This implementation does not require that your application's monad implement
interfaces from any other Snap Extension.
-}
module Snap.Extension.Timer.Timer
( TimerState
, HasTimerState(..)
, timerInitializer
) where
import Control.Monad.Reader
import Control.Monad.Trans
import Data.Time.Clock
import Snap.Extension
import Snap.Extension.Timer
import Snap.Types
------------------------------------------------------------------------------
-- | Your application's state must include a 'TimerState' in order for your
-- application to be a 'MonadTimer'.
newtype TimerState = TimerState
{ _startTime :: UTCTime
}
------------------------------------------------------------------------------
-- | For you appliaction's monad to be a 'MonadTimer', your application's
-- state needs to be an instance of 'HasTimerState'. Minimal complete
-- definition: 'getTimerState', 'setTimerState'.
class HasTimerState s where
getTimerState :: s -> TimerState
setTimerState :: TimerState -> s -> s
------------------------------------------------------------------------------
-- | The Initializer for 'TimerState'. No arguments are required.
timerInitializer :: Initializer TimerState
timerInitializer = liftIO getCurrentTime >>= mkInitializer . TimerState
------------------------------------------------------------------------------
instance InitializerState TimerState where
extensionId = const "Timer/Timer"
mkCleanup = const $ return ()
mkReload = const $ return ()
------------------------------------------------------------------------------
instance HasTimerState s => MonadTimer (SnapExtend s) where
startTime = fmap _startTime $ asks getTimerState
------------------------------------------------------------------------------
instance (MonadSnap m, HasTimerState s) => MonadTimer (ReaderT s m) where
startTime = fmap _startTime $ asks getTimerState
|
duairc/snap-extensions
|
src/Snap/Extension/Timer/Timer.hs
|
bsd-3-clause
| 2,372
| 0
| 8
| 370
| 265
| 151
| 114
| 26
| 1
|
module Language.Nextgen.Quote where
|
achudnov/language-nextgen
|
Language/Nextgen/Quote.hs
|
bsd-3-clause
| 36
| 0
| 3
| 3
| 7
| 5
| 2
| 1
| 0
|
module Graphics.UI.SDL.Event (
-- * Event Handling
addEventWatch,
delEventWatch,
eventState,
filterEvents,
flushEvent,
flushEvents,
getEventFilter,
getNumTouchDevices,
getNumTouchFingers,
getTouchDevice,
getTouchFinger,
hasEvent,
hasEvents,
loadDollarTemplates,
peepEvents,
pollEvent,
pumpEvents,
pushEvent,
quitRequested,
recordGesture,
registerEvents,
saveAllDollarTemplates,
saveDollarTemplate,
setEventFilter,
waitEvent,
waitEventTimeout,
-- * Keyboard Support
getKeyFromName,
getKeyFromScancode,
getKeyName,
getKeyboardFocus,
getKeyboardState,
getModState,
getScancodeFromKey,
getScancodeFromName,
getScancodeName,
hasScreenKeyboardSupport,
isScreenKeyboardShown,
isTextInputActive,
setModState,
setTextInputRect,
startTextInput,
stopTextInput,
-- * Mouse Support
createColorCursor,
createCursor,
createSystemCursor,
freeCursor,
getCursor,
getDefaultCursor,
getMouseFocus,
getMouseState,
getRelativeMouseMode,
getRelativeMouseState,
setCursor,
setRelativeMouseMode,
showCursor,
warpMouseInWindow,
-- * Joystick Support
joystickClose,
joystickEventState,
joystickGetAttached,
joystickGetAxis,
joystickGetBall,
joystickGetButton,
joystickGetDeviceGUID,
joystickGetGUID,
joystickGetGUIDFromString,
joystickGetGUIDString,
joystickGetHat,
joystickInstanceID,
joystickName,
joystickNameForIndex,
joystickNumAxes,
joystickNumBalls,
joystickNumButtons,
joystickNumHats,
joystickOpen,
joystickUpdate,
numJoysticks,
-- * Game Controller Support
gameControllerAddMapping,
gameControllerAddMappingsFromFile,
gameControllerAddMappingsFromRW,
gameControllerClose,
gameControllerEventState,
gameControllerGetAttached,
gameControllerGetAxis,
gameControllerGetAxisFromString,
gameControllerGetBindForAxis,
gameControllerGetBindForButton,
gameControllerGetButton,
gameControllerGetButtonFromString,
gameControllerGetJoystick,
gameControllerGetStringForAxis,
gameControllerGetStringForButton,
gameControllerMapping,
gameControllerMappingForGUID,
gameControllerName,
gameControllerNameForIndex,
gameControllerOpen,
gameControllerUpdate,
isGameController
) where
import Control.Monad.IO.Class
import Data.Int
import Data.Word
import Foreign.C.String
import Foreign.C.Types
import Foreign.Marshal.Alloc
import Foreign.Ptr
import Foreign.Storable
import Graphics.UI.SDL.Enum
import Graphics.UI.SDL.Filesystem
import Graphics.UI.SDL.Types
foreign import ccall "SDL.h SDL_AddEventWatch" addEventWatch' :: EventFilter -> Ptr () -> IO ()
foreign import ccall "SDL.h SDL_DelEventWatch" delEventWatch' :: EventFilter -> Ptr () -> IO ()
foreign import ccall "SDL.h SDL_EventState" eventState' :: Word32 -> CInt -> IO Word8
foreign import ccall "SDL.h SDL_FilterEvents" filterEvents' :: EventFilter -> Ptr () -> IO ()
foreign import ccall "SDL.h SDL_FlushEvent" flushEvent' :: Word32 -> IO ()
foreign import ccall "SDL.h SDL_FlushEvents" flushEvents' :: Word32 -> Word32 -> IO ()
foreign import ccall "SDL.h SDL_GetEventFilter" getEventFilter' :: Ptr EventFilter -> Ptr (Ptr ()) -> IO Bool
foreign import ccall "SDL.h SDL_GetNumTouchDevices" getNumTouchDevices' :: IO CInt
foreign import ccall "SDL.h SDL_GetNumTouchFingers" getNumTouchFingers' :: TouchID -> IO CInt
foreign import ccall "SDL.h SDL_GetTouchDevice" getTouchDevice' :: CInt -> IO TouchID
foreign import ccall "SDL.h SDL_GetTouchFinger" getTouchFinger' :: TouchID -> CInt -> IO (Ptr Finger)
foreign import ccall "SDL.h SDL_HasEvent" hasEvent' :: Word32 -> IO Bool
foreign import ccall "SDL.h SDL_HasEvents" hasEvents' :: Word32 -> Word32 -> IO Bool
foreign import ccall "SDL.h SDL_LoadDollarTemplates" loadDollarTemplates' :: TouchID -> Ptr RWops -> IO CInt
foreign import ccall "SDL.h SDL_PeepEvents" peepEvents' :: Ptr Event -> CInt -> EventAction -> Word32 -> Word32 -> IO CInt
foreign import ccall "SDL.h SDL_PollEvent" pollEvent' :: Ptr Event -> IO CInt
foreign import ccall "SDL.h SDL_PumpEvents" pumpEvents' :: IO ()
foreign import ccall "SDL.h SDL_PushEvent" pushEvent' :: Ptr Event -> IO CInt
foreign import ccall "SDL.h SDL_RecordGesture" recordGesture' :: TouchID -> IO CInt
foreign import ccall "SDL.h SDL_RegisterEvents" registerEvents' :: CInt -> IO Word32
foreign import ccall "SDL.h SDL_SaveAllDollarTemplates" saveAllDollarTemplates' :: Ptr RWops -> IO CInt
foreign import ccall "SDL.h SDL_SaveDollarTemplate" saveDollarTemplate' :: GestureID -> Ptr RWops -> IO CInt
foreign import ccall "SDL.h SDL_SetEventFilter" setEventFilter' :: EventFilter -> Ptr () -> IO ()
foreign import ccall "SDL.h SDL_WaitEvent" waitEvent' :: Ptr Event -> IO CInt
foreign import ccall "SDL.h SDL_WaitEventTimeout" waitEventTimeout' :: Ptr Event -> CInt -> IO CInt
foreign import ccall "SDL.h SDL_GetKeyFromName" getKeyFromName' :: CString -> IO Keycode
foreign import ccall "SDL.h SDL_GetKeyFromScancode" getKeyFromScancode' :: Scancode -> IO Keycode
foreign import ccall "SDL.h SDL_GetKeyName" getKeyName' :: Keycode -> IO CString
foreign import ccall "SDL.h SDL_GetKeyboardFocus" getKeyboardFocus' :: IO Window
foreign import ccall "SDL.h SDL_GetKeyboardState" getKeyboardState' :: Ptr CInt -> IO (Ptr Word8)
foreign import ccall "SDL.h SDL_GetModState" getModState' :: IO Keymod
foreign import ccall "SDL.h SDL_GetScancodeFromKey" getScancodeFromKey' :: Keycode -> IO Scancode
foreign import ccall "SDL.h SDL_GetScancodeFromName" getScancodeFromName' :: CString -> IO Scancode
foreign import ccall "SDL.h SDL_GetScancodeName" getScancodeName' :: Scancode -> IO CString
foreign import ccall "SDL.h SDL_HasScreenKeyboardSupport" hasScreenKeyboardSupport' :: IO Bool
foreign import ccall "SDL.h SDL_IsScreenKeyboardShown" isScreenKeyboardShown' :: Window -> IO Bool
foreign import ccall "SDL.h SDL_IsTextInputActive" isTextInputActive' :: IO Bool
foreign import ccall "SDL.h SDL_SetModState" setModState' :: Keymod -> IO ()
foreign import ccall "SDL.h SDL_SetTextInputRect" setTextInputRect' :: Ptr Rect -> IO ()
foreign import ccall "SDL.h SDL_StartTextInput" startTextInput' :: IO ()
foreign import ccall "SDL.h SDL_StopTextInput" stopTextInput' :: IO ()
foreign import ccall "SDL.h SDL_CreateColorCursor" createColorCursor' :: Ptr Surface -> CInt -> CInt -> IO Cursor
foreign import ccall "SDL.h SDL_CreateCursor" createCursor' :: Ptr Word8 -> Ptr Word8 -> CInt -> CInt -> CInt -> CInt -> IO Cursor
foreign import ccall "SDL.h SDL_CreateSystemCursor" createSystemCursor' :: SystemCursor -> IO Cursor
foreign import ccall "SDL.h SDL_FreeCursor" freeCursor' :: Cursor -> IO ()
foreign import ccall "SDL.h SDL_GetCursor" getCursor' :: IO Cursor
foreign import ccall "SDL.h SDL_GetDefaultCursor" getDefaultCursor' :: IO Cursor
foreign import ccall "SDL.h SDL_GetMouseFocus" getMouseFocus' :: IO Window
foreign import ccall "SDL.h SDL_GetMouseState" getMouseState' :: Ptr CInt -> Ptr CInt -> IO Word32
foreign import ccall "SDL.h SDL_GetRelativeMouseMode" getRelativeMouseMode' :: IO Bool
foreign import ccall "SDL.h SDL_GetRelativeMouseState" getRelativeMouseState' :: Ptr CInt -> Ptr CInt -> IO Word32
foreign import ccall "SDL.h SDL_SetCursor" setCursor' :: Cursor -> IO ()
foreign import ccall "SDL.h SDL_SetRelativeMouseMode" setRelativeMouseMode' :: Bool -> IO CInt
foreign import ccall "SDL.h SDL_ShowCursor" showCursor' :: CInt -> IO CInt
foreign import ccall "SDL.h SDL_WarpMouseInWindow" warpMouseInWindow' :: Window -> CInt -> CInt -> IO ()
foreign import ccall "SDL.h SDL_JoystickClose" joystickClose' :: Joystick -> IO ()
foreign import ccall "SDL.h SDL_JoystickEventState" joystickEventState' :: CInt -> IO CInt
foreign import ccall "SDL.h SDL_JoystickGetAttached" joystickGetAttached' :: Joystick -> IO Bool
foreign import ccall "SDL.h SDL_JoystickGetAxis" joystickGetAxis' :: Joystick -> CInt -> IO Int16
foreign import ccall "SDL.h SDL_JoystickGetBall" joystickGetBall' :: Joystick -> CInt -> Ptr CInt -> Ptr CInt -> IO CInt
foreign import ccall "SDL.h SDL_JoystickGetButton" joystickGetButton' :: Joystick -> CInt -> IO Word8
foreign import ccall "sdlhelper.h SDLHelper_JoystickGetDeviceGUID" joystickGetDeviceGUID' :: CInt -> Ptr JoystickGUID -> IO ()
foreign import ccall "sdlhelper.h SDLHelper_JoystickGetGUID" joystickGetGUID' :: Joystick -> Ptr JoystickGUID -> IO ()
foreign import ccall "sdlhelper.h SDLHelper_JoystickGetGUIDFromString" joystickGetGUIDFromString' :: CString -> Ptr JoystickGUID -> IO ()
foreign import ccall "sdlhelper.h SDLHelper_JoystickGetGUIDString" joystickGetGUIDString' :: Ptr JoystickGUID -> CString -> CInt -> IO ()
foreign import ccall "SDL.h SDL_JoystickGetHat" joystickGetHat' :: Joystick -> CInt -> IO Word8
foreign import ccall "SDL.h SDL_JoystickInstanceID" joystickInstanceID' :: Joystick -> IO JoystickID
foreign import ccall "SDL.h SDL_JoystickName" joystickName' :: Joystick -> IO CString
foreign import ccall "SDL.h SDL_JoystickNameForIndex" joystickNameForIndex' :: CInt -> IO CString
foreign import ccall "SDL.h SDL_JoystickNumAxes" joystickNumAxes' :: Joystick -> IO CInt
foreign import ccall "SDL.h SDL_JoystickNumBalls" joystickNumBalls' :: Joystick -> IO CInt
foreign import ccall "SDL.h SDL_JoystickNumButtons" joystickNumButtons' :: Joystick -> IO CInt
foreign import ccall "SDL.h SDL_JoystickNumHats" joystickNumHats' :: Joystick -> IO CInt
foreign import ccall "SDL.h SDL_JoystickOpen" joystickOpen' :: CInt -> IO Joystick
foreign import ccall "SDL.h SDL_JoystickUpdate" joystickUpdate' :: IO ()
foreign import ccall "SDL.h SDL_NumJoysticks" numJoysticks' :: IO CInt
foreign import ccall "SDL.h SDL_GameControllerAddMapping" gameControllerAddMapping' :: CString -> IO CInt
foreign import ccall "SDL.h SDL_GameControllerAddMappingsFromRW" gameControllerAddMappingsFromRW' :: Ptr RWops -> CInt -> IO CInt
foreign import ccall "SDL.h SDL_GameControllerClose" gameControllerClose' :: GameController -> IO ()
foreign import ccall "SDL.h SDL_GameControllerEventState" gameControllerEventState' :: CInt -> IO CInt
foreign import ccall "SDL.h SDL_GameControllerGetAttached" gameControllerGetAttached' :: GameController -> IO Bool
foreign import ccall "SDL.h SDL_GameControllerGetAxis" gameControllerGetAxis' :: GameController -> GameControllerAxis -> IO Int16
foreign import ccall "SDL.h SDL_GameControllerGetAxisFromString" gameControllerGetAxisFromString' :: CString -> IO GameControllerAxis
foreign import ccall "sdlhelper.h SDLHelper_GameControllerGetBindForAxis" gameControllerGetBindForAxis' :: GameController -> GameControllerAxis -> Ptr GameControllerButtonBind -> IO ()
foreign import ccall "sdlhelper.h SDLHelper_GameControllerGetBindForButton" gameControllerGetBindForButton' :: GameController -> GameControllerButton -> Ptr GameControllerButtonBind -> IO ()
foreign import ccall "SDL.h SDL_GameControllerGetButton" gameControllerGetButton' :: GameController -> GameControllerButton -> IO Word8
foreign import ccall "SDL.h SDL_GameControllerGetButtonFromString" gameControllerGetButtonFromString' :: CString -> IO GameControllerButton
foreign import ccall "SDL.h SDL_GameControllerGetJoystick" gameControllerGetJoystick' :: GameController -> IO Joystick
foreign import ccall "SDL.h SDL_GameControllerGetStringForAxis" gameControllerGetStringForAxis' :: GameControllerAxis -> IO CString
foreign import ccall "SDL.h SDL_GameControllerGetStringForButton" gameControllerGetStringForButton' :: GameControllerButton -> IO CString
foreign import ccall "SDL.h SDL_GameControllerMapping" gameControllerMapping' :: GameController -> IO CString
foreign import ccall "sdlhelper.h SDLHelper_GameControllerMappingForGUID" gameControllerMappingForGUID' :: Ptr JoystickGUID -> IO CString
foreign import ccall "SDL.h SDL_GameControllerName" gameControllerName' :: GameController -> IO CString
foreign import ccall "SDL.h SDL_GameControllerNameForIndex" gameControllerNameForIndex' :: CInt -> IO CString
foreign import ccall "SDL.h SDL_GameControllerOpen" gameControllerOpen' :: CInt -> IO GameController
foreign import ccall "SDL.h SDL_GameControllerUpdate" gameControllerUpdate' :: IO ()
foreign import ccall "SDL.h SDL_IsGameController" isGameController' :: CInt -> IO Bool
addEventWatch :: MonadIO m => EventFilter -> Ptr () -> m ()
addEventWatch v1 v2 = liftIO $ addEventWatch' v1 v2
{-# INLINE addEventWatch #-}
delEventWatch :: MonadIO m => EventFilter -> Ptr () -> m ()
delEventWatch v1 v2 = liftIO $ delEventWatch' v1 v2
{-# INLINE delEventWatch #-}
eventState :: MonadIO m => Word32 -> CInt -> m Word8
eventState v1 v2 = liftIO $ eventState' v1 v2
{-# INLINE eventState #-}
filterEvents :: MonadIO m => EventFilter -> Ptr () -> m ()
filterEvents v1 v2 = liftIO $ filterEvents' v1 v2
{-# INLINE filterEvents #-}
flushEvent :: MonadIO m => Word32 -> m ()
flushEvent v1 = liftIO $ flushEvent' v1
{-# INLINE flushEvent #-}
flushEvents :: MonadIO m => Word32 -> Word32 -> m ()
flushEvents v1 v2 = liftIO $ flushEvents' v1 v2
{-# INLINE flushEvents #-}
getEventFilter :: MonadIO m => Ptr EventFilter -> Ptr (Ptr ()) -> m Bool
getEventFilter v1 v2 = liftIO $ getEventFilter' v1 v2
{-# INLINE getEventFilter #-}
getNumTouchDevices :: MonadIO m => m CInt
getNumTouchDevices = liftIO getNumTouchDevices'
{-# INLINE getNumTouchDevices #-}
getNumTouchFingers :: MonadIO m => TouchID -> m CInt
getNumTouchFingers v1 = liftIO $ getNumTouchFingers' v1
{-# INLINE getNumTouchFingers #-}
getTouchDevice :: MonadIO m => CInt -> m TouchID
getTouchDevice v1 = liftIO $ getTouchDevice' v1
{-# INLINE getTouchDevice #-}
getTouchFinger :: MonadIO m => TouchID -> CInt -> m (Ptr Finger)
getTouchFinger v1 v2 = liftIO $ getTouchFinger' v1 v2
{-# INLINE getTouchFinger #-}
hasEvent :: MonadIO m => Word32 -> m Bool
hasEvent v1 = liftIO $ hasEvent' v1
{-# INLINE hasEvent #-}
hasEvents :: MonadIO m => Word32 -> Word32 -> m Bool
hasEvents v1 v2 = liftIO $ hasEvents' v1 v2
{-# INLINE hasEvents #-}
loadDollarTemplates :: MonadIO m => TouchID -> Ptr RWops -> m CInt
loadDollarTemplates v1 v2 = liftIO $ loadDollarTemplates' v1 v2
{-# INLINE loadDollarTemplates #-}
peepEvents :: MonadIO m => Ptr Event -> CInt -> EventAction -> Word32 -> Word32 -> m CInt
peepEvents v1 v2 v3 v4 v5 = liftIO $ peepEvents' v1 v2 v3 v4 v5
{-# INLINE peepEvents #-}
pollEvent :: MonadIO m => Ptr Event -> m CInt
pollEvent v1 = liftIO $ pollEvent' v1
{-# INLINE pollEvent #-}
pumpEvents :: MonadIO m => m ()
pumpEvents = liftIO pumpEvents'
{-# INLINE pumpEvents #-}
pushEvent :: MonadIO m => Ptr Event -> m CInt
pushEvent v1 = liftIO $ pushEvent' v1
{-# INLINE pushEvent #-}
quitRequested :: MonadIO m => m Bool
quitRequested = liftIO $ do
pumpEvents
ev <- peepEvents nullPtr 0 SDL_PEEKEVENT SDL_QUIT SDL_QUIT
return $ ev > 0
{-# INLINE quitRequested #-}
recordGesture :: MonadIO m => TouchID -> m CInt
recordGesture v1 = liftIO $ recordGesture' v1
{-# INLINE recordGesture #-}
registerEvents :: MonadIO m => CInt -> m Word32
registerEvents v1 = liftIO $ registerEvents' v1
{-# INLINE registerEvents #-}
saveAllDollarTemplates :: MonadIO m => Ptr RWops -> m CInt
saveAllDollarTemplates v1 = liftIO $ saveAllDollarTemplates' v1
{-# INLINE saveAllDollarTemplates #-}
saveDollarTemplate :: MonadIO m => GestureID -> Ptr RWops -> m CInt
saveDollarTemplate v1 v2 = liftIO $ saveDollarTemplate' v1 v2
{-# INLINE saveDollarTemplate #-}
setEventFilter :: MonadIO m => EventFilter -> Ptr () -> m ()
setEventFilter v1 v2 = liftIO $ setEventFilter' v1 v2
{-# INLINE setEventFilter #-}
waitEvent :: MonadIO m => Ptr Event -> m CInt
waitEvent v1 = liftIO $ waitEvent' v1
{-# INLINE waitEvent #-}
waitEventTimeout :: MonadIO m => Ptr Event -> CInt -> m CInt
waitEventTimeout v1 v2 = liftIO $ waitEventTimeout' v1 v2
{-# INLINE waitEventTimeout #-}
getKeyFromName :: MonadIO m => CString -> m Keycode
getKeyFromName v1 = liftIO $ getKeyFromName' v1
{-# INLINE getKeyFromName #-}
getKeyFromScancode :: MonadIO m => Scancode -> m Keycode
getKeyFromScancode v1 = liftIO $ getKeyFromScancode' v1
{-# INLINE getKeyFromScancode #-}
getKeyName :: MonadIO m => Keycode -> m CString
getKeyName v1 = liftIO $ getKeyName' v1
{-# INLINE getKeyName #-}
getKeyboardFocus :: MonadIO m => m Window
getKeyboardFocus = liftIO getKeyboardFocus'
{-# INLINE getKeyboardFocus #-}
getKeyboardState :: MonadIO m => Ptr CInt -> m (Ptr Word8)
getKeyboardState v1 = liftIO $ getKeyboardState' v1
{-# INLINE getKeyboardState #-}
getModState :: MonadIO m => m Keymod
getModState = liftIO getModState'
{-# INLINE getModState #-}
getScancodeFromKey :: MonadIO m => Keycode -> m Scancode
getScancodeFromKey v1 = liftIO $ getScancodeFromKey' v1
{-# INLINE getScancodeFromKey #-}
getScancodeFromName :: MonadIO m => CString -> m Scancode
getScancodeFromName v1 = liftIO $ getScancodeFromName' v1
{-# INLINE getScancodeFromName #-}
getScancodeName :: MonadIO m => Scancode -> m CString
getScancodeName v1 = liftIO $ getScancodeName' v1
{-# INLINE getScancodeName #-}
hasScreenKeyboardSupport :: MonadIO m => m Bool
hasScreenKeyboardSupport = liftIO hasScreenKeyboardSupport'
{-# INLINE hasScreenKeyboardSupport #-}
isScreenKeyboardShown :: MonadIO m => Window -> m Bool
isScreenKeyboardShown v1 = liftIO $ isScreenKeyboardShown' v1
{-# INLINE isScreenKeyboardShown #-}
isTextInputActive :: MonadIO m => m Bool
isTextInputActive = liftIO isTextInputActive'
{-# INLINE isTextInputActive #-}
setModState :: MonadIO m => Keymod -> m ()
setModState v1 = liftIO $ setModState' v1
{-# INLINE setModState #-}
setTextInputRect :: MonadIO m => Ptr Rect -> m ()
setTextInputRect v1 = liftIO $ setTextInputRect' v1
{-# INLINE setTextInputRect #-}
startTextInput :: MonadIO m => m ()
startTextInput = liftIO startTextInput'
{-# INLINE startTextInput #-}
stopTextInput :: MonadIO m => m ()
stopTextInput = liftIO stopTextInput'
{-# INLINE stopTextInput #-}
createColorCursor :: MonadIO m => Ptr Surface -> CInt -> CInt -> m Cursor
createColorCursor v1 v2 v3 = liftIO $ createColorCursor' v1 v2 v3
{-# INLINE createColorCursor #-}
createCursor :: MonadIO m => Ptr Word8 -> Ptr Word8 -> CInt -> CInt -> CInt -> CInt -> m Cursor
createCursor v1 v2 v3 v4 v5 v6 = liftIO $ createCursor' v1 v2 v3 v4 v5 v6
{-# INLINE createCursor #-}
createSystemCursor :: MonadIO m => SystemCursor -> m Cursor
createSystemCursor v1 = liftIO $ createSystemCursor' v1
{-# INLINE createSystemCursor #-}
freeCursor :: MonadIO m => Cursor -> m ()
freeCursor v1 = liftIO $ freeCursor' v1
{-# INLINE freeCursor #-}
getCursor :: MonadIO m => m Cursor
getCursor = liftIO getCursor'
{-# INLINE getCursor #-}
getDefaultCursor :: MonadIO m => m Cursor
getDefaultCursor = liftIO getDefaultCursor'
{-# INLINE getDefaultCursor #-}
getMouseFocus :: MonadIO m => m Window
getMouseFocus = liftIO getMouseFocus'
{-# INLINE getMouseFocus #-}
getMouseState :: MonadIO m => Ptr CInt -> Ptr CInt -> m Word32
getMouseState v1 v2 = liftIO $ getMouseState' v1 v2
{-# INLINE getMouseState #-}
getRelativeMouseMode :: MonadIO m => m Bool
getRelativeMouseMode = liftIO getRelativeMouseMode'
{-# INLINE getRelativeMouseMode #-}
getRelativeMouseState :: MonadIO m => Ptr CInt -> Ptr CInt -> m Word32
getRelativeMouseState v1 v2 = liftIO $ getRelativeMouseState' v1 v2
{-# INLINE getRelativeMouseState #-}
setCursor :: MonadIO m => Cursor -> m ()
setCursor v1 = liftIO $ setCursor' v1
{-# INLINE setCursor #-}
setRelativeMouseMode :: MonadIO m => Bool -> m CInt
setRelativeMouseMode v1 = liftIO $ setRelativeMouseMode' v1
{-# INLINE setRelativeMouseMode #-}
showCursor :: MonadIO m => CInt -> m CInt
showCursor v1 = liftIO $ showCursor' v1
{-# INLINE showCursor #-}
warpMouseInWindow :: MonadIO m => Window -> CInt -> CInt -> m ()
warpMouseInWindow v1 v2 v3 = liftIO $ warpMouseInWindow' v1 v2 v3
{-# INLINE warpMouseInWindow #-}
joystickClose :: MonadIO m => Joystick -> m ()
joystickClose v1 = liftIO $ joystickClose' v1
{-# INLINE joystickClose #-}
joystickEventState :: MonadIO m => CInt -> m CInt
joystickEventState v1 = liftIO $ joystickEventState' v1
{-# INLINE joystickEventState #-}
joystickGetAttached :: MonadIO m => Joystick -> m Bool
joystickGetAttached v1 = liftIO $ joystickGetAttached' v1
{-# INLINE joystickGetAttached #-}
joystickGetAxis :: MonadIO m => Joystick -> CInt -> m Int16
joystickGetAxis v1 v2 = liftIO $ joystickGetAxis' v1 v2
{-# INLINE joystickGetAxis #-}
joystickGetBall :: MonadIO m => Joystick -> CInt -> Ptr CInt -> Ptr CInt -> m CInt
joystickGetBall v1 v2 v3 v4 = liftIO $ joystickGetBall' v1 v2 v3 v4
{-# INLINE joystickGetBall #-}
joystickGetButton :: MonadIO m => Joystick -> CInt -> m Word8
joystickGetButton v1 v2 = liftIO $ joystickGetButton' v1 v2
{-# INLINE joystickGetButton #-}
joystickGetDeviceGUID :: MonadIO m => CInt -> m JoystickGUID
joystickGetDeviceGUID device_index = liftIO . alloca $ \ptr -> do
joystickGetDeviceGUID' device_index ptr
peek ptr
{-# INLINE joystickGetDeviceGUID #-}
joystickGetGUID :: MonadIO m => Joystick -> m JoystickGUID
joystickGetGUID joystick = liftIO . alloca $ \ptr -> do
joystickGetGUID' joystick ptr
peek ptr
{-# INLINE joystickGetGUID #-}
joystickGetGUIDFromString :: MonadIO m => CString -> m JoystickGUID
joystickGetGUIDFromString pchGUID = liftIO . alloca $ \ptr -> do
joystickGetGUIDFromString' pchGUID ptr
peek ptr
{-# INLINE joystickGetGUIDFromString #-}
joystickGetGUIDString :: MonadIO m => JoystickGUID -> CString -> CInt -> m ()
joystickGetGUIDString guid pszGUID cbGUID = liftIO . alloca $ \ptr -> do
poke ptr guid
joystickGetGUIDString' ptr pszGUID cbGUID
{-# INLINE joystickGetGUIDString #-}
joystickGetHat :: MonadIO m => Joystick -> CInt -> m Word8
joystickGetHat v1 v2 = liftIO $ joystickGetHat' v1 v2
{-# INLINE joystickGetHat #-}
joystickInstanceID :: MonadIO m => Joystick -> m JoystickID
joystickInstanceID v1 = liftIO $ joystickInstanceID' v1
{-# INLINE joystickInstanceID #-}
joystickName :: MonadIO m => Joystick -> m CString
joystickName v1 = liftIO $ joystickName' v1
{-# INLINE joystickName #-}
joystickNameForIndex :: MonadIO m => CInt -> m CString
joystickNameForIndex v1 = liftIO $ joystickNameForIndex' v1
{-# INLINE joystickNameForIndex #-}
joystickNumAxes :: MonadIO m => Joystick -> m CInt
joystickNumAxes v1 = liftIO $ joystickNumAxes' v1
{-# INLINE joystickNumAxes #-}
joystickNumBalls :: MonadIO m => Joystick -> m CInt
joystickNumBalls v1 = liftIO $ joystickNumBalls' v1
{-# INLINE joystickNumBalls #-}
joystickNumButtons :: MonadIO m => Joystick -> m CInt
joystickNumButtons v1 = liftIO $ joystickNumButtons' v1
{-# INLINE joystickNumButtons #-}
joystickNumHats :: MonadIO m => Joystick -> m CInt
joystickNumHats v1 = liftIO $ joystickNumHats' v1
{-# INLINE joystickNumHats #-}
joystickOpen :: MonadIO m => CInt -> m Joystick
joystickOpen v1 = liftIO $ joystickOpen' v1
{-# INLINE joystickOpen #-}
joystickUpdate :: MonadIO m => m ()
joystickUpdate = liftIO joystickUpdate'
{-# INLINE joystickUpdate #-}
numJoysticks :: MonadIO m => m CInt
numJoysticks = liftIO numJoysticks'
{-# INLINE numJoysticks #-}
gameControllerAddMapping :: MonadIO m => CString -> m CInt
gameControllerAddMapping v1 = liftIO $ gameControllerAddMapping' v1
{-# INLINE gameControllerAddMapping #-}
gameControllerAddMappingsFromFile :: MonadIO m => CString -> m CInt
gameControllerAddMappingsFromFile file = liftIO $ do
rw <- withCString "rb" $ rwFromFile file
gameControllerAddMappingsFromRW rw 1
{-# INLINE gameControllerAddMappingsFromFile #-}
gameControllerAddMappingsFromRW :: MonadIO m => Ptr RWops -> CInt -> m CInt
gameControllerAddMappingsFromRW v1 v2 = liftIO $ gameControllerAddMappingsFromRW' v1 v2
{-# INLINE gameControllerAddMappingsFromRW #-}
gameControllerClose :: MonadIO m => GameController -> m ()
gameControllerClose v1 = liftIO $ gameControllerClose' v1
{-# INLINE gameControllerClose #-}
gameControllerEventState :: MonadIO m => CInt -> m CInt
gameControllerEventState v1 = liftIO $ gameControllerEventState' v1
{-# INLINE gameControllerEventState #-}
gameControllerGetAttached :: MonadIO m => GameController -> m Bool
gameControllerGetAttached v1 = liftIO $ gameControllerGetAttached' v1
{-# INLINE gameControllerGetAttached #-}
gameControllerGetAxis :: MonadIO m => GameController -> GameControllerAxis -> m Int16
gameControllerGetAxis v1 v2 = liftIO $ gameControllerGetAxis' v1 v2
{-# INLINE gameControllerGetAxis #-}
gameControllerGetAxisFromString :: MonadIO m => CString -> m GameControllerAxis
gameControllerGetAxisFromString v1 = liftIO $ gameControllerGetAxisFromString' v1
{-# INLINE gameControllerGetAxisFromString #-}
gameControllerGetBindForAxis :: MonadIO m => GameController -> GameControllerAxis -> m GameControllerButtonBind
gameControllerGetBindForAxis gamecontroller axis = liftIO . alloca $ \ptr -> do
gameControllerGetBindForAxis' gamecontroller axis ptr
peek ptr
{-# INLINE gameControllerGetBindForAxis #-}
gameControllerGetBindForButton :: MonadIO m => GameController -> GameControllerButton -> m GameControllerButtonBind
gameControllerGetBindForButton gamecontroller button = liftIO . alloca $ \ptr -> do
gameControllerGetBindForButton' gamecontroller button ptr
peek ptr
{-# INLINE gameControllerGetBindForButton #-}
gameControllerGetButton :: MonadIO m => GameController -> GameControllerButton -> m Word8
gameControllerGetButton v1 v2 = liftIO $ gameControllerGetButton' v1 v2
{-# INLINE gameControllerGetButton #-}
gameControllerGetButtonFromString :: MonadIO m => CString -> m GameControllerButton
gameControllerGetButtonFromString v1 = liftIO $ gameControllerGetButtonFromString' v1
{-# INLINE gameControllerGetButtonFromString #-}
gameControllerGetJoystick :: MonadIO m => GameController -> m Joystick
gameControllerGetJoystick v1 = liftIO $ gameControllerGetJoystick' v1
{-# INLINE gameControllerGetJoystick #-}
gameControllerGetStringForAxis :: MonadIO m => GameControllerAxis -> m CString
gameControllerGetStringForAxis v1 = liftIO $ gameControllerGetStringForAxis' v1
{-# INLINE gameControllerGetStringForAxis #-}
gameControllerGetStringForButton :: MonadIO m => GameControllerButton -> m CString
gameControllerGetStringForButton v1 = liftIO $ gameControllerGetStringForButton' v1
{-# INLINE gameControllerGetStringForButton #-}
gameControllerMapping :: MonadIO m => GameController -> m CString
gameControllerMapping v1 = liftIO $ gameControllerMapping' v1
{-# INLINE gameControllerMapping #-}
gameControllerMappingForGUID :: MonadIO m => JoystickGUID -> m CString
gameControllerMappingForGUID guid = liftIO . alloca $ \ptr -> do
poke ptr guid
gameControllerMappingForGUID' ptr
{-# INLINE gameControllerMappingForGUID #-}
gameControllerName :: MonadIO m => GameController -> m CString
gameControllerName v1 = liftIO $ gameControllerName' v1
{-# INLINE gameControllerName #-}
gameControllerNameForIndex :: MonadIO m => CInt -> m CString
gameControllerNameForIndex v1 = liftIO $ gameControllerNameForIndex' v1
{-# INLINE gameControllerNameForIndex #-}
gameControllerOpen :: MonadIO m => CInt -> m GameController
gameControllerOpen v1 = liftIO $ gameControllerOpen' v1
{-# INLINE gameControllerOpen #-}
gameControllerUpdate :: MonadIO m => m ()
gameControllerUpdate = liftIO gameControllerUpdate'
{-# INLINE gameControllerUpdate #-}
isGameController :: MonadIO m => CInt -> m Bool
isGameController v1 = liftIO $ isGameController' v1
{-# INLINE isGameController #-}
|
polarina/sdl2
|
Graphics/UI/SDL/Event.hs
|
bsd-3-clause
| 27,297
| 0
| 12
| 3,834
| 6,464
| 3,264
| 3,200
| 524
| 1
|
module Parse.Module (moduleDecl, elmModule) where
import Text.Parsec hiding (newline, spaces)
import Parse.Helpers
import Parse.Declaration as Decl
import qualified AST.Declaration
import qualified AST.Module as Module
import qualified AST.Module.Name as ModuleName
import qualified AST.Variable as Var
import AST.V0_16
elmModule :: IParser Module.Module
elmModule =
do preModule <- option [] freshLine
h <- header
decls <- declarations
trailingComments <-
(++)
<$> option [] freshLine
<*> option [] spaces
eof
return $ Module.Module preModule h (decls ++ (map AST.Declaration.BodyComment trailingComments))
declarations :: IParser [AST.Declaration.Decl]
declarations =
(++) <$> ((\x -> [x]) <$> Decl.declaration) -- TODO: can there be comments before this?
<*> (concat <$> many freshDef)
freshDef :: IParser [AST.Declaration.Decl]
freshDef =
commitIf (freshLine >> (letter <|> char '_')) $
do comments <- freshLine
decl <- Decl.declaration
return $ (map AST.Declaration.BodyComment comments) ++ [decl]
header :: IParser Module.Header
header =
do ((names, exports, postExports), preDocsComments) <-
option
((Commented [] ["Main"] [], Var.OpenListing (Commented [] () []), []), [])
((,) <$> moduleDecl <*> freshLine)
(docs, postDocsComments) <-
choice
[ (,) <$> addLocation (Just <$> docComment) <*> freshLine
, (,) <$> addLocation (return Nothing) <*> return []
]
imports' <- imports
return (Module.Header names docs exports postExports ((fmap Module.ImportComment (preDocsComments ++ postDocsComments)) ++ imports'))
moduleDecl :: IParser (Commented ModuleName.Raw, Var.Listing Var.Value, Comments)
moduleDecl =
expecting "a module declaration" $
do try (reserved "module")
(_, preName) <- whitespace
names <- dotSep1 capVar <?> "the name of this module"
(_, postName1) <- whitespace
(postName2, exports) <- option ([], Var.OpenListing (Commented [] () [])) (listing value)
(_, preWhere) <- whitespace
reserved "where"
return (Commented preName names (postName1 ++ postName2), exports, preWhere)
imports :: IParser [Module.UserImport]
imports =
concat <$> many ((:) <$> import' <*> (fmap Module.ImportComment <$> freshLine))
import' :: IParser Module.UserImport
import' =
Module.UserImport <$> (
expecting "an import" $
addLocation $
do try (reserved "import")
(_, preName) <- whitespace
names <- dotSep1 capVar
method' <- method (ModuleName.toString names)
return ((,) preName names, method')
)
where
method :: String -> IParser Module.ImportMethod
method originalName =
Module.ImportMethod
<$> option Nothing (Just <$> as' originalName)
<*> option ([], ([], Var.ClosedListing)) exposing
as' :: String -> IParser (Comments, PreCommented String)
as' moduleName =
do (_, preAs) <- try (whitespace <* reserved "as")
(_, postAs) <- whitespace
(,) preAs <$> (,) postAs <$> capVar <?> ("an alias for module `" ++ moduleName ++ "`")
exposing :: IParser (Comments, PreCommented (Var.Listing Var.Value))
exposing =
do (_, preExposing) <- try (whitespace <* reserved "exposing")
(_, postExposing) <- whitespace
(postExposing2, listing') <- listing value
return (preExposing, (postExposing ++ postExposing2, listing'))
listing :: IParser a -> IParser (Comments, Var.Listing a)
listing item =
expecting "a listing of values and types to expose, like (..)" $
do (_, preParen) <- try (whitespace <* char '(')
(_, pre) <- whitespace
listing <-
choice
[ (\_ pre post -> Var.OpenListing (Commented pre () post)) <$> string ".."
, (\x pre post -> Var.ExplicitListing (x pre post)) <$> commaSep1' item
]
(_, post) <- whitespace
char ')'
return $ (preParen, listing pre post)
value :: IParser Var.Value
value =
val <|> tipe <?> "a value or type to expose"
where
val =
Var.Value <$> ((Var.VarRef <$> lowVar) <|> parens' symOp)
tipe =
do name <- capVar
maybeCtors <- optionMaybe (listing capVar)
case maybeCtors of
Nothing -> return (Var.Alias name)
Just (pre, ctors) -> return (Var.Union (name, pre) ctors)
|
fredcy/elm-format
|
parser/src/Parse/Module.hs
|
bsd-3-clause
| 4,463
| 0
| 17
| 1,123
| 1,543
| 799
| 744
| 105
| 2
|
{-# LANGUAGE FlexibleContexts #-}
-----------------------------------------------------------------------------
-- |
-- Module : Xmobar.Main
-- Copyright : (c) Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Jose A. Ortega Ruiz <jao@gnu.org>
-- Stability : unstable
-- Portability : unportable
--
-- The main module of Xmobar, a text based status bar
--
-----------------------------------------------------------------------------
module Main ( -- * Main Stuff
-- $main
main
, readConfig
, readDefaultConfig
) where
import Xmobar
import Parsers
import Config
import XUtil
import Data.List (intercalate)
import qualified Data.Map as Map
import Paths_xmobar (version)
import Data.Version (showVersion)
import Graphics.X11.Xlib
import System.Console.GetOpt
import System.Directory (getHomeDirectory)
import System.Exit
import System.Environment
import System.FilePath ((</>))
import System.Posix.Files
import Control.Monad (unless)
import Signal (setupSignalHandler)
-- $main
-- | The main entry point
main :: IO ()
main = do
initThreads
d <- openDisplay ""
args <- getArgs
(o,file) <- getOpts args
(c,defaultings) <- case file of
[cfgfile] -> readConfig cfgfile
_ -> readDefaultConfig
unless (null defaultings) $ putStrLn $
"Fields missing from config defaulted: " ++ intercalate "," defaultings
conf <- doOpts c o
fs <- initFont d (font conf)
cls <- mapM (parseTemplate conf) (splitTemplate conf)
sig <- setupSignalHandler
vars <- mapM (mapM $ startCommand sig) cls
(r,w) <- createWin d fs conf
let ic = Map.empty
startLoop (XConf d r w fs ic conf) sig vars
-- | Splits the template in its parts
splitTemplate :: Config -> [String]
splitTemplate conf =
case break (==l) t of
(le,_:re) -> case break (==r) re of
(ce,_:ri) -> [le, ce, ri]
_ -> def
_ -> def
where [l, r] = alignSep
(if length (alignSep conf) == 2 then conf else defaultConfig)
t = template conf
def = [t, "", ""]
-- | Reads the configuration files or quits with an error
readConfig :: FilePath -> IO (Config,[String])
readConfig f = do
file <- io $ fileExist f
s <- io $ if file then readFileSafe f else error $
f ++ ": file not found!\n" ++ usage
either (\err -> error $ f ++
": configuration file contains errors at:\n" ++ show err)
return $ parseConfig s
xdgConfigDir :: IO String
xdgConfigDir = do env <- getEnvironment
case lookup "XDG_CONFIG_HOME" env of
Just val -> return val
Nothing -> getHomeDirectory >>= return . (</> ".config")
xmobarConfigDir :: IO FilePath
xmobarConfigDir = xdgConfigDir >>= return . (</> "xmobar")
getXdgConfigFile :: IO FilePath
getXdgConfigFile = xmobarConfigDir >>= return . (</> "xmobarrc")
-- | Read default configuration file or load the default config
readDefaultConfig :: IO (Config,[String])
readDefaultConfig = do
xdgConfigFile <- getXdgConfigFile
xdgConfigFileExists <- io $ fileExist xdgConfigFile
home <- io $ getEnv "HOME"
let defaultConfigFile = home ++ "/.xmobarrc"
defaultConfigFileExists <- io $ fileExist defaultConfigFile
if xdgConfigFileExists
then readConfig xdgConfigFile
else if defaultConfigFileExists
then readConfig defaultConfigFile
else return (defaultConfig,[])
data Opts = Help
| Version
| Font String
| BgColor String
| FgColor String
| T
| B
| D
| AlignSep String
| Commands String
| AddCommand String
| SepChar String
| Template String
| OnScr String
deriving Show
options :: [OptDescr Opts]
options =
[ Option "h?" ["help"] (NoArg Help) "This help"
, Option "V" ["version"] (NoArg Version) "Show version information"
, Option "f" ["font"] (ReqArg Font "font name") "The font name"
, Option "B" ["bgcolor"] (ReqArg BgColor "bg color" )
"The background color. Default black"
, Option "F" ["fgcolor"] (ReqArg FgColor "fg color")
"The foreground color. Default grey"
, Option "o" ["top"] (NoArg T) "Place xmobar at the top of the screen"
, Option "b" ["bottom"] (NoArg B)
"Place xmobar at the bottom of the screen"
, Option "d" ["dock"] (NoArg D)
"Don't override redirect from WM and function as a dock"
, Option "a" ["alignsep"] (ReqArg AlignSep "alignsep")
"Separators for left, center and right text\nalignment. Default: '}{'"
, Option "s" ["sepchar"] (ReqArg SepChar "char")
("The character used to separate commands in" ++
"\nthe output template. Default '%'")
, Option "t" ["template"] (ReqArg Template "template")
"The output template"
, Option "c" ["commands"] (ReqArg Commands "commands")
"The list of commands to be executed"
, Option "C" ["add-command"] (ReqArg AddCommand "command")
"Add to the list of commands to be executed"
, Option "x" ["screen"] (ReqArg OnScr "screen")
"On which X screen number to start"
]
getOpts :: [String] -> IO ([Opts], [String])
getOpts argv =
case getOpt Permute options argv of
(o,n,[]) -> return (o,n)
(_,_,errs) -> error (concat errs ++ usage)
usage :: String
usage = usageInfo header options ++ footer
where header = "Usage: xmobar [OPTION...] [FILE]\nOptions:"
footer = "\nMail bug reports and suggestions to " ++ mail ++ "\n"
info :: String
info = "xmobar " ++ showVersion version
++ "\n (C) 2007 - 2010 Andrea Rossato "
++ "\n (C) 2010 - 2014 Jose A Ortega Ruiz\n "
++ mail ++ "\n" ++ license
mail :: String
mail = "<xmobar@projects.haskell.org>"
license :: String
license = "\nThis program is distributed in the hope that it will be useful," ++
"\nbut WITHOUT ANY WARRANTY; without even the implied warranty of" ++
"\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." ++
"\nSee the License for more details."
doOpts :: Config -> [Opts] -> IO Config
doOpts conf [] =
return (conf {lowerOnStart = lowerOnStart conf && overrideRedirect conf})
doOpts conf (o:oo) =
case o of
Help -> putStr usage >> exitSuccess
Version -> putStrLn info >> exitSuccess
Font s -> doOpts' (conf {font = s})
BgColor s -> doOpts' (conf {bgColor = s})
FgColor s -> doOpts' (conf {fgColor = s})
T -> doOpts' (conf {position = Top})
B -> doOpts' (conf {position = Bottom})
D -> doOpts' (conf {overrideRedirect = False})
AlignSep s -> doOpts' (conf {alignSep = s})
SepChar s -> doOpts' (conf {sepChar = s})
Template s -> doOpts' (conf {template = s})
OnScr n -> doOpts' (conf {position = OnScreen (read n) $ position conf})
Commands s -> case readCom 'c' s of
Right x -> doOpts' (conf {commands = x})
Left e -> putStr (e ++ usage) >> exitWith (ExitFailure 1)
AddCommand s -> case readCom 'C' s of
Right x -> doOpts' (conf {commands = commands conf ++ x})
Left e -> putStr (e ++ usage) >> exitWith (ExitFailure 1)
where readCom c str =
case readStr str of
[x] -> Right x
_ -> Left ("xmobar: cannot read list of commands " ++
"specified with the -" ++ c:" option\n")
readStr str = [x | (x,t) <- reads str, ("","") <- lex t]
doOpts' opts = doOpts opts oo
|
apoikos/pkg-xmobar
|
src/Main.hs
|
bsd-3-clause
| 7,677
| 0
| 16
| 2,116
| 2,131
| 1,123
| 1,008
| 174
| 17
|
{-# LANGUAGE RankNTypes, ScopedTypeVariables, GADTs #-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- | 'Applicative' programs over an @operational@-style instruction
-- set, implemented on top of the 'Ap' free 'Applicative' type.
module Control.Applicative.Operational
( module Control.Operational.Class
, ProgramAp(..)
, interpretAp
, fromProgramAp
, ProgramViewAp(..)
, viewAp
, compileAp
, foldProgramViewAp
, instructions
, AnyInstr(..)
) where
import Control.Applicative
import Control.Applicative.Free (Ap, runAp, liftAp)
import qualified Control.Applicative.Free as Free
import Control.Operational.Class
import Control.Operational.Instruction
import Data.Functor.Coyoneda
-- | An 'Applicative' program over instruction set @instr@. This is
-- modeled after the 'Program' type from @operational@
-- (<http://hackage.haskell.org/package/operational>), but this one is
-- an 'Applicative', not a 'Monad'. This makes it less powerful, but
-- in exchange for the sacrificed power 'ProgramAp' is suceptible to
-- much stronger static analysis.
--
-- For examples of this (though applied to free applicatives), see:
--
-- * <http://gergo.erdi.hu/blog/2012-12-01-static_analysis_with_applicatives/>
--
-- * <http://paolocapriotti.com/blog/2013/04/03/free-applicative-functors/>
--
-- See also the examples in "Control.Alternative.Operational".
newtype ProgramAp instr a =
ProgramAp { -- | Interpret a 'ProgramAp' as a free applicative ('Ap').
toAp :: Ap (Coyoneda instr) a
} deriving (Functor, Applicative)
instance Operational instr (ProgramAp instr) where
singleton = ProgramAp . liftAp . liftInstr
-- | Evaluate a 'ProgramAp' by interpreting each instruction as an
-- 'Applicative' action. Example @Reader@ implementation:
--
-- > type Reader r a = ProgramAp (ReaderI r) a
-- >
-- > data ReaderI r a where
-- > Ask :: ReaderI r r
-- >
-- > ask :: Reader r r
-- > ask = singleton Ask
-- >
-- > runReader :: forall r a. Reader r a -> r -> a
-- > runReader = interpretAp evalI
-- > where evalI :: forall a. ReaderI r a -> r -> a
-- > evalI Ask = id
interpretAp :: forall instr f a.
Applicative f =>
(forall x. instr x -> f x)
-> ProgramAp instr a
-> f a
interpretAp evalI = runAp (liftEvalI evalI) . toAp
-- | Lift a 'ProgramAp' into any other 'Operational' program type that
-- is at least as strong as 'Applicative'; e.g., lift an applicative
-- program into a monadic one. Note that not all applicatives are
-- monads, so a lifted program may \"lose\" some of the
-- interpretations that the original could be given.
fromProgramAp
:: (Operational instr f, Applicative f) => ProgramAp instr a -> f a
fromProgramAp = interpretAp singleton
-- | A friendly concrete tree view type for 'ProgramAp'. Unlike the
-- ':>>=' constructor in the 'ProgramView' type of
-- "Control.Monad.Operational", whose second data member is a function
-- that consumes an instruction result to generate the rest of the
-- program, our ':<**>' constructor exposes the rest of program
-- immediately.
--
-- Note that the 'ProgramViewAp' type normalizes the program into a
-- different ordering and bracketing than the applicative '<*>'
-- operator does. The ':<**>' constructor is an analogue of @'<**>'
-- :: Applicative f => f a -> f (a -> b) -> f b@ from
-- "Control.Applicative". The normalization means that you get a
-- list-like structure with instructions as the elements (in the same
-- order as their effects) and 'Pure' as the terminator.
--
-- A static analysis example, based on Capriotti and Kaposi (2013,
-- <http://paolocapriotti.com/blog/2013/04/03/free-applicative-functors/>):
--
-- > {-# LANGUAGE GADTs, RankNTypes, ScopedTypeVariables #-}
-- >
-- > import Control.Operational.Applicative
-- >
-- > data FileSystemI a where
-- > Read :: FilePath -> FileSystemI String
-- > Write :: FilePath -> String -> FileSystemI ()
-- >
-- > -- | Count how many file accesses a program does.
-- > count :: ProgramAp FileSystemI a -> Int
-- > count = count' . viewAp
-- > where count' :: forall x. ProgramViewAp FileSystemI x -> Int
-- > count' (Pure _) = 0
-- > count' (_ :<**> k) = succ (count' k)
--
-- Or actually, just this:
--
-- > count :: ProgramAp FileSystemI a -> Int
-- > count = length . instructions
--
-- You can also use the 'ProgramViewAp' to interpret the program, in
-- the style of the @operational@ package. Example implementation of
-- a simple terminal language in this style:
--
-- > data TermI a where
-- > Say :: String -> TermI ()
-- > Get :: TermI String
-- >
-- > say :: String -> ProgramAp TermI ()
-- > say = singleton . Say
-- >
-- > get :: ProgramAp TermI String
-- > get = singleton Get
-- >
-- > prompt :: String -> ProgramAp TermI String
-- > prompt str = say str *> get
-- >
-- > runTerm :: ProgramAp TermI a -> IO a
-- > runTerm = eval . viewAp
-- > where eval :: forall x. ProgramViewAp TermI x -> IO x
-- > eval (Pure a) = pure a
-- > eval (Say str :<**> k) = putStr str <**> eval k
-- > eval (Get :<**> k) = getLine <**> eval k
-- >
-- > example :: ProgramAp TermI (String, String)
-- > example = (,) <$> prompt "First question: " <*> prompt "Second question: "
-- >
-- > -- example = Say "First question: " :<**> (Get :<**> (Say "Second question: " :<**> (Get :<**> Pure (\_ a _ b -> (a, b)))))
--
-- But as a general rule, 'interpretAp' makes for shorter, less
-- repetitive, fooler-proof interpreters:
--
-- > runTerm :: ProgramAp TermI a -> IO a
-- > runTerm = interpretAp evalI
-- > where evalI :: forall x. TermI x -> IO x
-- > evalI (Say str) = putStr str
-- > evalI Get = getLine
--
data ProgramViewAp instr a where
Pure :: a -> ProgramViewAp instr a
(:<**>) :: instr a
-> ProgramViewAp instr (a -> b)
-> ProgramViewAp instr b
-- this is the same fixity as '<**>'; dunno why it's not infixr
infixl 4 :<**>
-- | Materialize a 'ProgramAp' as a concrete tree. Note that
-- 'ProgramAp''s 'Functor' and 'Applicative' instances normalize their
-- programs, so the view term may not look like the code that created
-- it. Instructions however will appear in the order that their
-- effects should happen, from left to right.
viewAp :: ProgramAp instr a -> ProgramViewAp instr a
viewAp = viewAp' . toAp
viewAp' :: Ap (Coyoneda instr) a -> ProgramViewAp instr a
viewAp' (Free.Pure a) = Pure a
viewAp' (Free.Ap (Coyoneda f i) next) = i :<**> viewAp' (fmap (.f) next)
-- | Compile a 'ProgramViewAp' back into a 'ProgramAp'.
compileAp :: ProgramViewAp instr a -> ProgramAp instr a
compileAp (Pure f) = pure f
compileAp (instr :<**> k) = singleton instr <**> compileAp k
foldProgramViewAp :: (forall x. instr x -> r -> r)
-> r
-> ProgramViewAp instr a
-> r
foldProgramViewAp k z (Pure _) = z
foldProgramViewAp k z (i :<**> is) = k i (foldProgramViewAp k z is)
instructions :: ProgramAp instr a -> [AnyInstr instr]
instructions = foldProgramViewAp (\i -> (AnyInstr i:)) [] . viewAp
data AnyInstr instr = forall a. AnyInstr (instr a)
|
sacundim/free-operational
|
Control/Applicative/Operational.hs
|
bsd-3-clause
| 7,317
| 0
| 11
| 1,600
| 810
| 495
| 315
| -1
| -1
|
{-# LANGUAGE NoMonomorphismRestriction #-}
module Language.PiEtaEpsilon.Parser.Type where
import Language.PiEtaEpsilon.Token
import Language.PiEtaEpsilon.Syntax
import Text.Parsec
import Text.Parsec.Expr
---------------------------------------------Type----------------------------------------------
parseType = runParser pType () ""
pZero = do
spaces
char '0'
spaces
return Zero
pOne = do
spaces
char '1'
spaces
return One
pType = spaces >> buildExpressionParser table pTypeTerm
<?> "type"
pTypeTerm = parens pType
<|> pZero
<|> pOne
<?> "simple type"
table = [
[prefix "-" Negative, prefix "/" Reciprocal ],
[binary "*" Product AssocLeft],
[binary "+" Sum AssocLeft]
]
binary name fun assoc = Infix (do{ reservedOp name; return fun }) assoc
prefix name fun = Prefix (do{ reservedOp name; return fun })
|
dmwit/pi-eta-epsilon
|
src/Language/PiEtaEpsilon/Parser/Type.hs
|
bsd-3-clause
| 987
| 0
| 9
| 286
| 247
| 126
| 121
| 29
| 1
|
{-|
Module : Idris.Elab.Clause
Description : Code to elaborate clauses.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE PatternGuards #-}
module Idris.Elab.Clause where
import Idris.AbsSyntax
import Idris.ASTUtils
import Idris.Core.CaseTree
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Evaluate
import Idris.Core.Execute
import Idris.Core.TT
import Idris.Core.Typecheck
import Idris.Core.WHNF
import Idris.Coverage
import Idris.DataOpts
import Idris.DeepSeq
import Idris.Delaborate
import Idris.Docstrings hiding (Unchecked)
import Idris.DSL
import Idris.Elab.AsPat
import Idris.Elab.Term
import Idris.Elab.Transform
import Idris.Elab.Type
import Idris.Elab.Utils
import Idris.Error
import Idris.Imports
import Idris.Inliner
import Idris.Output (iRenderResult, iWarn, iputStrLn, pshow, sendHighlighting)
import Idris.PartialEval
import Idris.Primitives
import Idris.Providers
import Idris.Termination
import Idris.Transforms
import IRTS.Lang
import Util.Pretty hiding ((<$>))
import Util.Pretty (pretty, text)
import Prelude hiding (id, (.))
import Control.Applicative hiding (Const)
import Control.Category
import Control.DeepSeq
import Control.Monad
import qualified Control.Monad.State.Lazy as LState
import Control.Monad.State.Strict as State
import Data.Char (isLetter, toLower)
import Data.List
import Data.List.Split (splitOn)
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Word
import Debug.Trace
import Numeric
-- | Elaborate a collection of left-hand and right-hand pairs - that is, a
-- top-level definition.
elabClauses :: ElabInfo -> FC -> FnOpts -> Name -> [PClause] -> Idris ()
elabClauses info' fc opts n_in cs =
do let n = liftname info n_in
info = info' { elabFC = Just fc }
ctxt <- getContext
ist <- getIState
optimise <- getOptimise
let petrans = PETransform `elem` optimise
inacc <- map fst <$> fgetState (opt_inaccessible . ist_optimisation n)
-- Check n actually exists, with no definition yet
let tys = lookupTy n ctxt
let reflect = Reflection `elem` opts
when (reflect && FCReflection `notElem` idris_language_extensions ist) $
ierror $ At fc (Msg "You must turn on the FirstClassReflection extension to use %reflection")
checkUndefined n ctxt
unless (length tys > 1) $ do
fty <- case tys of
[] -> -- TODO: turn into a CAF if there's no arguments
-- question: CAFs in where blocks?
tclift $ tfail $ At fc (NoTypeDecl n)
[ty] -> return ty
let atys_in = map snd (getArgTys (normalise ctxt [] fty))
let atys = map (\x -> (x, isCanonical x ctxt)) atys_in
cs_elab <- mapM (elabClause info opts)
(zip [0..] cs)
ctxt <- getContext
-- pats_raw is the basic type checked version, no PE or forcing
let optinfo = idris_optimisation ist
let (pats_in, cs_full) = unzip cs_elab
let pats_raw = map (simple_lhs ctxt) pats_in
-- We'll apply forcing to the left hand side here, so that we don't
-- do any unnecessary case splits
let pats_forced = map (force_lhs optinfo) pats_raw
logElab 3 $ "Elaborated patterns:\n" ++ show pats_raw
logElab 5 $ "Forced patterns:\n" ++ show pats_forced
solveDeferred fc n
-- just ensure that the structure exists
fmodifyState (ist_optimisation n) id
addIBC (IBCOpt n)
ist <- getIState
ctxt <- getContext
-- Don't apply rules if this is a partial evaluation definition,
-- or we'll make something that just runs itself!
let tpats = case specNames opts of
Nothing -> transformPats ist pats_in
_ -> pats_in
-- If the definition is specialisable, this reduces the
-- RHS
pe_tm <- doPartialEval ist tpats
let pats_pe = if petrans
then map (force_lhs optinfo . simple_lhs ctxt) pe_tm
else pats_forced
let tcase = opt_typecase (idris_options ist)
-- Look for 'static' names and generate new specialised
-- definitions for them, as well as generating rewrite rules
-- for partially evaluated definitions
newrules <- if petrans
then mapM (\ e -> case e of
Left _ -> return []
Right (l, r) -> elabPE info fc n r) pats_pe
else return []
-- Redo transforms with the newly generated transformations, so
-- that the specialised application we've just made gets
-- used in place of the general one
ist <- getIState
let pats_transformed = if petrans
then transformPats ist pats_pe
else pats_pe
-- Summary of what's about to happen: Definitions go:
--
-- pats_in -> pats -> pdef -> pdef'
-- addCaseDef builds case trees from <pdef> and <pdef'>
-- pdef is the compile-time pattern definition, after forcing
-- optimisation applied to LHS
let pdef = map (\(ns, lhs, rhs) -> (map fst ns, lhs, rhs)) $
map debind pats_forced
-- pdef_cov is the pattern definition without forcing, which
-- we feed to the coverage checker (we need to know what the
-- programmer wrote before forcing erasure)
let pdef_cov
= map (\(ns, lhs, rhs) -> (map fst ns, lhs, rhs)) $
map debind pats_raw
-- pdef_pe is the one which will get further optimised
-- for run-time, with no forcing optimisation of the LHS because
-- the affects erasure. Also, it's partially evaluated
let pdef_pe = map debind pats_transformed
logElab 5 $ "Initial typechecked patterns:\n" ++ show pats_raw
logElab 5 $ "Initial typechecked pattern def:\n" ++ show pdef
-- NOTE: Need to store original definition so that proofs which
-- rely on its structure aren't affected by any changes to the
-- inliner. Just use the inlined version to generate pdef' and to
-- help with later inlinings.
ist <- getIState
let pdef_inl = inlineDef ist pdef
numArgs <- tclift $ sameLength pdef
case specNames opts of
Just _ ->
do logElab 3 $ "Partially evaluated:\n" ++ show pats_pe
_ -> return ()
logElab 3 $ "Transformed:\n" ++ show pats_transformed
erInfo <- getErasureInfo <$> getIState
tree@(CaseDef scargs sc _) <- tclift $
simpleCase tcase (UnmatchedCase "Error") reflect CompileTime fc inacc atys pdef erInfo
cov <- coverage
pmissing <-
if cov && not (hasDefault pats_raw)
then do -- Generate clauses from the given possible cases
missing <- genClauses fc n
(map (\ (ns,tm,_) -> (ns, tm)) pdef)
cs_full
-- missing <- genMissing n scargs sc
missing' <- checkPossibles info fc True n missing
-- Filter out the ones which match one of the
-- given cases (including impossible ones)
let clhs = map getLHS pdef
logElab 2 $ "Must be unreachable (" ++ show (length missing') ++ "):\n" ++
showSep "\n" (map showTmImpls missing') ++
"\nAgainst: " ++
showSep "\n" (map (\t -> showTmImpls (delab ist t)) (map getLHS pdef))
-- filter out anything in missing' which is
-- matched by any of clhs. This might happen since
-- unification may force a variable to take a
-- particular form, rather than force a case
-- to be impossible.
return missing' -- (filter (noMatch ist clhs) missing')
else return []
let pcover = null pmissing
-- pdef' is the version that gets compiled for run-time,
-- so we start from the partially evaluated version
pdef_in' <- applyOpts $ map (\(ns, lhs, rhs) -> (map fst ns, lhs, rhs)) pdef_pe
ctxt <- getContext
let pdef' = map (simple_rt ctxt) pdef_in'
logElab 5 $ "After data structure transformations:\n" ++ show pdef'
ist <- getIState
let tot | pcover = Unchecked -- finish later
| AssertTotal `elem` opts = Total []
| PEGenerated `elem` opts = Generated
| otherwise = Partial NotCovering -- already know it's not total
case tree of
CaseDef _ _ [] -> return ()
CaseDef _ _ xs -> mapM_ (\x ->
iputStrLn $ show fc ++
":warning - Unreachable case: " ++
show (delab ist x)) xs
let knowncovering = (pcover && cov) || AssertTotal `elem` opts
let defaultcase = if knowncovering
then STerm Erased
else UnmatchedCase $ "*** " ++
show fc ++
":unmatched case in " ++ show n ++
" ***"
tree' <- tclift $ simpleCase tcase defaultcase reflect
RunTime fc inacc atys pdef' erInfo
logElab 3 $ "Unoptimised " ++ show n ++ ": " ++ show tree
logElab 3 $ "Optimised: " ++ show tree'
ctxt <- getContext
ist <- getIState
let opt = idris_optimisation ist
putIState (ist { idris_patdefs = addDef n (force pdef_pe, force pmissing)
(idris_patdefs ist) })
let caseInfo = CaseInfo (inlinable opts) (inlinable opts) (dictionary opts)
case lookupTyExact n ctxt of
Just ty ->
do ctxt' <- do ctxt <- getContext
tclift $
addCasedef n erInfo caseInfo
tcase defaultcase
reflect
(AssertTotal `elem` opts)
atys
inacc
pats_forced
pdef
pdef' ty
ctxt
setContext ctxt'
addIBC (IBCDef n)
addDefinedName n
setTotality n tot
when (not reflect && PEGenerated `notElem` opts) $
do totcheck (fc, n)
defer_totcheck (fc, n)
when (tot /= Unchecked) $ addIBC (IBCTotal n tot)
i <- getIState
ctxt <- getContext
case lookupDef n ctxt of
(CaseOp _ _ _ _ _ cd : _) ->
let (scargs, sc) = cases_compiletime cd in
do let calls = map fst $ findCalls sc scargs
-- let scg = buildSCG i sc scargs
-- add SCG later, when checking totality
logElab 2 $ "Called names: " ++ show calls
-- if the definition is public, make sure
-- it only uses public names
nvis <- getFromHideList n
case nvis of
Just Public -> mapM_ (checkVisibility fc n Public Public) calls
_ -> return ()
addCalls n calls
let rig = if linearArg (whnfArgs ctxt [] ty)
then Rig1
else RigW
updateContext (setRigCount n (minRig ctxt rig calls))
addIBC (IBCCG n)
_ -> return ()
return ()
-- addIBC (IBCTotal n tot)
_ -> return ()
-- Check it's covering, if 'covering' option is used. Chase
-- all called functions, and fail if any of them are also
-- 'Partial NotCovering'
when (CoveringFn `elem` opts) $ checkAllCovering fc [] n n
-- Add the 'AllGuarded' flag if it's guaranteed that every
-- 'Inf' argument will be guarded by constructors in the result
-- (allows productivity check to go under this function)
checkIfGuarded n
-- If this has %static arguments, cache the names of functions
-- it calls for partial evaluation later
ist <- getIState
let statics = case lookupCtxtExact n (idris_statics ist) of
Just ns -> ns
Nothing -> []
when (or statics) $ do getAllNames n
return ()
where
noMatch i cs tm = all (\x -> case trim_matchClause i (delab' i x True True) tm of
Right _ -> False
Left miss -> True) cs
where
trim_matchClause i (PApp fcl fl ls) (PApp fcr fr rs)
= let args = min (length ls) (length rs) in
matchClause i (PApp fcl fl (take args ls))
(PApp fcr fr (take args rs))
checkUndefined n ctxt = case lookupDef n ctxt of
[] -> return ()
[TyDecl _ _] -> return ()
_ -> tclift $ tfail (At fc (AlreadyDefined n))
debind (Right (x, y)) = let (vs, x') = depat [] x
(_, y') = depat [] y in
(vs, x', y')
debind (Left x) = let (vs, x') = depat [] x in
(vs, x', Impossible)
depat acc (Bind n (PVar rig t) sc) = depat ((n, t) : acc) (instantiate (P Bound n t) sc)
depat acc x = (acc, x)
getPVs (Bind x (PVar rig _) tm) = let (vs, tm') = getPVs tm
in (x:vs, tm')
getPVs tm = ([], tm)
isPatVar vs (P Bound n _) = n `elem` vs
isPatVar _ _ = False
hasDefault cs | (Right (lhs, rhs) : _) <- reverse cs
, (pvs, tm) <- getPVs (explicitNames lhs)
, (f, args) <- unApply tm = all (isPatVar pvs) args
hasDefault _ = False
getLHS (_, l, _) = l
-- Simplify the left hand side of a definition, to remove any lets
-- that may have arisen during elaboration
simple_lhs ctxt (Right (x, y))
= Right (Idris.Core.Evaluate.simplify ctxt [] x, y)
simple_lhs ctxt t = t
force_lhs opts (Right (x, y)) = Right (forceWith opts x, y)
force_lhs opts t = t
simple_rt ctxt (p, x, y) = (p, x, force (uniqueBinders p
(rt_simplify ctxt [] y)))
specNames [] = Nothing
specNames (Specialise ns : _) = Just ns
specNames (_ : xs) = specNames xs
sameLength ((_, x, _) : xs)
= do l <- sameLength xs
let (f, as) = unApply x
if (null xs || l == length as) then return (length as)
else tfail (At fc (Msg "Clauses have differing numbers of arguments "))
sameLength [] = return 0
-- Partially evaluate, if the definition is marked as specialisable
doPartialEval ist pats =
case specNames opts of
Nothing -> return pats
Just ns -> case partial_eval (tt_ctxt ist) ns pats of
Just t -> return t
Nothing -> ierror (At fc (Msg "No specialisation achieved"))
minRig :: Context -> RigCount -> [Name] -> RigCount
minRig c minr [] = minr
minRig c minr (r : rs) = case lookupRigCountExact r c of
Nothing -> minRig c minr rs
Just rc -> minRig c (min minr rc) rs
forceWith :: Ctxt OptInfo -> Term -> Term
forceWith opts lhs = -- trace (show lhs ++ "\n==>\n" ++ show (force lhs) ++ "\n----") $
force lhs
where
-- If there's forced arguments, erase them
force ap@(App _ _ _)
| (fn@(P _ c _), args) <- unApply ap,
Just copt <- lookupCtxtExact c opts
= let args' = eraseArg 0 (forceable copt) args in
mkApp fn (map force args')
force (App t f a)
= App t (force f) (force a)
-- We might have pat bindings, so go under them
force (Bind n b sc) = Bind n b (force sc)
-- Everything else, leave it alone
force t = t
eraseArg i fs (n : ns) | i `elem` fs = Erased : eraseArg (i + 1) fs ns
| otherwise = n : eraseArg (i + 1) fs ns
eraseArg i _ [] = []
-- | Find 'static' applications in a term and partially evaluate them.
-- Return any new transformation rules
elabPE :: ElabInfo -> FC -> Name -> Term -> Idris [(Term, Term)]
-- Don't go deeper than 5 nested partially evaluated definitions in one go
-- (make this configurable? It's a good limit for most cases, certainly for
-- interfaces and polymorphic definitions, but maybe not for DSLs and
-- interpreters in complicated cases.
-- Possibly only worry about the limit if we've specialised the same function
-- a number of times in one go.)
elabPE info fc caller r | pe_depth info > 5 = return []
elabPE info fc caller r =
do ist <- getIState
let sa = filter (\ap -> fst ap /= caller) $ getSpecApps ist [] r
rules <- mapM mkSpecialised sa
return $ concat rules
where
-- Make a specialised version of the application, and
-- add a PTerm level transformation rule, which is basically the
-- new definition in reverse (before specialising it).
-- RHS => LHS where implicit arguments are left blank in the
-- transformation.
-- Transformation rules are applied after every PClause elaboration
mkSpecialised :: (Name, [(PEArgType, Term)]) -> Idris [(Term, Term)]
mkSpecialised specapp_in = do
ist <- getIState
ctxt <- getContext
(specTy, specapp) <- getSpecTy ist specapp_in
let (n, newnm, specdecl) = getSpecClause ist specapp specTy
let lhs = pe_app specdecl
let rhs = pe_def specdecl
let undef = case lookupDefExact newnm ctxt of
Nothing -> True
_ -> False
logElab 5 $ show (newnm, undef, map (concreteArg ist) (snd specapp))
idrisCatch
(if (undef && all (concreteArg ist) (snd specapp)) then do
cgns <- getAllNames n
-- on the RHS of the new definition, we should reduce
-- everything that's not itself static (because we'll
-- want to be a PE version of those next)
let cgns' = filter (\x -> x /= n &&
notStatic ist x) cgns
-- set small reduction limit on partial/productive things
let maxred = case lookupTotal n ctxt of
[Total _] -> 65536
[Productive] -> 16
_ -> 1
let specnames = mapMaybe (specName (pe_simple specdecl))
(snd specapp)
descs <- mapM getStaticsFrom (map fst specnames)
let opts = [Specialise ((if pe_simple specdecl
then map (\x -> (x, Nothing)) cgns'
else []) ++
(n, Just maxred) : specnames ++
concat descs)]
logElab 3 $ "Specialising application: " ++ show specapp
++ "\n in \n" ++ show caller ++
"\n with \n" ++ show opts
++ "\nCalling: " ++ show cgns
logElab 3 $ "New name: " ++ show newnm
logElab 3 $ "PE definition type : " ++ (show specTy)
++ "\n" ++ show opts
logElab 2 $ "PE definition " ++ show newnm ++ ":\n" ++
showSep "\n"
(map (\ (lhs, rhs) ->
(showTmImpls lhs ++ " = " ++
showTmImpls rhs)) (pe_clauses specdecl))
logElab 5 $ show n ++ " transformation rule: " ++
showTmImpls rhs ++ " ==> " ++ showTmImpls lhs
elabType info defaultSyntax emptyDocstring [] fc opts newnm NoFC specTy
let def = map (\(lhs, rhs) ->
let lhs' = mapPT hiddenToPH $ stripUnmatchable ist lhs in
PClause fc newnm lhs' [] rhs [])
(pe_clauses specdecl)
trans <- elabTransform info fc False rhs lhs
elabClauses (info {pe_depth = pe_depth info + 1}) fc
(PEGenerated:opts) newnm def
return [trans]
else return [])
-- if it doesn't work, just don't specialise. Could happen for lots
-- of valid reasons (e.g. local variables in scope which can't be
-- lifted out).
(\e -> do logElab 5 $ "Couldn't specialise: " ++ (pshow ist e)
return [])
hiddenToPH (PHidden _) = Placeholder
hiddenToPH x = x
specName simpl (ImplicitS _, tm)
| (P Ref n _, _) <- unApply tm = Just (n, Just (if simpl then 1 else 0))
specName simpl (ExplicitS, tm)
| (P Ref n _, _) <- unApply tm = Just (n, Just (if simpl then 1 else 0))
specName simpl (ConstraintS, tm)
| (P Ref n _, _) <- unApply tm = Just (n, Just (if simpl then 1 else 0))
specName simpl _ = Nothing
-- get the descendants of the name 'n' which are marked %static
-- Marking a function %static essentially means it's used to construct
-- programs, so should be evaluated by the partial evaluator
getStaticsFrom :: Name -> Idris [(Name, Maybe Int)]
getStaticsFrom n = do ns <- getAllNames n
i <- getIState
let statics = filter (staticFn i) ns
return (map (\n -> (n, Nothing)) statics)
staticFn :: IState -> Name -> Bool
staticFn i n = case lookupCtxt n (idris_flags i) of
[opts] -> elem StaticFn opts
_ -> False
notStatic ist n = case lookupCtxtExact n (idris_statics ist) of
Just s -> not (or s)
_ -> True
concreteArg ist (ImplicitS _, tm) = concreteTm ist tm
concreteArg ist (ExplicitS, tm) = concreteTm ist tm
concreteArg ist _ = True
concreteTm ist tm | (P _ n _, _) <- unApply tm =
case lookupTy n (tt_ctxt ist) of
[] -> False
_ -> True
concreteTm ist (Constant _) = True
concreteTm ist (Bind n (Lam _ _) sc) = True
concreteTm ist (Bind n (Pi _ _ _ _) sc) = True
concreteTm ist (Bind n (Let _ _) sc) = concreteTm ist sc
concreteTm ist _ = False
-- get the type of a specialised application
getSpecTy ist (n, args)
= case lookupTy n (tt_ctxt ist) of
[ty] -> let (specty_in, args') = specType args (explicitNames ty)
specty = normalise (tt_ctxt ist) [] (finalise specty_in)
t = mkPE_TyDecl ist args' (explicitNames specty) in
return (t, (n, args'))
-- (normalise (tt_ctxt ist) [] (specType args ty))
_ -> ifail $ "Ambiguous name " ++ show n ++ " (getSpecTy)"
-- get the clause of a specialised application
getSpecClause ist (n, args) specTy
= let newnm = sUN ("PE_" ++ show (nsroot n) ++ "_" ++
qhash 5381 (showSep "_" (map showArg args))) in
-- UN (show n ++ show (map snd args)) in
(n, newnm, mkPE_TermDecl ist newnm n specTy args)
where showArg (ExplicitS, n) = qshow n
showArg (ImplicitS _, n) = qshow n
showArg _ = ""
qshow (Bind _ _ _) = "fn"
qshow (App _ f a) = qshow f ++ qshow a
qshow (P _ n _) = show n
qshow (Constant c) = show c
qshow _ = ""
-- Simple but effective string hashing...
-- Keep it to 32 bits for readability/debuggability
qhash :: Word64 -> String -> String
qhash hash [] = showHex (abs hash `mod` 0xffffffff) ""
qhash hash (x:xs) = qhash (hash * 33 + fromIntegral(fromEnum x)) xs
-- | Checks if the clause is a possible left hand side.
-- NOTE: A lot of this is repeated for reflected definitions in Idris.Elab.Term
-- One day, these should be merged, but until then remember that if you edit
-- this you might need to edit the other version...
checkPossible :: ElabInfo -> FC -> Bool -> Name -> PTerm -> Idris (Maybe PTerm)
checkPossible info fc tcgen fname lhs_in
= do ctxt <- getContext
i <- getIState
let lhs = addImplPat i lhs_in
logElab 10 $ "Trying missing case: " ++ showTmImpls lhs
-- if the LHS type checks, it is possible
case elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "patLHS") infP initEState
(erun fc (buildTC i info EImpossible [] fname
(allNamesIn lhs_in)
(infTerm lhs))) of
OK (ElabResult lhs' _ _ ctxt' newDecls highlights newGName, _) ->
do setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
let lhs_tm = normalise ctxt [] (orderPats (getInferTerm lhs'))
let emptyPat = hasEmptyPat ctxt (idris_datatypes i) lhs_tm
if emptyPat then
do logElab 10 $ "Empty type in pattern "
return Nothing
else
case recheck (constraintNS info) ctxt' [] (forget lhs_tm) lhs_tm of
OK (tm, _, _) ->
do logElab 10 $ "Valid " ++ show tm ++ "\n"
++ " from " ++ show lhs
return (Just (delab' i tm True True))
err -> do logElab 10 $ "Conversion failure"
return Nothing
-- if it's a recoverable error, the case may become possible
Error err -> do logLvl 10 $ "Impossible case " ++ (pshow i err)
++ "\n" ++ show (recoverableCoverage ctxt err,
validCoverageCase ctxt err)
-- tcgen means that it was generated by genClauses,
-- so only looking for an error. Otherwise, it
-- needs to be the right kind of error (a type mismatch
-- in the same family).
if tcgen then returnTm i err (recoverableCoverage ctxt err)
else returnTm i err (validCoverageCase ctxt err ||
recoverableCoverage ctxt err)
where returnTm i err True = do logLvl 10 $ "Possibly resolvable error on " ++
pshow i (fmap (normalise (tt_ctxt i) []) err)
++ " on " ++ showTmImpls lhs_in
return $ Just lhs_in
returnTm i err False = return $ Nothing
-- Filter out the terms which are not well type left hand sides. Whenever we
-- eliminate one, also eliminate later ones which match it without checking,
-- because they're obviously going to have the same result
checkPossibles :: ElabInfo -> FC -> Bool -> Name -> [PTerm] -> Idris [PTerm]
checkPossibles info fc tcgen fname (lhs : rest)
= do ok <- checkPossible info fc tcgen fname lhs
i <- getIState
-- Hypothesis: any we can remove will be within the next few, because
-- leftmost patterns tend to change less
-- Since the match could take a while if there's a lot of cases to
-- check, just remove from the next batch
let rest' = filter (\x -> not (qmatch x lhs)) (take 200 rest) ++ drop 200 rest
restpos <- checkPossibles info fc tcgen fname rest'
case ok of
Nothing -> return restpos
Just lhstm -> return (lhstm : restpos)
where
qmatch _ Placeholder = True
qmatch (PApp _ f args) (PApp _ f' args')
| length args == length args'
= qmatch f f' && and (zipWith qmatch (map getTm args)
(map getTm args'))
qmatch (PRef _ _ n) (PRef _ _ n') = n == n'
qmatch (PPair _ _ _ l r) (PPair _ _ _ l' r') = qmatch l l' && qmatch r r'
qmatch (PDPair _ _ _ l t r) (PDPair _ _ _ l' t' r')
= qmatch l l' && qmatch t t' && qmatch r r'
qmatch x y = x == y
checkPossibles _ _ _ _ [] = return []
findUnique :: Context -> Env -> Term -> [Name]
findUnique ctxt env (Bind n b sc)
= let rawTy = forgetEnv (map fstEnv env) (binderTy b)
uniq = case check ctxt env rawTy of
OK (_, UType UniqueType) -> True
OK (_, UType NullType) -> True
OK (_, UType AllTypes) -> True
_ -> False in
if uniq then n : findUnique ctxt ((n, RigW, b) : env) sc
else findUnique ctxt ((n, RigW, b) : env) sc
findUnique _ _ _ = []
-- | Return the elaborated LHS/RHS, and the original LHS with implicits added
elabClause :: ElabInfo -> FnOpts -> (Int, PClause) ->
Idris (Either Term (Term, Term), PTerm)
elabClause info opts (_, PClause fc fname lhs_in [] PImpossible [])
= do let tcgen = Dictionary `elem` opts
i <- get
let lhs = addImpl [] i lhs_in
b <- checkPossible info fc tcgen fname lhs_in
case b of
Just _ -> tclift $ tfail (At fc
(Msg $ show lhs_in ++ " is a valid case"))
Nothing -> do ptm <- mkPatTm lhs_in
logElab 5 $ "Elaborated impossible case " ++ showTmImpls lhs ++
"\n" ++ show ptm
return (Left ptm, lhs)
elabClause info opts (cnum, PClause fc fname lhs_in_as withs rhs_in_as whereblock)
= do let tcgen = Dictionary `elem` opts
push_estack fname False
ctxt <- getContext
let (lhs_in, rhs_in) = desugarAs lhs_in_as rhs_in_as
-- Build the LHS as an "Infer", and pull out its type and
-- pattern bindings
i <- getIState
inf <- isTyInferred fname
-- Check if we have "with" patterns outside of "with" block
when (isOutsideWith lhs_in && (not $ null withs)) $
ierror (At fc (Elaborating "left hand side of " fname Nothing
(Msg "unexpected patterns outside of \"with\" block")))
-- get the parameters first, to pass through to any where block
let fn_ty = case lookupTy fname ctxt of
[t] -> t
_ -> error "Can't happen (elabClause function type)"
let fn_is = case lookupCtxt fname (idris_implicits i) of
[t] -> t
_ -> []
let norm_ty = normalise ctxt [] fn_ty
let params = getParamsInType i [] fn_is norm_ty
let tcparams = getTCParamsInType i [] fn_is norm_ty
let lhs = mkLHSapp $ stripLinear i $ stripUnmatchable i $
propagateParams i params norm_ty (allNamesIn lhs_in) (addImplPat i lhs_in)
-- let lhs = mkLHSapp $
-- propagateParams i params fn_ty (addImplPat i lhs_in)
logElab 10 (show (params, fn_ty) ++ " " ++ showTmImpls (addImplPat i lhs_in))
logElab 5 ("LHS: " ++ show opts ++ "\n" ++ show fc ++ " " ++ showTmImpls lhs)
logElab 4 ("Fixed parameters: " ++ show params ++ " from " ++ showTmImpls lhs_in ++
"\n" ++ show (fn_ty, fn_is))
((ElabResult lhs' dlhs [] ctxt' newDecls highlights newGName, probs, inj), _) <-
tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "patLHS") infP initEState
(do res <- errAt "left hand side of " fname Nothing
(erun fc (buildTC i info ELHS opts fname
(allNamesIn lhs_in)
(infTerm lhs)))
probs <- get_probs
inj <- get_inj
return (res, probs, inj))
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
when inf $ addTyInfConstraints fc (map (\(x,y,_,_,_,_,_) -> (x,y)) probs)
let lhs_tm = orderPats (getInferTerm lhs')
let lhs_ty = getInferType lhs'
let static_names = getStaticNames i lhs_tm
logElab 3 ("Elaborated: " ++ show lhs_tm)
logElab 3 ("Elaborated type: " ++ show lhs_ty)
logElab 5 ("Injective: " ++ show fname ++ " " ++ show inj)
-- If we're inferring metavariables in the type, don't recheck,
-- because we're only doing this to try to work out those metavariables
ctxt <- getContext
(clhs_c, clhsty) <- if not inf
then recheckC_borrowing False (PEGenerated `notElem` opts)
[] (constraintNS info) fc id [] lhs_tm
else return (lhs_tm, lhs_ty)
let clhs = normalise ctxt [] clhs_c
let borrowed = borrowedNames [] clhs
-- These are the names we're not allowed to use on the RHS, because
-- they're UniqueTypes and borrowed from another function.
when (not (null borrowed)) $
logElab 5 ("Borrowed names on LHS: " ++ show borrowed)
logElab 3 ("Normalised LHS: " ++ showTmImpls (delabMV i clhs))
rep <- useREPL
when rep $ do
addInternalApp (fc_fname fc) (fst . fc_start $ fc) (delabMV i clhs) -- TODO: Should use span instead of line and filename?
addIBC (IBCLineApp (fc_fname fc) (fst . fc_start $ fc) (delabMV i clhs))
logElab 5 ("Checked " ++ show clhs ++ "\n" ++ show clhsty)
-- Elaborate where block
ist <- getIState
ctxt <- getContext
windex <- getName
let decls = nub (concatMap declared whereblock)
let defs = nub (decls ++ concatMap defined whereblock)
let newargs_all = pvars ist lhs_tm
-- Unique arguments must be passed to the where block explicitly
-- (since we can't control "usage" easlily otherwise). Remove them
-- from newargs here
let uniqargs = findUnique ctxt [] lhs_tm
let newargs = filter (\(n,_) -> n `notElem` uniqargs) newargs_all
let winfo = (pinfo info newargs defs windex) { elabFC = Just fc }
let wb = map (mkStatic static_names) $
map (expandImplementationScope ist decorate newargs defs) $
map (expandParamsD False ist decorate newargs defs) whereblock
-- Split the where block into declarations with a type, and those
-- without
-- Elaborate those with a type *before* RHS, those without *after*
let (wbefore, wafter) = sepBlocks wb
logElab 5 $ "Where block:\n " ++ show wbefore ++ "\n" ++ show wafter
mapM_ (rec_elabDecl info EAll winfo) wbefore
-- Now build the RHS, using the type of the LHS as the goal.
i <- getIState -- new implicits from where block
logElab 5 (showTmImpls (expandParams decorate newargs defs (defs \\ decls) rhs_in))
let rhs = rhs_trans info $
addImplBoundInf i (map fst newargs_all) (defs \\ decls)
(expandParams decorate newargs defs (defs \\ decls) rhs_in)
logElab 2 $ "RHS: " ++ show (map fst newargs_all) ++ " " ++ showTmImpls rhs
ctxt <- getContext -- new context with where block added
logElab 5 "STARTING CHECK"
((rhsElab, defer, holes, is, probs, ctxt', newDecls, highlights, newGName), _) <-
tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "patRHS") clhsty initEState
(do pbinds ist lhs_tm
-- proof search can use explicitly written names
mapM_ addPSname (allNamesIn lhs_in)
ulog <- getUnifyLog
traceWhen ulog ("Setting injective: " ++ show (nub (tcparams ++ inj))) $
mapM_ setinj (nub (tcparams ++ inj))
setNextName
(ElabResult _ _ is ctxt' newDecls highlights newGName) <-
errAt "right hand side of " fname (Just clhsty)
(erun fc (build i winfo ERHS opts fname rhs))
errAt "right hand side of " fname (Just clhsty)
(erun fc $ psolve lhs_tm)
tt <- get_term
aux <- getAux
let (tm, ds) = runState (collectDeferred (Just fname)
(map fst $ case_decls aux) ctxt tt) []
probs <- get_probs
hs <- get_holes
return (tm, ds, hs, is, probs, ctxt', newDecls, highlights, newGName))
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
when inf $ addTyInfConstraints fc (map (\(x,y,_,_,_,_,_) -> (x,y)) probs)
logElab 3 "DONE CHECK"
logElab 3 $ "---> " ++ show rhsElab
ctxt <- getContext
let rhs' = rhsElab
when (not (null defer)) $ logElab 2 $ "DEFERRED " ++
show (map (\ (n, (_,_,t,_)) -> (n, t)) defer)
-- If there's holes, set the metavariables as undefinable
def' <- checkDef info fc (\n -> Elaborating "deferred type of " n Nothing) (null holes) defer
let def'' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, False, null holes))) def'
addDeferred def''
mapM_ (\(n, _) -> addIBC (IBCDef n)) def''
when (not (null def')) $ do
mapM_ defer_totcheck (map (\x -> (fc, fst x)) def'')
-- Now the remaining deferred (i.e. no type declarations) clauses
-- from the where block
mapM_ (rec_elabDecl info EAll winfo) wafter
mapM_ (elabCaseBlock winfo opts) is
ctxt <- getContext
logElab 5 "Rechecking"
logElab 6 $ " ==> " ++ show (forget rhs')
(crhs, crhsty) -- if there's holes && deferred things, it's okay
-- but we'll need to freeze the definition and not
-- allow the deferred things to be definable
-- (this is just to allow users to inspect intermediate
-- things)
<- if (null holes || null def') && not inf
then recheckC_borrowing True (PEGenerated `notElem` opts)
borrowed (constraintNS info) fc id [] rhs'
else return (rhs', clhsty)
logElab 6 $ " ==> " ++ showEnvDbg [] crhsty ++ " against " ++ showEnvDbg [] clhsty
-- If there's holes, make sure this definition is frozen
when (not (null holes)) $ do
logElab 5 $ "Making " ++ show fname ++ " frozen due to " ++ show holes
setAccessibility fname Frozen
ctxt <- getContext
let constv = next_tvar ctxt
tit <- typeInType
case LState.runStateT (convertsC ctxt [] crhsty clhsty) (constv, []) of
OK (_, cs) -> when (PEGenerated `notElem` opts && not tit) $ do
addConstraints fc cs
mapM_ (\c -> addIBC (IBCConstraint fc c)) (snd cs)
logElab 6 $ "CONSTRAINTS ADDED: " ++ show cs ++ "\n" ++ show (clhsty, crhsty)
return ()
Error e -> ierror (At fc (CantUnify False (clhsty, Nothing) (crhsty, Nothing) e [] 0))
i <- getIState
checkInferred fc (delab' i crhs True True) rhs
-- if the function is declared '%error_reverse',
-- then we'll try running it in reverse to improve error messages
-- Also if the type is '%error_reverse' and the LHS is smaller than
-- the RHS
let (ret_fam, _) = unApply (getRetTy crhsty)
rev <- case ret_fam of
P _ rfamn _ ->
case lookupCtxt rfamn (idris_datatypes i) of
[TI _ _ dopts _ _ _] ->
return (DataErrRev `elem` dopts &&
size clhs <= size crhs)
_ -> return False
_ -> return False
when (rev || ErrorReverse `elem` opts) $ do
addIBC (IBCErrRev (crhs, clhs))
addErrRev (crhs, clhs)
when (rev || ErrorReduce `elem` opts) $ do
addIBC (IBCErrReduce fname)
addErrReduce fname
pop_estack
return (Right (clhs, crhs), lhs)
where
pinfo :: ElabInfo -> [(Name, PTerm)] -> [Name] -> Int -> ElabInfo
pinfo info ns ds i
= let newps = params info ++ ns
dsParams = map (\n -> (n, map fst newps)) ds
newb = addAlist dsParams (inblock info)
l = liftname info in
info { params = newps,
inblock = newb,
liftname = id -- (\n -> case lookupCtxt n newb of
-- Nothing -> n
-- _ -> MN i (show n)) . l
}
-- Find the variable names which appear under a 'Ownership.Read' so that
-- we know they can't be used on the RHS
borrowedNames :: [Name] -> Term -> [Name]
borrowedNames env (App _ (App _ (P _ (NS (UN lend) [owner]) _) _) arg)
| owner == txt "Ownership" &&
(lend == txt "lend" || lend == txt "Read") = getVs arg
where
getVs (V i) = [env!!i]
getVs (App _ f a) = nub $ getVs f ++ getVs a
getVs _ = []
borrowedNames env (App _ f a) = nub $ borrowedNames env f ++ borrowedNames env a
borrowedNames env (Bind n b sc) = nub $ borrowedB b ++ borrowedNames (n:env) sc
where borrowedB (Let t v) = nub $ borrowedNames env t ++ borrowedNames env v
borrowedB b = borrowedNames env (binderTy b)
borrowedNames _ _ = []
mkLHSapp t@(PRef _ _ _) = PApp fc t []
mkLHSapp t = t
decorate (NS x ns)
= NS (SN (WhereN cnum fname x)) ns
decorate x
= SN (WhereN cnum fname x)
sepBlocks bs = sepBlocks' [] bs where
sepBlocks' ns (d@(PTy _ _ _ _ _ n _ t) : bs)
= let (bf, af) = sepBlocks' (n : ns) bs in
(d : bf, af)
sepBlocks' ns (d@(PClauses _ _ n _) : bs)
| not (n `elem` ns) = let (bf, af) = sepBlocks' ns bs in
(bf, d : af)
sepBlocks' ns (b : bs) = let (bf, af) = sepBlocks' ns bs in
(b : bf, af)
sepBlocks' ns [] = ([], [])
-- term is not within "with" block
isOutsideWith :: PTerm -> Bool
isOutsideWith (PApp _ (PRef _ _ (SN (WithN _ _))) _) = False
isOutsideWith _ = True
elabClause info opts (_, PWith fc fname lhs_in withs wval_in pn_in withblock)
= do let tcgen = Dictionary `elem` opts
ctxt <- getContext
-- Build the LHS as an "Infer", and pull out its type and
-- pattern bindings
i <- getIState
-- get the parameters first, to pass through to any where block
let fn_ty = case lookupTy fname ctxt of
[t] -> t
_ -> error "Can't happen (elabClause function type)"
let fn_is = case lookupCtxt fname (idris_implicits i) of
[t] -> t
_ -> []
let params = getParamsInType i [] fn_is (normalise ctxt [] fn_ty)
let lhs = stripLinear i $ stripUnmatchable i $
propagateParams i params fn_ty (allNamesIn lhs_in)
(addImplPat i lhs_in)
logElab 2 ("LHS: " ++ show lhs)
(ElabResult lhs' dlhs [] ctxt' newDecls highlights newGName, _) <-
tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "patLHS") infP initEState
(errAt "left hand side of with in " fname Nothing
(erun fc (buildTC i info ELHS opts fname
(allNamesIn lhs_in)
(infTerm lhs))) )
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
ctxt <- getContext
let lhs_tm = orderPats (getInferTerm lhs')
let lhs_ty = getInferType lhs'
let ret_ty = getRetTy (explicitNames (normalise ctxt [] lhs_ty))
let static_names = getStaticNames i lhs_tm
logElab 5 (show lhs_tm ++ "\n" ++ show static_names)
(clhs_c, clhsty) <- recheckC (constraintNS info) fc id [] lhs_tm
let clhs = normalise ctxt [] clhs_c
logElab 5 ("Checked " ++ show clhs)
let bargs = getPBtys (explicitNames (normalise ctxt [] lhs_tm))
wval <- case wval_in of
Placeholder -> ierror $ At fc $
Msg "No expression for the with block to inspect.\nYou need to replace the _ with an expression."
_ -> return $
rhs_trans info $
addImplBound i (map fst bargs) wval_in
logElab 5 ("Checking " ++ showTmImpls wval)
-- Elaborate wval in this context
((wvalElab, defer, is, ctxt', newDecls, highlights, newGName), _) <-
tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "withRHS")
(bindTyArgs PVTy bargs infP) initEState
(do pbinds i lhs_tm
-- proof search can use explicitly written names
mapM_ addPSname (allNamesIn lhs_in)
setNextName
-- TODO: may want where here - see winfo abpve
(ElabResult _ d is ctxt' newDecls highlights newGName) <- errAt "with value in " fname Nothing
(erun fc (build i info ERHS opts fname (infTerm wval)))
erun fc $ psolve lhs_tm
tt <- get_term
return (tt, d, is, ctxt', newDecls, highlights, newGName))
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
def' <- checkDef info fc iderr True defer
let def'' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, False, True))) def'
addDeferred def''
mapM_ (elabCaseBlock info opts) is
let wval' = wvalElab
logElab 5 ("Checked wval " ++ show wval')
ctxt <- getContext
(cwval, cwvalty) <- recheckC (constraintNS info) fc id [] (getInferTerm wval')
let cwvaltyN = explicitNames (normalise ctxt [] cwvalty)
let cwvalN = explicitNames (normalise ctxt [] cwval)
logElab 3 ("With type " ++ show cwvalty ++ "\nRet type " ++ show ret_ty)
-- We're going to assume the with type is not a function shortly,
-- so report an error if it is (you can't match on a function anyway
-- so this doesn't lose anything)
case getArgTys cwvaltyN of
[] -> return ()
(_:_) -> ierror $ At fc (WithFnType cwvalty)
let pvars = map fst (getPBtys cwvalty)
-- we need the unelaborated term to get the names it depends on
-- rather than a de Bruijn index.
let pdeps = usedNamesIn pvars i (delab i cwvalty)
let (bargs_pre, bargs_post) = split pdeps bargs []
let mpn = case pn_in of
Nothing -> Nothing
Just (n, nfc) -> Just (uniqueName n (map fst bargs))
-- Highlight explicit proofs
sendHighlighting [(fc, AnnBoundName n False) | (n, fc) <- maybeToList pn_in]
logElab 10 ("With type " ++ show (getRetTy cwvaltyN) ++
" depends on " ++ show pdeps ++ " from " ++ show pvars)
logElab 10 ("Pre " ++ show bargs_pre ++ "\nPost " ++ show bargs_post)
windex <- getName
-- build a type declaration for the new function:
-- (ps : Xs) -> (withval : cwvalty) -> (ps' : Xs') -> ret_ty
let wargval = getRetTy cwvalN
let wargtype = getRetTy cwvaltyN
let wargname = sMN windex "warg"
logElab 5 ("Abstract over " ++ show wargval ++ " in " ++ show wargtype)
let wtype = bindTyArgs (flip (Pi RigW Nothing) (TType (UVar [] 0))) (bargs_pre ++
(wargname, wargtype) :
map (abstract wargname wargval wargtype) bargs_post ++
case mpn of
Just pn -> [(pn, mkApp (P Ref eqTy Erased)
[wargtype, wargtype,
P Bound wargname Erased, wargval])]
Nothing -> [])
(substTerm wargval (P Bound wargname wargtype) ret_ty)
logElab 3 ("New function type " ++ show wtype)
let wname = SN (WithN windex fname)
let imps = getImps wtype -- add to implicits context
putIState (i { idris_implicits = addDef wname imps (idris_implicits i) })
let statics = getStatics static_names wtype
logElab 5 ("Static positions " ++ show statics)
i <- getIState
putIState (i { idris_statics = addDef wname statics (idris_statics i) })
addIBC (IBCDef wname)
addIBC (IBCImp wname)
addIBC (IBCStatic wname)
def' <- checkDef info fc iderr True [(wname, (-1, Nothing, wtype, []))]
let def'' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, False, True))) def'
addDeferred def''
-- in the subdecls, lhs becomes:
-- fname pats | wpat [rest]
-- ==> fname' ps wpat [rest], match pats against toplevel for ps
wb <- mapM (mkAuxC mpn wname lhs (map fst bargs_pre) (map fst bargs_post))
withblock
logElab 3 ("with block " ++ show wb)
setFlags wname [Inlinable]
when (AssertTotal `elem` opts) $
setFlags wname [Inlinable, AssertTotal]
i <- getIState
let rhstrans' = updateWithTerm i mpn wname lhs (map fst bargs_pre) (map fst (bargs_post))
. rhs_trans info
mapM_ (rec_elabDecl info EAll (info { rhs_trans = rhstrans' })) wb
-- rhs becomes: fname' ps_pre wval ps_post Refl
let rhs = PApp fc (PRef fc [] wname)
(map (pexp . (PRef fc []) . fst) bargs_pre ++
pexp wval :
(map (pexp . (PRef fc []) . fst) bargs_post) ++
case mpn of
Nothing -> []
Just _ -> [pexp (PApp NoFC (PRef NoFC [] eqCon)
[ pimp (sUN "A") Placeholder False
, pimp (sUN "x") Placeholder False
])])
logElab 5 ("New RHS " ++ showTmImpls rhs)
ctxt <- getContext -- New context with block added
i <- getIState
((rhsElab, defer, is, ctxt', newDecls, highlights, newGName), _) <-
tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "wpatRHS") clhsty initEState
(do pbinds i lhs_tm
setNextName
(ElabResult _ d is ctxt' newDecls highlights newGName) <-
erun fc (build i info ERHS opts fname rhs)
psolve lhs_tm
tt <- get_term
return (tt, d, is, ctxt', newDecls, highlights, newGName))
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
ctxt <- getContext
let rhs' = rhsElab
def' <- checkDef info fc iderr True defer
let def'' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, False, True))) def'
addDeferred def''
mapM_ (elabCaseBlock info opts) is
logElab 5 ("Checked RHS " ++ show rhs')
(crhs, crhsty) <- recheckC (constraintNS info) fc id [] rhs'
return (Right (clhs, crhs), lhs)
where
getImps (Bind n (Pi _ _ _ _) t) = pexp Placeholder : getImps t
getImps _ = []
mkAuxC pn wname lhs ns ns' (PClauses fc o n cs)
= do cs' <- mapM (mkAux pn wname lhs ns ns') cs
return $ PClauses fc o wname cs'
mkAuxC pn wname lhs ns ns' d = return d
mkAux pn wname toplhs ns ns' (PClause fc n tm_in (w:ws) rhs wheres)
= do i <- getIState
let tm = addImplPat i tm_in
logElab 2 ("Matching " ++ showTmImpls tm ++ " against " ++
showTmImpls toplhs)
case matchClause i toplhs tm of
Left (a,b) -> ifail $ show fc ++ ":with clause does not match top level"
Right mvars ->
do logElab 3 ("Match vars : " ++ show mvars)
lhs <- updateLHS n pn wname mvars ns ns' (fullApp tm) w
return $ PClause fc wname lhs ws rhs wheres
mkAux pn wname toplhs ns ns' (PWith fc n tm_in (w:ws) wval pn' withs)
= do i <- getIState
let tm = addImplPat i tm_in
logElab 2 ("Matching " ++ showTmImpls tm ++ " against " ++
showTmImpls toplhs)
withs' <- mapM (mkAuxC pn wname toplhs ns ns') withs
case matchClause i toplhs tm of
Left (a,b) -> trace ("matchClause: " ++ show a ++ " =/= " ++ show b) (ifail $ show fc ++ "with clause does not match top level")
Right mvars ->
do lhs <- updateLHS n pn wname mvars ns ns' (fullApp tm) w
return $ PWith fc wname lhs ws wval pn' withs'
mkAux pn wname toplhs ns ns' c
= ifail $ show fc ++ ":badly formed with clause"
addArg (PApp fc f args) w = PApp fc f (args ++ [pexp w])
addArg (PRef fc hls f) w = PApp fc (PRef fc hls f) [pexp w]
-- ns, arguments which don't depend on the with argument
-- ns', arguments which do
updateLHS n pn wname mvars ns_in ns_in' (PApp fc (PRef fc' hls' n') args) w
= let ns = map (keepMvar (map fst mvars) fc') ns_in
ns' = map (keepMvar (map fst mvars) fc') ns_in' in
return $ substMatches mvars $
PApp fc (PRef fc' [] wname)
(map pexp ns ++ pexp w : (map pexp ns') ++
case pn of
Nothing -> []
Just pnm -> [pexp (PRef fc [] pnm)])
updateLHS n pn wname mvars ns_in ns_in' tm w
= updateLHS n pn wname mvars ns_in ns_in' (PApp fc tm []) w
-- Only keep a var as a pattern variable in the with block if it's
-- matched in the top level pattern
keepMvar mvs fc v | v `elem` mvs = PRef fc [] v
| otherwise = Placeholder
updateWithTerm :: IState -> Maybe Name -> Name -> PTerm -> [Name] -> [Name] -> PTerm -> PTerm
updateWithTerm ist pn wname toplhs ns_in ns_in' tm
= mapPT updateApp tm
where
arity (PApp _ _ as) = length as
arity _ = 0
lhs_arity = arity toplhs
currentFn fname (PAlternative _ _ as)
| Just tm <- getApp as = tm
where getApp (tm@(PApp _ (PRef _ _ f) _) : as)
| f == fname = Just tm
getApp (_ : as) = getApp as
getApp [] = Nothing
currentFn _ tm = tm
updateApp wtm@(PWithApp fcw tm_in warg) =
let tm = currentFn fname tm_in in
case matchClause ist toplhs tm of
Left _ -> PElabError (Msg (show fc ++ ":with application does not match top level "))
Right mvars ->
let ns = map (keepMvar (map fst mvars) fcw) ns_in
ns' = map (keepMvar (map fst mvars) fcw) ns_in'
wty = lookupTyExact wname (tt_ctxt ist)
res = substMatches mvars $
PApp fcw (PRef fcw [] wname)
(map pexp ns ++ pexp warg : (map pexp ns') ++
case pn of
Nothing -> []
Just pnm -> [pexp (PRef fc [] pnm)]) in
case wty of
Nothing -> res -- can't happen!
Just ty -> addResolves ty res
updateApp tm = tm
addResolves ty (PApp fc f args) = PApp fc f (addResolvesArgs fc ty args)
addResolves ty tm = tm
-- if an argument's type is an interface, and is otherwise to
-- be inferred, then resolve it with implementation search
-- This is something of a hack, because matching on the top level
-- application won't find this information for us
addResolvesArgs :: FC -> Term -> [PArg] -> [PArg]
addResolvesArgs fc (Bind n (Pi _ _ ty _) sc) (a : args)
| (P _ cn _, _) <- unApply ty,
getTm a == Placeholder
= case lookupCtxtExact cn (idris_interfaces ist) of
Just _ -> a { getTm = PResolveTC fc } : addResolvesArgs fc sc args
Nothing -> a : addResolvesArgs fc sc args
addResolvesArgs fc (Bind n (Pi _ _ ty _) sc) (a : args)
= a : addResolvesArgs fc sc args
addResolvesArgs fc _ args = args
fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
fullApp x = x
split [] rest pre = (reverse pre, rest)
split deps ((n, ty) : rest) pre
| n `elem` deps = split (deps \\ [n]) rest ((n, ty) : pre)
| otherwise = split deps rest ((n, ty) : pre)
split deps [] pre = (reverse pre, [])
abstract wn wv wty (n, argty) = (n, substTerm wv (P Bound wn wty) argty)
-- | Apply a transformation to all RHSes and nested RHSs
mapRHS :: (PTerm -> PTerm) -> PClause -> PClause
mapRHS f (PClause fc n lhs args rhs ws)
= PClause fc n lhs args (f rhs) (map (mapRHSdecl f) ws)
mapRHS f (PWith fc n lhs args warg prf ws)
= PWith fc n lhs args (f warg) prf (map (mapRHSdecl f) ws)
mapRHS f (PClauseR fc args rhs ws)
= PClauseR fc args (f rhs) (map (mapRHSdecl f) ws)
mapRHS f (PWithR fc args warg prf ws)
= PWithR fc args (f warg) prf (map (mapRHSdecl f) ws)
mapRHSdecl :: (PTerm -> PTerm) -> PDecl -> PDecl
mapRHSdecl f (PClauses fc opt n cs)
= PClauses fc opt n (map (mapRHS f) cs)
mapRHSdecl f t = t
|
FranklinChen/Idris-dev
|
src/Idris/Elab/Clause.hs
|
bsd-3-clause
| 61,851
| 9
| 30
| 24,646
| 17,380
| 8,611
| 8,769
| 955
| 52
|
import Cookbook.Essential.IO
import Cookbook.Ingredients.Lists.Access
import System.IO
import System.Environment
main = do
(file:command:text:_) <- getArgs
fileText <- filelines file
if command == "remove" then do
let parsed = filter (\c -> not (c `contains` text)) fileText
writeFile file (unlines parsed)
else mapM_ putStrLn (filter (\c -> c `contains` text) fileText)
|
natepisarski/WriteUtils
|
sweep.hs
|
bsd-3-clause
| 393
| 1
| 18
| 71
| 154
| 80
| 74
| 11
| 2
|
{-# LANGUAGE CPP, BangPatterns, OverloadedStrings #-}
#ifdef USE_MONO_PAT_BINDS
{-# LANGUAGE MonoPatBinds #-}
#endif
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Blaze.ByteString.Builder.ByteString
-- Copyright : (c) 2010 Jasper Van der Jeugt & Simon Meier
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Simon Meier <iridcode@gmail.com>
-- Stability : experimental
-- Portability : tested on GHC only
--
-- 'Write's and 'Builder's for strict and lazy bytestrings.
--
-- We assume the following qualified imports in order to differentiate between
-- strict and lazy bytestrings in the code examples.
--
-- > import qualified Data.ByteString as S
-- > import qualified Data.ByteString.Lazy as L
--
module Blaze.ByteString.Builder.ByteString
(
-- * Strict bytestrings
writeByteString
, fromByteString
, fromByteStringWith
, copyByteString
, insertByteString
-- * Lazy bytestrings
, fromLazyByteString
, fromLazyByteStringWith
, copyLazyByteString
, insertLazyByteString
) where
import Blaze.ByteString.Builder.Internal hiding (insertByteString)
import qualified Blaze.ByteString.Builder.Internal as I (insertByteString)
#ifdef HAS_FOREIGN_UNSAFE_MODULE
import Foreign (withForeignPtr, touchForeignPtr, copyBytes, plusPtr, minusPtr)
import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
#else
import Foreign (unsafeForeignPtrToPtr, withForeignPtr, touchForeignPtr, copyBytes, plusPtr, minusPtr)
#endif
import Data.Monoid
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
#ifdef BYTESTRING_IN_BASE
import qualified Data.ByteString.Base as S
import qualified Data.ByteString.Lazy.Base as L -- FIXME: check if this is the right module
#else
import qualified Data.ByteString.Internal as S
import qualified Data.ByteString.Lazy.Internal as L
#endif
------------------------------------------------------------------------------
-- Strict ByteStrings
------------------------------------------------------------------------------
-- | Write a strict 'S.ByteString' to a buffer.
--
writeByteString :: S.ByteString -> Write
writeByteString bs = exactWrite l io
where
(fptr, o, l) = S.toForeignPtr bs
io pf = withForeignPtr fptr $ \p -> copyBytes pf (p `plusPtr` o) l
{-# INLINE writeByteString #-}
-- | Smart serialization of a strict bytestring.
--
-- @'fromByteString' = 'fromByteStringWith' 'defaultMaximalCopySize'@
--
-- Use this function to serialize strict bytestrings. It guarantees an
-- average chunk size of 4kb, which has been shown to be a reasonable size in
-- benchmarks. Note that the check whether to copy or to insert is (almost)
-- free as the builder performance is mostly memory-bound.
--
-- If you statically know that copying or inserting the strict bytestring is
-- always the best choice, then you can use the 'copyByteString' or
-- 'insertByteString' functions.
--
fromByteString :: S.ByteString -> Builder
fromByteString = fromByteStringWith defaultMaximalCopySize
{-# INLINE fromByteString #-}
-- | @fromByteStringWith maximalCopySize bs@ serializes the strict bytestring
-- @bs@ according to the following rules.
--
-- [@S.length bs <= maximalCopySize@:] @bs@ is copied to the output buffer.
--
-- [@S.length bs > maximalCopySize@:] @bs@ the output buffer is flushed and
-- @bs@ is inserted directly as separate chunk in the output stream.
--
-- These rules guarantee that average chunk size in the output stream is at
-- least half the @maximalCopySize@.
--
fromByteStringWith :: Int -- ^ Maximal number of bytes to copy.
-> S.ByteString -- ^ Strict 'S.ByteString' to serialize.
-> Builder -- ^ Resulting 'Builder'.
fromByteStringWith maxCopySize =
\bs -> fromBuildStepCont $ step bs
where
step !bs !k br@(BufRange !op _)
| maxCopySize < S.length bs = return $ I.insertByteString op bs k
| otherwise = copyByteStringStep bs k br
{-# INLINE fromByteStringWith #-}
-- | @copyByteString bs@ serialize the strict bytestring @bs@ by copying it to
-- the output buffer.
--
-- Use this function to serialize strict bytestrings that are statically known
-- to be smallish (@<= 4kb@).
--
copyByteString :: S.ByteString -> Builder
copyByteString = \bs -> fromBuildStepCont $ copyByteStringStep bs
{-# INLINE copyByteString #-}
copyByteStringStep :: S.ByteString
-> (BufRange -> IO (BuildSignal a))
-> (BufRange -> IO (BuildSignal a))
copyByteStringStep (S.PS ifp ioff isize) !k =
goBS (unsafeForeignPtrToPtr ifp `plusPtr` ioff)
where
!ipe = unsafeForeignPtrToPtr ifp `plusPtr` (ioff + isize)
goBS !ip !(BufRange op ope)
| inpRemaining <= outRemaining = do
copyBytes op ip inpRemaining
touchForeignPtr ifp -- input consumed: OK to release from here
let !br' = BufRange (op `plusPtr` inpRemaining) ope
k br'
| otherwise = do
copyBytes op ip outRemaining
let !ip' = ip `plusPtr` outRemaining
return $ bufferFull 1 ope (goBS ip')
where
outRemaining = ope `minusPtr` op
inpRemaining = ipe `minusPtr` ip
{-# INLINE copyByteStringStep #-}
-- | @insertByteString bs@ serializes the strict bytestring @bs@ by inserting
-- it directly as a chunk of the output stream.
--
-- Note that this implies flushing the output buffer; even if it contains just
-- a single byte. Hence, you should use this operation only for large (@> 8kb@)
-- bytestrings, as otherwise the resulting output stream may be too fragmented
-- to be processed efficiently.
--
insertByteString :: S.ByteString -> Builder
insertByteString =
\bs -> fromBuildStepCont $ step bs
where
step !bs !k !(BufRange op _) = return $ I.insertByteString op bs k
{-# INLINE insertByteString #-}
-- Lazy bytestrings
------------------------------------------------------------------------------
-- | /O(n)/. Smart serialization of a lazy bytestring.
--
-- @'fromLazyByteString' = 'fromLazyByteStringWith' 'defaultMaximalCopySize'@
--
-- Use this function to serialize lazy bytestrings. It guarantees an average
-- chunk size of 4kb, which has been shown to be a reasonable size in
-- benchmarks. Note that the check whether to copy or to insert is (almost)
-- free as the builder performance is mostly memory-bound.
--
-- If you statically know that copying or inserting /all/ chunks of the lazy
-- bytestring is always the best choice, then you can use the
-- 'copyLazyByteString' or 'insertLazyByteString' functions.
--
fromLazyByteString :: L.ByteString -> Builder
fromLazyByteString = fromLazyByteStringWith defaultMaximalCopySize
{-# INLINE fromLazyByteString #-}
-- | /O(n)/. Serialize a lazy bytestring chunk-wise according to the same rules
-- as in 'fromByteStringWith'.
--
-- Semantically, it holds that
--
-- > fromLazyByteStringWith maxCopySize
-- > = mconcat . map (fromByteStringWith maxCopySize) . L.toChunks
--
-- However, the left-hand-side is much more efficient, as it moves the
-- end-of-buffer pointer out of the inner loop and provides the compiler with
-- more strictness information.
--
fromLazyByteStringWith :: Int -- ^ Maximal number of bytes to copy.
-> L.ByteString -- ^ Lazy 'L.ByteString' to serialize.
-> Builder -- ^ Resulting 'Builder'.
fromLazyByteStringWith maxCopySize =
L.foldrChunks (\bs b -> fromByteStringWith maxCopySize bs `mappend` b) mempty
{-# INLINE fromLazyByteStringWith #-}
-- | /O(n)/. Serialize a lazy bytestring by copying /all/ chunks sequentially
-- to the output buffer.
--
-- See 'copyByteString' for usage considerations.
--
copyLazyByteString :: L.ByteString -> Builder
copyLazyByteString =
L.foldrChunks (\bs b -> copyByteString bs `mappend` b) mempty
{-# INLINE copyLazyByteString #-}
-- | /O(n)/. Serialize a lazy bytestring by inserting /all/ its chunks directly
-- into the output stream.
--
-- See 'insertByteString' for usage considerations.
--
-- For library developers, see the 'ModifyChunks' build signal, if you
-- need an /O(1)/ lazy bytestring insert based on difference lists.
--
insertLazyByteString :: L.ByteString -> Builder
insertLazyByteString =
L.foldrChunks (\bs b -> insertByteString bs `mappend` b) mempty
{-# INLINE insertLazyByteString #-}
|
meiersi/blaze-builder
|
Blaze/ByteString/Builder/ByteString.hs
|
bsd-3-clause
| 8,429
| 0
| 15
| 1,609
| 991
| 589
| 402
| 82
| 1
|
module Main ( main ) where
import Data.Map ( Map )
import Data.Monoid
import Data.Set ( Set )
import System.FilePath ( (<.>) )
import System.Environment ( getArgs, withArgs )
import Test.HUnit ( assertEqual )
import LLVM.Analysis
import LLVM.Analysis.CallGraph
import LLVM.Analysis.CallGraphSCCTraversal
import LLVM.Analysis.Util.Testing
import LLVM.Parse
import Foreign.Inference.Interface
import Foreign.Inference.Preprocessing
import Foreign.Inference.Analysis.Finalize
import Foreign.Inference.Analysis.IndirectCallResolver
import Foreign.Inference.Analysis.Util.CompositeSummary
main :: IO ()
main = do
args <- getArgs
let pattern = case args of
[] -> "tests/finalize/*.c"
[infile] -> infile
_ -> error "At most one argument allowed"
ds <- loadDependencies ["tests/finalize"] []
let testDescriptors = [ TestDescriptor { testPattern = pattern
, testExpectedMapping = (<.> "expected")
, testResultBuilder = analyzeFinalize ds
, testResultComparator = assertEqual
}
]
withArgs [] $ testAgainstExpected requiredOptimizations parser testDescriptors
where
parser = parseLLVMFile defaultParserOptions
analyzeFinalize :: DependencySummary -> Module -> Map String (Set String)
analyzeFinalize ds m =
finalizerSummaryToTestFormat (_finalizerSummary res)
where
ics = identifyIndirectCallTargets m
cg = callGraph m ics []
analyses :: [ComposableAnalysis AnalysisSummary FunctionMetadata]
analyses = [ identifyFinalizers ds ics finalizerSummary ]
analysisFunc = callGraphComposeAnalysis analyses
res = callGraphSCCTraversal cg analysisFunc mempty
|
travitch/foreign-inference
|
tests/FinalizerTests.hs
|
bsd-3-clause
| 1,800
| 0
| 13
| 438
| 399
| 222
| 177
| 40
| 3
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ordinal.DE.Corpus
( corpus
, negativeCorpus
) where
import Prelude
import Data.String
import Duckling.Locale
import Duckling.Ordinal.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale DE Nothing}, testOptions, allExamples)
negativeCorpus :: NegativeCorpus
negativeCorpus = (testContext {locale = makeLocale DE Nothing}, testOptions, examples)
where
examples =
[ "1.1"
, "1.1."
]
allExamples :: [Example]
allExamples =
examples (OrdinalData 4)
[ "vierter"
, "4ter"
, "Vierter"
, "4."
]
|
facebookincubator/duckling
|
Duckling/Ordinal/DE/Corpus.hs
|
bsd-3-clause
| 905
| 0
| 8
| 205
| 165
| 103
| 62
| 24
| 1
|
{-# LANGUAGE TemplateHaskell #-}
module BoolExpr.ROBDD_TH
( compile
, compileE
) where
import Data.Bimap (assocs)
import Language.Haskell.TH
import BoolExpr.BoolExpr (BoolExpr, numVars)
import BoolExpr.Env (VarId)
import BoolExpr.ROBDD (NodeId, Ref (..), NodeAttr)
import qualified BoolExpr.ROBDD as ROBDD (build)
-- TH naming scheme for the node variables.
nodeName :: NodeId -> Name
nodeName u = mkName $ "n_" ++ (show u)
-- Map a ROBDD.Ref to either a boolean literal or a node variable.
mkRefExp :: Ref -> ExpQ
mkRefExp (Val b) = [| b |]
mkRefExp (Ptr u) = varE $ nodeName u
-- Compile a boolean expression into a TH expression of the form:
-- @{ \ x_0 x_1 x_2 x_3
-- -> let
-- n_5 = if x_3 then n_3 else n_4
-- n_4 = if x_2 then False else n_2
-- n_3 = if x_2 then n_2 else False
-- n_2 = if x_1 then n_0 else n_1
-- n_1 = if x_0 then False else True
-- n_0 = if x_0 then True else False
-- in n_5 }
compile :: BoolExpr -> ExpQ
compile expr =
let (ref, refmap) = ROBDD.build expr
decs = map mkNodeDec (assocs refmap)
letExp = letE decs $ mkRefExp ref
exprSize = numVars expr
varNums = take exprSize [0..]
lamPat = map (varP . varName) $ varNums
in if exprSize == 0 then letExp else lamE lamPat letExp
where -- TH naming scheme for the boolean expression variables.
varName :: VarId -> Name
varName i = mkName $ "x_" ++ (show i)
-- Map a node of the ROBDD to a TH declaration of the form:
-- @{ n_3 = if x_2 then n_2 else False }
mkNodeDec :: (NodeId, NodeAttr) -> DecQ
mkNodeDec (u, (i, nₗ, nᵣ)) =
let iteExp = condE (varE $ varName i) (mkRefExp nₗ) (mkRefExp nᵣ)
in valD (varP $ nodeName u) (normalB iteExp) []
-- Compile a boolean expression into a TH expression of the form:
-- @{ \ i2b
-- -> let
-- n_5 = if i2b 3 then n_3 else n_4
-- n_4 = if i2b 2 then False else n_2
-- n_3 = if i2b 2 then n_2 else False
-- n_2 = if i2b 1 then n_0 else n_1
-- n_1 = if i2b 0 then False else True
-- n_0 = if i2b 0 then True else False
-- in n_5 }
compileE :: BoolExpr -> ExpQ
compileE expr =
let (ref, refmap) = ROBDD.build expr
decs = map mkNodeDec (assocs refmap)
letExp = letE decs $ mkRefExp ref
in lamE [varP $ mkName "i2b"] letExp
where -- Lookup a boolean with the `i2b` function parameter.
mkLookup :: VarId -> ExpQ
mkLookup i = appE (varE $ mkName "i2b") (litE $ intPrimL (toInteger i))
-- Map a node of the ROBDD to a TH declaration of the form:
-- @{ n_3 = if i2b 2 then n_2 else False }
mkNodeDec :: (NodeId, NodeAttr) -> DecQ
mkNodeDec (u, (i, nₗ, nᵣ)) =
let iteExp = condE (mkLookup i) (mkRefExp nₗ) (mkRefExp nᵣ)
in valD (varP $ nodeName u) (normalB iteExp) []
|
robrene/robdd-with-template-hs
|
src/BoolExpr/ROBDD_TH.hs
|
bsd-3-clause
| 2,941
| 29
| 11
| 863
| 685
| 384
| 301
| 42
| 2
|
{-# LANGUAGE DeriveGeneric #-}
-- |
-- The AST definition for the language
module Language.Pureli.AST where
import qualified Data.Map as M
import qualified Text.Parsec.Pos as P (SourcePos, newPos)
import System.IO as IO (FilePath)
import Control.DeepSeq (NFData, rnf)
import GHC.Generics (Generic)
------------------
-- definitions
------------------
-- |
-- a possible repl expression
data ReqDefExp
= Req Require
| Def (Name, WithMD Expr)
| Exp (WithMD Expr)
-- |a definition of a module read from parser
data ModuleDef = ModuleDef
{ modFile :: IO.FilePath
, modName :: Name
, modExposes :: Maybe [Name]
, modRequires :: [Require]
, modDefs :: [(Name, WithMD Expr)]
}
-- |
-- A module definition and environment, created from ModuleDef
data Module = Module
{ getModFile :: IO.FilePath
, getModName :: Name
, getModImports :: [Module]
, getModExports :: Env
, getModEnv :: Env
} deriving (Eq, Generic)
-- |
-- A require for a module.
data Require
= Require FilePath Name (Maybe Name) (Maybe [Name])
deriving (Show, Eq, Ord)
-- |
-- An environment for the interpreter.
-- used to find binded names and expression which were bound with let, letrec, let!, define or defmacro
type Env
= M.Map Name (WithMD Expr)
-- |
-- metadata, current holds the position in the interpreted file
type Metadata
= P.SourcePos
-- |
-- creates an empty metadata
emptyMeta :: Metadata
emptyMeta = P.newPos "Main" 0 0
-- |
-- holds metadata on the type
data WithMD a
= WithMD Metadata a
deriving (Eq, Generic)
-- |
-- remove metadata
stripMD :: WithMD a -> a
stripMD (WithMD _ x) = x
-- |
-- an alias for String
type Name = String
-- |
-- a function with the environment it had when interpreted - for lexical scoping
data Closure
= Closure Module (WithMD Fun)
deriving (Eq)
-- |
-- a function is a list of argument names, maybe an additional 'rest' argument and a body
data Fun
= Fun FunArgs Expr
deriving (Eq)
-- |
-- arguments for a function
-- either it is a list of names arguments can be bind to on by one and a maybe a rest name to bind rest
-- or a name to bind all arguments in a list
data FunArgs
= FunArgs [Name] (Maybe Name)
| FunArgsList Name
deriving (Eq)
-- |
-- the main expression for our language
data Expr
= LIST [WithMD Expr] -- ^a list of expressions
| QUOTE (WithMD Expr) -- ^quoted expression
| ATOM Atom -- ^a primitive expression
| PROCEDURE Closure -- ^a procedure - a closure
| ENVEXPR Module (WithMD Expr) -- ^an expression with an environment
| STOREENV (WithMD Expr) -- ^converts to ENVEXPR with current module
| IOResult (WithMD Expr) -- ^a return value of an IO action
deriving (Eq, Generic)
-- |
-- primitives of the language
data Atom
= Integer Integer
| Real Double
| Symbol Name
| Keyword Name
| String String
| Bool Bool
| Nil
deriving (Eq, Ord, Generic)
-- |
-- defines how to call elements in modules syntactically
moduleSplitter :: Char
moduleSplitter = '/'
----------------
-- instances
----------------
instance NFData Expr where rnf x = seq x ()
instance NFData Atom where rnf x = seq x ()
instance NFData (WithMD a) where rnf x = seq x ()
-- |
-- map a function on the underline type, keeps the metadata
instance Functor WithMD where
fmap f (WithMD md x) = WithMD md $ f x
|
soupi/pureli
|
src/Language/Pureli/AST.hs
|
bsd-3-clause
| 3,411
| 0
| 11
| 793
| 747
| 443
| 304
| 74
| 1
|
module WithLBS where
import Network.Wai.Util
import Test.HUnit
import Control.Concurrent.MVar
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy as L
import Data.Enumerator (($$))
import qualified Data.Enumerator as E
import qualified Data.Enumerator.Binary as E
src = map B8.pack [show i | i <- [0 .. 10000]]
out = L.fromChunks src
withLBSTester f = do
let enum = E.enumList 2 src
E.run_ (enum $$ withLBS f)
fromRight def (Left _) = def
fromRight _ (Right r) = r
testWithLBS = test [
"withLBS complete" ~: do
res <- withLBSTester $ \lbs ->
return $ lbs == out
assert $ fromRight False res
, "withLBS parital" ~: do
res <- withLBSTester $ \lbs -> do
return $ "0" == (B8.unpack $ head $ L.toChunks lbs)
assert $ fromRight False res
]
|
softmechanics/wai-utils
|
test/WithLBS.hs
|
bsd-3-clause
| 827
| 0
| 19
| 189
| 299
| 162
| 137
| 25
| 1
|
module Data.JSON.TokenStream.Token
( Tokens (..)
, Encoding (..)
, encodeInt
, encodeDouble
, encodeText
, encodeString
, encodeBool
, encodeKey
, encodeKeyString
, encodeNull
, encodeComma
, encodeListEmpty
, encodeListBegin
, encodeListEnd
, encodeObjectEmpty
, encodeObjectBegin
, encodeObjectEnd
) where
import Data.Text (Text)
newtype Encoding = Encoding (Tokens -> Tokens)
data Tokens
= TkInt {-# UNPACK #-} !Int Tokens -- Scientific?
| TkDouble {-# UNPACK #-} !Double Tokens -- same
| TkString {-# UNPACK #-} !String Tokens
| TkText {-# UNPACK #-} !Text Tokens
| TkBool !Bool Tokens
| TkKey {-# UNPACK #-} !Text Tokens
| TkKeyString {-# UNPACK #-} !String Tokens
| TkNull Tokens
| TkComma Tokens
| TkListEmpty Tokens
| TkListBegin Tokens
| TkListEnd Tokens
| TkObjectEmpty Tokens
| TkObjectBegin Tokens
| TkObjectEnd Tokens
| TkEnd
deriving (Eq, Ord, Show)
instance Monoid Encoding where
mempty = Encoding (\ts -> ts)
{-# INLINE mempty #-}
Encoding b1 `mappend` Encoding b2 = Encoding (\ts -> b1 (b2 ts))
{-# INLINE mappend #-}
mconcat = foldr mappend mempty
{-# INLINE mconcat #-}
encodeInt :: Int -> Encoding
encodeInt = Encoding . TkInt
encodeDouble :: Double -> Encoding
encodeDouble = Encoding . TkDouble
encodeText :: Text -> Encoding
encodeText = Encoding . TkText
encodeString :: String -> Encoding
encodeString = Encoding . TkString
encodeBool :: Bool -> Encoding
encodeBool = Encoding . TkBool
encodeKey :: Text -> Encoding
encodeKey = Encoding . TkKey
encodeKeyString :: String -> Encoding
encodeKeyString = Encoding . TkKeyString
encodeNull :: Encoding
encodeNull = Encoding TkNull
encodeComma :: Encoding
encodeComma = Encoding TkComma
encodeListEmpty :: Encoding
encodeListEmpty = Encoding TkListEmpty
encodeListBegin :: Encoding
encodeListBegin = Encoding TkListBegin
encodeListEnd :: Encoding
encodeListEnd = Encoding TkListEnd
encodeObjectEmpty :: Encoding
encodeObjectEmpty = Encoding TkObjectEmpty
encodeObjectBegin :: Encoding
encodeObjectBegin = Encoding TkObjectBegin
encodeObjectEnd :: Encoding
encodeObjectEnd = Encoding TkObjectEnd
|
sopvop/json-token-stream
|
src/Data/JSON/TokenStream/Token.hs
|
bsd-3-clause
| 2,452
| 0
| 11
| 685
| 526
| 300
| 226
| 77
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
module Transient.EVars where
import Transient.Internals
import Data.Typeable
import Control.Applicative
import Control.Concurrent.STM
import Control.Monad.State
data EVar a= EVar (TChan (StreamData a)) deriving Typeable
-- | creates an EVar.
--
-- Evars are event vars. `writeEVar` trigger the execution of all the continuations associated to the `readEVar` of this variable
-- (the code that is after them).
--
-- It is like the publish-subscribe pattern but without inversion of control, since a readEVar can be inserted at any place in the
-- Transient flow.
--
-- EVars are created upstream and can be used to communicate two sub-threads of the monad. Following the Transient philosophy they
-- do not block his own thread if used with alternative operators, unlike the IORefs and TVars. And unlike STM vars, that are composable,
-- they wait for their respective events, while TVars execute the whole expression when any variable is modified.
--
-- The execution continues after the writeEVar when all subscribers have been executed.
--
-- Now the continuations are executed in parallel.
--
-- see https://www.fpcomplete.com/user/agocorona/publish-subscribe-variables-transient-effects-v
--
newEVar :: TransIO (EVar a)
newEVar = Transient $ do
ref <-liftIO newBroadcastTChanIO
return . Just $ EVar ref
-- | delete al the subscriptions for an evar.
cleanEVar :: EVar a -> TransIO ()
cleanEVar (EVar ref1)= liftIO $ atomically $ writeTChan ref1 SDone
-- | read the EVar. It only succeed when the EVar is being updated
-- The continuation gets registered to be executed whenever the variable is updated.
--
-- if readEVar is re-executed in any kind of loop, since each continuation is different, this will register
-- again. The effect is that the continuation will be executed multiple times
-- To avoid multiple registrations, use `cleanEVar`
readEVar :: EVar a -> TransIO a
readEVar (EVar ref1)= do
tchan <- liftIO . atomically $ dupTChan ref1
r <- parallel $ atomically $ readTChan tchan
case r of
SDone -> empty
SMore x -> return x
SLast x -> return x
SError e -> empty
-- error $ "readEVar: "++ show e
-- | update the EVar and execute all readEVar blocks with "last in-first out" priority
--
writeEVar :: EVar a -> a -> TransIO ()
writeEVar (EVar ref1) x= liftIO $ atomically $ do
writeTChan ref1 $ SMore x
-- | write the EVar and drop all the `readEVar` handlers.
--
-- It is like a combination of `writeEVar` and `cleanEVar`
lastWriteEVar (EVar ref1) x= liftIO $ atomically $ do
writeTChan ref1 $ SLast x
|
transient-haskell/transient
|
src/Transient/EVars.hs
|
mit
| 2,668
| 0
| 10
| 535
| 387
| 204
| 183
| 28
| 4
|
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE IncoherentInstances #-}
module ALaCarte where
-- References:
-- "W. Swierstra; Data types a la carte"
-- <http://www.cs.ru.nl/~W.Swierstra/Publications/DataTypesALaCarte.pdf>
--
-- > The goal is to define a data type by cases, where one can add new cases to the data type
-- > and new functions over the data type, without recompiling existing code, and while retaining static type safety
-- 'The expression problem' (Wadler, 1998)
import Fix
data Expr' = Val' Int | Add' Expr' Expr'
eval' :: Expr' -> Int
eval' (Val' x) = x
eval' (Add' e e') = eval' e + eval' e'
render' :: Expr' -> String
render' (Val' x) = show x
render' (Add' e e') = "(" ++ render' e ++ " + " ++ render' e' ++ ")"
data Val e = Val Int
type IntExpr = Fix Val
data Add e = Add e e
type AddExpr = Fix Add
-- > The big challenge, of course, is to combine the ValExpr and AddExpr
-- > types somehow. The key idea is to combine expressions by taking the
-- > coproduct of their signatures
data (f :+: g) e = Inl (f e) | Inr (g e)
infixr 5 :+:
addExample :: Fix (Val :+: Add)
addExample = Fix (Inr (Add (Fix (Inl (Val 2))) (Fix (Inl (Val 3)))))
instance Functor Val where
fmap f (Val x) = Val x
instance Functor Add where
fmap f (Add e e') = Add (f e) (f e')
instance (Functor f, Functor g) => Functor (f :+: g) where
fmap f (Inl e) = Inl (fmap f e)
fmap f (Inr e) = Inr (fmap f e)
class Functor f => Eval f where
evalAlg :: f Int -> Int
instance Eval Val where
evalAlg (Val x) = x
instance Eval Add where
evalAlg (Add x y) = x + y
instance (Eval f, Eval g) => Eval (f :+: g) where
evalAlg (Inl x) = evalAlg x
evalAlg (Inr x) = evalAlg x
eval :: Eval f => Fix f -> Int
eval = cata evalAlg
-- > The definition of addExample illustrates how messy expressions can easily
-- > become. In this section, we remedy the situation by introducing smart
-- > constructors for addition and values.
class (Functor sub, Functor sup) => sub :<: sup where
inj :: sub a -> sup a
instance Functor f => f :<: f where
inj = id
instance (Functor f, Functor g) => f :<: (f :+: g) where
inj = Inl
instance (Functor f, Functor g, Functor h, f :<: g) => f :<: (h :+: g) where
inj = Inr . inj
inject :: (g :<: f) => g (Fix f) -> Fix f
inject = Fix . inj
val :: (Val :<: f) => Int -> Fix f
val x = inject (Val x)
(<+>) :: (Add :<: f) => Fix f -> Fix f -> Fix f
x <+> y = inject (Add x y)
infixl 6 <+>
-- > The type signature of x is very important! We exploit the type signature to
-- > figure out the injection into a coproduct: if we fail to provide the type
-- > signature, a compiler has no hope whatsoever of guessing the right injection
expression :: Fix (Add :+: Val)
expression = (val 30000) <+> (val 200)
-- Now lets add more constructors, e.g. multiplication!
data Mul x = Mul x x
instance Functor Mul where
fmap f (Mul e e') = Mul (f e) (f e')
instance Eval Mul where
evalAlg (Mul x y) = x * y
(<#>) :: (Mul :<: f) => Fix f -> Fix f -> Fix f
x <#> y = inject (Mul x y)
infixl 7 <#>
expression2 :: Fix (Val :+: Add :+: Mul)
expression2 = (val 30000) <+> (val 200) <#> (val 300)
-- Lets add more functionality!
-- for example pretty printing
--
-- NOTE: this differs from the implementation in the paper, but I think
-- expressing it as an algebra is nicer
class Functor f => Render f where
render :: f String -> String
pretty :: Render f => Fix f -> String
pretty = cata render
instance Render Val where
render (Val x) = show x
instance Render Add where
render (Add e e') = "(" ++ e ++ " + " ++ e' ++ ")"
instance Render Mul where
render (Mul e e') = "(" ++ e ++ " * " ++ e' ++ ")"
instance (Render f, Render g) => Render (f :+: g) where
render (Inl x) = render x
render (Inr y) = render y
-- Testing environment
main = do
let e = (Add' (Val' 5) (Val' 1))
print $ render' e
print $ eval' e
print $ eval expression
print $ eval expression2
print $ pretty expression2
|
jwbuurlage/category-theory-programmers
|
examples/catamorphisms/ALaCarte.hs
|
mit
| 4,118
| 7
| 16
| 976
| 1,454
| 747
| 707
| 87
| 1
|
-----------------------------------------------------------------------------
--
-- Module : Cell
-- Copyright :
-- License : MIT
--
-- Maintainer : agocorona@gmail.com
-- Stability : experimental
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, OverloadedStrings, CPP, ScopedTypeVariables #-}
module GHCJS.HPlay.Cell(Cell(..),boxCell,bcell,(.=),get,mkscell,scell, gcell, calc) where
import Transient.Internals
import Transient.Move --hiding (JSString)
import GHCJS.HPlay.View
import Data.Typeable
import Unsafe.Coerce
import qualified Data.Map as M hiding ((!))
import Control.Monad.State hiding (get)
import Control.Monad
import Data.Monoid
import Data.List
import Control.Exception
import Data.IORef
import System.IO.Unsafe
#ifdef ghcjs_HOST_OS
import Data.JSString hiding (empty)
#else
-- type JSString = String
#endif
data Cell a = Cell { mk :: Maybe a -> Widget a
, setter :: a -> IO ()
, getter :: IO (Maybe a)}
--instance Functor Cell where
-- fmap f cell = cell{setter= \c x -> c .= f x, getter = \cell -> get cell >>= return . f}
-- | creates (but not instantiates) an input box that has a setter and a getter. To instantiate it us his method `mk`
bcell :: (Show a, Read a, Typeable a) =>TransIO (Cell a)
bcell= genNewId >>= return . boxCell
-- | creates (but not instantiates) a input box cell with polimorphic value, identified by a string.
-- the cell has a getter and a setter. To instantiate it us his method `mk`
boxCell :: (Show a, Read a, Typeable a) => ElemID -> Cell a
boxCell id = Cell{ mk= \mv -> getParam (Just id) "text" mv
, setter= \x -> do
me <- elemById id
case me of
Just e -> setProp e "value" (toJSString $ show1 x)
Nothing -> return ()
, getter= getID id}
getID id = withElem id $ \e -> do
ms <- getValue e
case ms of
Nothing -> return Nothing
Just s -> return $ read1 s
where
read1 s=
if typeOf(typeIO getID) /= typestring
then case readsPrec 0 s of
[(v,_)] -> v `seq` Just v
_ -> Nothing
else Just $ unsafeCoerce s
typeIO :: (ElemID -> IO (Maybe a)) -> a
typeIO = undefined
typestring :: TypeRep
typestring= typeOf (undefined :: String)
show1 :: (Show a, Typeable a) => a -> String
show1 x= if typeOf x== typestring
then unsafeCoerce x
else show x
instance Attributable (Cell a) where
(Cell mk setter getter) ! atr = Cell (\ma -> mk ma ! atr) setter getter
-- | Cell assignment using the cell setter
(.=) :: MonadIO m => Cell a -> a -> m ()
(.=) cell x = liftIO $ (setter cell ) x
get cell = Transient $ liftIO (getter cell)
---- | a cell value assigned to other cell
--(..=) :: Cell a -> Cell a -> Widget ()
--(..=) cell cell'= get cell' >>= (cell .= )
infixr 0 .= -- , ..=
-- experimental: to permit cell arithmetic
--instance Num a => Num (Cell a) where
-- c + c'= Cell undefined undefined $
-- do r1 <- getter c
-- r2 <- getter c'
-- return $ liftA2 (+) r1 r2
--
-- c * c'= Cell undefined undefined $
-- do r1 <- getter c
-- r2 <- getter c'
-- return $ liftA2 (+) r1 r2
--
-- abs c= c{getter= getter c >>= return . fmap abs}
--
-- signum c= c{getter= getter c >>= return . fmap signum}
--
-- fromInteger i= Cell undefined undefined . return $ Just $ fromInteger i
-- * Spradsheet type cells
-- Implement a solver that allows circular dependencies . See
-- > http://tryplayg.herokuapp.com/try/spreadsheet.hs/edit
-- The recursive Cell calculation DSL BELOW ------
-- | within a `mkscell` formula, `gcell` get the the value of another cell using his name.
--
-- see http://tryplayg.herokuapp.com/try/spreadsheet.hs/edit
gcell :: JSString -> Cloud Double
gcell n= loggedc $ do
-- onAll $ do
-- cutExceptions
-- reportBack
vars <- getCloudState rvars <|> return M.empty -- liftIO $ readIORef rvars
localIO $ print ("gcell", n)
case M.lookup n vars of
Just exp -> do inc ; exp !> "executing exp"
Nothing -> error $ "cell not found: " ++ show n
where
inc = do
Tries tries maxtries <- getCloudState rtries <|> error "no tries" --do
-- Exprs exprs <- getCloudState
-- return . Tries 0 $ 3 * (M.size $ exprs)
localIO $ print tries
if tries <= maxtries
then localIO $ writeIORef rtries $ Tries (tries+1) maxtries
else local $ do
-- liftIO $ print "back"
back Loop
data Loop= Loop deriving (Show,Typeable)
instance Exception Loop
-- a parameter is a function of all of the rest
type Expr a = Cloud a
data Tries= Tries Int Int deriving Typeable
rtries= unsafePerformIO $ newIORef $ Tries 0 0
--maxtries= 3 * (M.size $ unsafePerformIO $ readIORef rexprs)
-- newtype Exprs= Exprs (M.Map JSString (Expr Double))
rexprs :: IORef (M.Map JSString (Expr Double))
rexprs= unsafePerformIO $ newIORef M.empty -- initial expressions
-- newtype Vars= Vars (M.Map JSString (Expr Double))
rvars :: IORef (M.Map JSString (Expr Double))
rvars= unsafePerformIO $ newIORef M.empty -- expressions actually used for each cell.
-- initially, A mix of reexprs and rmodified
-- and also contains the result of calculation
-- newtype Modified= Modified (M.Map JSString (Expr Double)) deriving Typeable
rmodified :: IORef (M.Map JSString ( Double))
rmodified= unsafePerformIO $ newIORef M.empty -- cells modified by the user or by the loop detection mechanism
-- | make a spreadsheet cell. a spreadsheet cell is an input-output box that takes input values from
-- the user, has an expression associated and display the result value after executing `calc`
--
-- see http://tryplayg.herokuapp.com/try/spreadsheet.hs/edit
mkscell :: JSString -> Expr Double -> Cloud (Cell Double)
mkscell name expr= do
exprs <- onAll $ liftIO (readIORef rexprs) <|> return ( M.empty) -- readIORef rexprs
onAll $ liftIO $ writeIORef rexprs $ M.insert name expr exprs
return $ scell name expr
scell :: JSString -> Expr Double -> Cell Double
scell id expr= Cell{ mk= \mv -> Widget $ do
r <- norender $ getParam (Just id) "text" mv `fire` OnChange
mod <- liftIO (readIORef rmodified) <|> return( M.empty)
liftIO $ writeIORef rmodified $ M.insert id r mod
return r
, setter= \x -> withElem id $ \e -> setProp e "value" (toJSString $ show1 x)
, getter= getID id}
-- | executes the spreadsheet adjusting the vaules of the cells created with `mkscell` and solving loops
--
-- see http://tryplayg.herokuapp.com/try/spreadsheet.hs/edit
calc :: Cloud ()
calc= do
mod <- localIO $ readIORef rmodified
onAll $ liftIO $ print ("LENGTH MOD", M.size mod)
onAll $ liftIO $ print "setCloudState modified"
setCloudState rmodified mod
exprs <- getCloudState rexprs
onAll $ liftIO $ print "setCloudState exprs"
setCloudState rexprs exprs
onAll $ liftIO $ print "setCloudState rvars"
setCloudState rvars M.empty
onAll $ return() `onBack` (\(e::Loop) -> runCloud' $ do localIO $ print "REMOVEVAR"; removeVar e; local (forward Loop) )
exprs <- getCloudState rexprs <|> error "no exprs"
onAll $ liftIO $ print "setCloudState rtries"
setCloudState rtries $ Tries 0 $ 3 * (M.size $ exprs)
nvs <- getCloudState rmodified <|> error "no modified" -- liftIO $ readIORef rmodified
onAll $ liftIO $ print ("LENGTH NVS", M.size nvs)
when (not $ M.null nvs) $ calc1
--values <- calc1
--localIO $ print "NEW CALC"
--local $ mapM_ (\(n,v) -> boxCell n .= v) values
onAll $ liftIO $ print "setCloudState modified"
setCloudState rmodified M.empty
where
--calc1 :: Expr [(JSString,Double)]
calc1= do
return () !> "CALC1"
cells <- getCloudState rexprs <|> error "no exprs" -- liftIO $ readIORef rexprs
nvs <- getCloudState rmodified <|> error "no modified2" -- liftIO $ readIORef rmodified
onAll $ liftIO $ print "setCloudState vars"
setCloudState rvars $ M.union (M.map return nvs) cells
solve
--solve :: Expr [(JSString,Double)]
solve = do
vars <- getCloudState rvars <|> error "no vars" -- liftIO $ readIORef rvars
onAll $ liftIO $ print $ ("LENGHT VARS", M.size vars)
mapM_ (solve1 vars) $ M.toList vars
where
solve1 vars (k,f)= do
localIO $ print ("solve1",k)
x <- f
localIO $ print ("setcloudstate var",k,x)
local $ boxCell k .= x
setCloudState rvars $ M.insert k (return x) vars
return () -- (k,x) :: Expr (JSString,Double)
setCloudState r v= allNodes $ writeIORef r v
getCloudState r= onAll . liftIO $ readIORef r
-- removeVar ::SomeException -> IO () -- [(JSString,Double)]
removeVar = \(e:: Loop) -> do
nvs <- getCloudState rmodified <|> error "no modified 3"-- readIORef rmodified
-- mapM (\n -> snd n >>= \v -> localIO $ print (fst n,v)) $ M.toList nvs
exprs <- getCloudState rexprs <|> error " no Exprs2" --readIORef rexprs
case M.keys exprs \\ M.keys nvs of
[] -> error "non solvable circularity in cell dependencies"
(name:_) -> do
localIO $ print ("removeVar",name)
mv <- localIO $ getID name
case mv of
Nothing -> return ()
Just v -> do
onAll $ liftIO $ print "setCloudState modified"
setCloudState rmodified $ M.insert name v nvs
return ()
allNodes :: IO () -> Cloud ()
allNodes mx= loggedc $ (localIO mx) <> (atRemote $ (localIO $ print "UPDATE" >> mx))
--atBrowser mx= if isBrowserInstance then mx else atRemote mx
--atServer mx= if not isBrowserInstance then mx else atRemote mx
-- http://blog.sigfpe.com/2006/11/from-l-theorem-to-spreadsheet.html
-- loeb :: Functor f => f (t -> a) -> f a
-- loeb x = fmap (\a -> a (loeb x)) x
-- loeb :: [([a]-> a)] -> [a]
-- loeb x= map (\f -> f (loeb x)) x
--loeb :: [([a] -> IO a)] -> IO [a]
--loeb x= mapM (\f -> loeb x >>= f) x -- fail does not terminate
--loeb x= map (\f -> f (loeb x)) x
|
agocorona/ghcjs-hplay
|
src/GHCJS/HPlay/Cell.hs
|
mit
| 10,875
| 0
| 20
| 3,154
| 2,442
| 1,251
| 1,191
| 147
| 4
|
{- |
Module : ./Common/GraphAlgo.hs
Description : Algorithms on Graphs
Copyright : (c) Jonathan von Schroeder, DFKI Bremen 2012
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Jonathan von Schroeder <jonathan.von_schroeder@dfki.de>
Stability : provisional
Portability : portable
-}
module Common.GraphAlgo where
import qualified Data.Map as Map
import Data.Maybe (mapMaybe)
data Graph node edge = Graph {
neighbours :: node -> [(edge, node)],
weight :: edge -> Int
}
data Node = Node String deriving (Eq, Ord)
data Edge = Edge (String, String) deriving (Eq, Ord)
instance Show Node where
show (Node s) = s
instance Show Edge where
show (Edge (s1, s2)) = s1 ++ "," ++ s2
exampleGraph :: [(String, String)] -> Graph Node Edge
exampleGraph conns = Graph {
neighbours = \ n -> map (\ (s1, s2) -> (Edge (s1, s2), Node s2)) $
filter (\ (s, _) -> (Node s == n)) conns,
weight = const 1
}
mapMin :: (a -> a -> Bool) -> Map.Map k a -> Maybe (k, a)
mapMin less = Map.foldWithKey (\ k a b -> case b of
Just (_, a1) -> if less a1 a then b else Just (k, a)
Nothing -> Just (k, a)) Nothing
dijkstra :: (Show node, Show edge, Ord node) => node -> (node -> Bool)
-> Graph node edge -> Maybe ([(node, edge)], node)
dijkstra start isEnd (Graph neighbours_ weight_) =
let visited = snd $ adjust (Map.fromList [(start, (Nothing, 0))], Map.empty)
in case mapMin (\ (_, w1) (_, w2) -> w1 < w2) $
Map.filterWithKey (\ n _ -> isEnd n) visited of
Just (end, _) -> maybe Nothing (\ p -> Just (reverse p, end))
$ extractPath end visited
_ -> Nothing
where
adjust (known, visited) =
case mapMin (\ (_, w1) (_, w2) -> w1 < w2) known of
Just (n, d@(_, n_weight)) ->
let (known_, visited_) = (Map.delete n known,
Map.insert n d visited)
in if isEnd n then (known_, visited_)
else adjust $
foldl (\ (known', visited') (e, next_n) ->
case Map.lookup next_n visited' of
Just (_, w) -> (known', if n_weight + weight_ e < w then
Map.insert next_n (Just (n, e), n_weight + weight_ e)
visited' else visited')
Nothing -> (case Map.lookup next_n known' of
Just (_, w) -> if n_weight + weight_ e < w then
Map.insert next_n (Just (n, e), n_weight + weight_ e) known'
else known'
Nothing -> Map.insert next_n
(Just (n, e), n_weight + weight_ e) known', visited'))
(known_, visited_) (neighbours_ n)
Nothing -> (known, visited)
extractPath n visited = case Map.lookup n visited of
Just (Just (prev, e), _) -> case extractPath prev (Map.delete n visited) of
Just l -> Just $ (prev, e) : l
Nothing -> Nothing
Just (Nothing, _) -> Just []
Nothing -> Nothing
yen :: (Ord node, Eq edge, Show node, Show edge) => Int -> node -> (node -> Bool)
-> Graph node edge -> [([(node, edge)], node)]
yen k' start end g = case dijkstra start end g of
Just (shortest_path, end') -> map (\ p -> (p, end')) $ yen_ (k' - 1) [shortest_path]
Nothing -> []
where
yen_ k a = if k <= 0 then a
else let b = mapMaybe (yen' k a) [0 .. (length (a !! (k' - k - 1)) - 1)]
in case minPath b of
Just m -> yen_ (k - 1) $ a ++ [m]
Nothing -> a
yen' k a i =
let spurNode = fst $ (a !! (k' - k - 1)) !! i
rootPath = take i (a !! (k' - k - 1))
hide =
concatMap (\ p -> [p !! i | take i p == rootPath]) a
g' = g { neighbours = \ n -> filter (\ (e, _) -> notElem (n, e) hide) $
neighbours g n }
in case dijkstra spurNode end g' of
Just (spurPath, _) -> Just $ rootPath ++ spurPath
Nothing -> Nothing
minPath (p : ps) = case minPath ps of
Just m -> Just $ if pathLen p < pathLen m then p else m
Nothing -> Just p
minPath [] = Nothing
pathLen p = sum $ map (\ (_, e) -> (weight g e)) p
prettyPath :: (Show node, Show edge) => ([(node, edge)], node) -> String
prettyPath (p, last_node) =
let (nodes, edges) = unzip p
(nodes_s, edges_s) = (map show nodes,
map (\ e -> " =(" ++ show e ++ ")=> ") edges)
in foldl (\ s (n, e) -> s ++ n ++ e) "" (zip nodes_s edges_s) ++ show last_node
test_graph :: Graph Node Edge
test_graph = exampleGraph [("A", "B"), ("B", "C"), ("B", "E"), ("B", "D"), ("D", "E")]
test :: String
test = maybe "" prettyPath $
dijkstra (Node "A") ((==) $ Node "E") test_graph
test1 :: [[String]]
test1 = map (map prettyPath)
[yen i (Node "A") ((==) $ Node "E") test_graph | i <- [1 .. 3]]
|
spechub/Hets
|
Common/GraphAlgo.hs
|
gpl-2.0
| 4,760
| 0
| 28
| 1,454
| 2,127
| 1,145
| 982
| 95
| 11
|
{- |
Module : $Id: Modal.hs 13959 2010-08-31 22:15:26Z cprodescu $
Description : modal logic extension of CASL
Copyright : (c) Christian Maeder and Uni Bremen 2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : portable (except Modal.Logic_Modal)
This folder contains the files for ModalCASL basic specs
ModalCASL is the modal logic extension of CASL. See
/Heterogeneous specification and the heterogeneous tool set/
(<http://www.informatik.uni-bremen.de/~till/papers/habil.ps>), section 3.2.
The modules for ModalCASL largely are built on top of those for "CASL",
using the holes for future extensions that have been left in the
datatypes for CASL.
* "Modal.AS_Modal" abstract syntax
* "Modal.Parse_AS" parser
* "Modal.Print_AS" pretty printing
* "Modal.ModalSign" signatures
* "Modal.StatAna" static analysis
* "Modal.ModalSystems" recognition of various systems such as S4, S5 etc.
* "Modal.ATC_Modal" ATerm conversion
* "Modal.Logic_Modal" the ModalCASL instance of type class 'Logic.Logic.Logic'
-}
module Modal where
|
nevrenato/HetsAlloy
|
Modal.hs
|
gpl-2.0
| 1,154
| 0
| 2
| 206
| 5
| 4
| 1
| 1
| 0
|
module CO4
( module CO4.Compilation
, Config (..), Configs, configurable
, module CO4.Solve
, module CO4.Allocator
, module CO4.Encodeable
, encodedConstructor
, encCO4OVUndefinedCons, encCO4OVDefinedCons
)
where
import CO4.Frontend.TH ()
import CO4.Compilation
import CO4.Config (Config (..),Configs,configurable)
import CO4.Solve
import CO4.Allocator
import CO4.Encodeable
import CO4.EncodedAdt (encodedConstructor)
import CO4.Algorithms.UndefinedValues.Data (encCO4OVUndefinedCons,encCO4OVDefinedCons)
|
apunktbau/co4
|
src/CO4.hs
|
gpl-3.0
| 604
| 0
| 6
| 146
| 126
| 82
| 44
| 16
| 0
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.CloudWatchLogs.GetLogEvents
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves log events from the specified log stream. You can provide an
-- optional time range to filter the results on the event 'timestamp'.
--
-- By default, this operation returns as much log events as can fit in a
-- response size of 1MB, up to 10,000 log events. The response will always
-- include a 'nextForwardToken' and a 'nextBackwardToken' in the response
-- body. You can use any of these tokens in subsequent 'GetLogEvents'
-- requests to paginate through events in either forward or backward
-- direction. You can also limit the number of log events returned in the
-- response by specifying the 'limit' parameter in the request.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetLogEvents.html AWS API Reference> for GetLogEvents.
module Network.AWS.CloudWatchLogs.GetLogEvents
(
-- * Creating a Request
getLogEvents
, GetLogEvents
-- * Request Lenses
, gleStartTime
, gleStartFromHead
, gleNextToken
, gleEndTime
, gleLimit
, gleLogGroupName
, gleLogStreamName
-- * Destructuring the Response
, getLogEventsResponse
, GetLogEventsResponse
-- * Response Lenses
, glersNextBackwardToken
, glersNextForwardToken
, glersEvents
, glersResponseStatus
) where
import Network.AWS.CloudWatchLogs.Types
import Network.AWS.CloudWatchLogs.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'getLogEvents' smart constructor.
data GetLogEvents = GetLogEvents'
{ _gleStartTime :: !(Maybe Nat)
, _gleStartFromHead :: !(Maybe Bool)
, _gleNextToken :: !(Maybe Text)
, _gleEndTime :: !(Maybe Nat)
, _gleLimit :: !(Maybe Nat)
, _gleLogGroupName :: !Text
, _gleLogStreamName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GetLogEvents' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gleStartTime'
--
-- * 'gleStartFromHead'
--
-- * 'gleNextToken'
--
-- * 'gleEndTime'
--
-- * 'gleLimit'
--
-- * 'gleLogGroupName'
--
-- * 'gleLogStreamName'
getLogEvents
:: Text -- ^ 'gleLogGroupName'
-> Text -- ^ 'gleLogStreamName'
-> GetLogEvents
getLogEvents pLogGroupName_ pLogStreamName_ =
GetLogEvents'
{ _gleStartTime = Nothing
, _gleStartFromHead = Nothing
, _gleNextToken = Nothing
, _gleEndTime = Nothing
, _gleLimit = Nothing
, _gleLogGroupName = pLogGroupName_
, _gleLogStreamName = pLogStreamName_
}
-- | Undocumented member.
gleStartTime :: Lens' GetLogEvents (Maybe Natural)
gleStartTime = lens _gleStartTime (\ s a -> s{_gleStartTime = a}) . mapping _Nat;
-- | If set to true, the earliest log events would be returned first. The
-- default is false (the latest log events are returned first).
gleStartFromHead :: Lens' GetLogEvents (Maybe Bool)
gleStartFromHead = lens _gleStartFromHead (\ s a -> s{_gleStartFromHead = a});
-- | A string token used for pagination that points to the next page of
-- results. It must be a value obtained from the 'nextForwardToken' or
-- 'nextBackwardToken' fields in the response of the previous
-- 'GetLogEvents' request.
gleNextToken :: Lens' GetLogEvents (Maybe Text)
gleNextToken = lens _gleNextToken (\ s a -> s{_gleNextToken = a});
-- | Undocumented member.
gleEndTime :: Lens' GetLogEvents (Maybe Natural)
gleEndTime = lens _gleEndTime (\ s a -> s{_gleEndTime = a}) . mapping _Nat;
-- | The maximum number of log events returned in the response. If you don\'t
-- specify a value, the request would return as many log events as can fit
-- in a response size of 1MB, up to 10,000 log events.
gleLimit :: Lens' GetLogEvents (Maybe Natural)
gleLimit = lens _gleLimit (\ s a -> s{_gleLimit = a}) . mapping _Nat;
-- | The name of the log group to query.
gleLogGroupName :: Lens' GetLogEvents Text
gleLogGroupName = lens _gleLogGroupName (\ s a -> s{_gleLogGroupName = a});
-- | The name of the log stream to query.
gleLogStreamName :: Lens' GetLogEvents Text
gleLogStreamName = lens _gleLogStreamName (\ s a -> s{_gleLogStreamName = a});
instance AWSRequest GetLogEvents where
type Rs GetLogEvents = GetLogEventsResponse
request = postJSON cloudWatchLogs
response
= receiveJSON
(\ s h x ->
GetLogEventsResponse' <$>
(x .?> "nextBackwardToken") <*>
(x .?> "nextForwardToken")
<*> (x .?> "events" .!@ mempty)
<*> (pure (fromEnum s)))
instance ToHeaders GetLogEvents where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("Logs_20140328.GetLogEvents" :: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON GetLogEvents where
toJSON GetLogEvents'{..}
= object
(catMaybes
[("startTime" .=) <$> _gleStartTime,
("startFromHead" .=) <$> _gleStartFromHead,
("nextToken" .=) <$> _gleNextToken,
("endTime" .=) <$> _gleEndTime,
("limit" .=) <$> _gleLimit,
Just ("logGroupName" .= _gleLogGroupName),
Just ("logStreamName" .= _gleLogStreamName)])
instance ToPath GetLogEvents where
toPath = const "/"
instance ToQuery GetLogEvents where
toQuery = const mempty
-- | /See:/ 'getLogEventsResponse' smart constructor.
data GetLogEventsResponse = GetLogEventsResponse'
{ _glersNextBackwardToken :: !(Maybe Text)
, _glersNextForwardToken :: !(Maybe Text)
, _glersEvents :: !(Maybe [OutputLogEvent])
, _glersResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GetLogEventsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'glersNextBackwardToken'
--
-- * 'glersNextForwardToken'
--
-- * 'glersEvents'
--
-- * 'glersResponseStatus'
getLogEventsResponse
:: Int -- ^ 'glersResponseStatus'
-> GetLogEventsResponse
getLogEventsResponse pResponseStatus_ =
GetLogEventsResponse'
{ _glersNextBackwardToken = Nothing
, _glersNextForwardToken = Nothing
, _glersEvents = Nothing
, _glersResponseStatus = pResponseStatus_
}
-- | Undocumented member.
glersNextBackwardToken :: Lens' GetLogEventsResponse (Maybe Text)
glersNextBackwardToken = lens _glersNextBackwardToken (\ s a -> s{_glersNextBackwardToken = a});
-- | Undocumented member.
glersNextForwardToken :: Lens' GetLogEventsResponse (Maybe Text)
glersNextForwardToken = lens _glersNextForwardToken (\ s a -> s{_glersNextForwardToken = a});
-- | Undocumented member.
glersEvents :: Lens' GetLogEventsResponse [OutputLogEvent]
glersEvents = lens _glersEvents (\ s a -> s{_glersEvents = a}) . _Default . _Coerce;
-- | The response status code.
glersResponseStatus :: Lens' GetLogEventsResponse Int
glersResponseStatus = lens _glersResponseStatus (\ s a -> s{_glersResponseStatus = a});
|
fmapfmapfmap/amazonka
|
amazonka-cloudwatch-logs/gen/Network/AWS/CloudWatchLogs/GetLogEvents.hs
|
mpl-2.0
| 7,968
| 0
| 14
| 1,770
| 1,274
| 755
| 519
| 145
| 1
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="tr-TR">
<title>Forced Browse Add-On</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/bruteforce/src/main/javahelp/org/zaproxy/zap/extension/bruteforce/resources/help_tr_TR/helpset_tr_TR.hs
|
apache-2.0
| 966
| 79
| 67
| 158
| 415
| 210
| 205
| -1
| -1
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
-- | Generate HPC (Haskell Program Coverage) reports
module Stack.Coverage
( deleteHpcReports
, updateTixFile
, generateHpcReport
, HpcReportOpts(..)
, generateHpcReportForTargets
, generateHpcUnifiedReport
, generateHpcMarkupIndex
) where
import Control.Applicative
import Control.Exception.Enclosed (handleIO)
import Control.Exception.Lifted
import Control.Monad (liftM, when, unless, void, (<=<))
import Control.Monad.Catch (MonadMask)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Resource
import qualified Data.ByteString.Char8 as S8
import Data.Foldable (forM_, asum, toList)
import Data.Function
import Data.List
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Maybe.Extra (mapMaybeM)
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as LT
import Data.Traversable (forM)
import Path
import Path.Extra (toFilePathNoTrailingSep)
import Path.IO
import Prelude hiding (FilePath, writeFile)
import Stack.Build.Source (parseTargetsFromBuildOpts)
import Stack.Build.Target
import Stack.Constants
import Stack.Package
import Stack.Types.PackageIdentifier
import Stack.Types.PackageName
import Stack.Types.Version
import Stack.Types.Config
import Stack.Types.Package
import Stack.Types.Compiler
import System.FilePath (isPathSeparator)
import System.Process.Read
import Text.Hastache (htmlEscape)
import Trace.Hpc.Tix
-- | Invoked at the beginning of running with "--coverage"
deleteHpcReports :: (MonadIO m, MonadMask m, MonadReader env m, HasEnvConfig env)
=> m ()
deleteHpcReports = do
hpcDir <- hpcReportDir
ignoringAbsence (removeDirRecur hpcDir)
-- | Move a tix file into a sub-directory of the hpc report directory. Deletes the old one if one is
-- present.
updateTixFile :: (MonadIO m,MonadReader env m,MonadLogger m,MonadBaseControl IO m,MonadMask m,HasEnvConfig env)
=> PackageName -> Path Abs File -> String -> m ()
updateTixFile pkgName tixSrc testName = do
exists <- doesFileExist tixSrc
when exists $ do
tixDest <- tixFilePath pkgName testName
ignoringAbsence (removeFile tixDest)
ensureDir (parent tixDest)
-- Remove exe modules because they are problematic. This could be revisited if there's a GHC
-- version that fixes https://ghc.haskell.org/trac/ghc/ticket/1853
mtix <- readTixOrLog tixSrc
case mtix of
Nothing -> $logError $ "Failed to read " <> T.pack (toFilePath tixSrc)
Just tix -> do
liftIO $ writeTix (toFilePath tixDest) (removeExeModules tix)
-- TODO: ideally we'd do a file move, but IIRC this can
-- have problems. Something about moving between drives
-- on windows?
copyFile tixSrc =<< parseAbsFile (toFilePath tixDest ++ ".premunging")
ignoringAbsence (removeFile tixSrc)
-- | Get the directory used for hpc reports for the given pkgId.
hpcPkgPath :: (MonadIO m,MonadReader env m,MonadMask m,HasEnvConfig env)
=> PackageName -> m (Path Abs Dir)
hpcPkgPath pkgName = do
outputDir <- hpcReportDir
pkgNameRel <- parseRelDir (packageNameString pkgName)
return (outputDir </> pkgNameRel)
-- | Get the tix file location, given the name of the file (without extension), and the package
-- identifier string.
tixFilePath :: (MonadIO m,MonadReader env m,MonadMask m,HasEnvConfig env)
=> PackageName -> String -> m (Path Abs File)
tixFilePath pkgName testName = do
pkgPath <- hpcPkgPath pkgName
tixRel <- parseRelFile (testName ++ "/" ++ testName ++ ".tix")
return (pkgPath </> tixRel)
-- | Generates the HTML coverage report and shows a textual coverage summary for a package.
generateHpcReport :: (MonadIO m,MonadReader env m,MonadLogger m,MonadBaseControl IO m,MonadMask m,HasEnvConfig env)
=> Path Abs Dir -> Package -> [Text] -> m ()
generateHpcReport pkgDir package tests = do
compilerVersion <- asks (envConfigCompilerVersion . getEnvConfig)
-- If we're using > GHC 7.10, the hpc 'include' parameter must specify a ghc package key. See
-- https://github.com/commercialhaskell/stack/issues/785
let pkgName = packageNameText (packageName package)
pkgId = packageIdentifierString (packageIdentifier package)
ghcVersion = getGhcVersion compilerVersion
eincludeName <-
-- Pre-7.8 uses plain PKG-version in tix files.
if ghcVersion < $(mkVersion "7.10") then return $ Right $ Just pkgId
-- We don't expect to find a package key if there is no library.
else if not (packageHasLibrary package) then return $ Right Nothing
-- Look in the inplace DB for the package key.
-- See https://github.com/commercialhaskell/stack/issues/1181#issuecomment-148968986
else do
-- GHC 8.0 uses package id instead of package key.
-- See https://github.com/commercialhaskell/stack/issues/2424
let hpcNameField = if ghcVersion >= $(mkVersion "8.0") then "id" else "key"
eincludeName <- findPackageFieldForBuiltPackage pkgDir (packageIdentifier package) hpcNameField
case eincludeName of
Left err -> do
$logError err
return $ Left err
Right includeName -> return $ Right $ Just $ T.unpack includeName
forM_ tests $ \testName -> do
tixSrc <- tixFilePath (packageName package) (T.unpack testName)
let report = "coverage report for " <> pkgName <> "'s test-suite \"" <> testName <> "\""
reportDir = parent tixSrc
case eincludeName of
Left err -> generateHpcErrorReport reportDir (sanitize (T.unpack err))
-- Restrict to just the current library code, if there is a library in the package (see
-- #634 - this will likely be customizable in the future)
Right mincludeName -> do
let extraArgs = case mincludeName of
Just includeName -> ["--include", includeName ++ ":"]
Nothing -> []
generateHpcReportInternal tixSrc reportDir report extraArgs extraArgs
generateHpcReportInternal :: (MonadIO m,MonadReader env m,MonadLogger m,MonadBaseControl IO m,MonadMask m,HasEnvConfig env)
=> Path Abs File -> Path Abs Dir -> Text -> [String] -> [String] -> m ()
generateHpcReportInternal tixSrc reportDir report extraMarkupArgs extraReportArgs = do
-- If a .tix file exists, move it to the HPC output directory and generate a report for it.
tixFileExists <- doesFileExist tixSrc
if not tixFileExists
then $logError $ T.concat
[ "Didn't find .tix for "
, report
, " - expected to find it at "
, T.pack (toFilePath tixSrc)
, "."
]
else (`catch` \err -> do
let msg = show (err :: ReadProcessException)
$logError (T.pack msg)
generateHpcErrorReport reportDir $ sanitize msg) $
(`onException` $logError ("Error occurred while producing " <> report)) $ do
-- Directories for .mix files.
hpcRelDir <- hpcRelativeDir
-- Compute arguments used for both "hpc markup" and "hpc report".
pkgDirs <- Map.keys . envConfigPackages <$> asks getEnvConfig
let args =
-- Use index files from all packages (allows cross-package coverage results).
concatMap (\x -> ["--srcdir", toFilePathNoTrailingSep x]) pkgDirs ++
-- Look for index files in the correct dir (relative to each pkgdir).
["--hpcdir", toFilePathNoTrailingSep hpcRelDir, "--reset-hpcdirs"]
menv <- getMinimalEnvOverride
$logInfo $ "Generating " <> report
outputLines <- liftM (map (S8.filter (/= '\r')) . S8.lines) $
readProcessStdout Nothing menv "hpc"
( "report"
: toFilePath tixSrc
: (args ++ extraReportArgs)
)
if all ("(0/0)" `S8.isSuffixOf`) outputLines
then do
let msg html = T.concat
[ "Error: The "
, report
, " did not consider any code. One possible cause of this is"
, " if your test-suite builds the library code (see stack "
, if html then "<a href='https://github.com/commercialhaskell/stack/issues/1008'>" else ""
, "issue #1008"
, if html then "</a>" else ""
, "). It may also indicate a bug in stack or"
, " the hpc program. Please report this issue if you think"
, " your coverage report should have meaningful results."
]
$logError (msg False)
generateHpcErrorReport reportDir (msg True)
else do
-- Print output, stripping @\r@ characters because Windows.
forM_ outputLines ($logInfo . T.decodeUtf8)
$logInfo
("The " <> report <> " is available at " <>
T.pack (toFilePath (reportDir </> $(mkRelFile "hpc_index.html"))))
-- Generate the markup.
void $ readProcessStdout Nothing menv "hpc"
( "markup"
: toFilePath tixSrc
: ("--destdir=" ++ toFilePathNoTrailingSep reportDir)
: (args ++ extraMarkupArgs)
)
data HpcReportOpts = HpcReportOpts
{ hroptsInputs :: [Text]
, hroptsAll :: Bool
, hroptsDestDir :: Maybe String
} deriving (Show)
generateHpcReportForTargets :: (MonadIO m, MonadReader env m, MonadBaseControl IO m, MonadMask m, MonadLogger m, HasEnvConfig env)
=> HpcReportOpts -> m ()
generateHpcReportForTargets opts = do
let (tixFiles, targetNames) = partition (".tix" `T.isSuffixOf`) (hroptsInputs opts)
targetTixFiles <-
-- When there aren't any package component arguments, then
-- don't default to all package components.
if not (hroptsAll opts) && null targetNames
then return []
else do
when (hroptsAll opts && not (null targetNames)) $
$logWarn $ "Since --all is used, it is redundant to specify these targets: " <> T.pack (show targetNames)
(_,_,targets) <- parseTargetsFromBuildOpts
AllowNoTargets
defaultBuildOptsCLI
{ boptsCLITargets = if hroptsAll opts then [] else targetNames }
liftM concat $ forM (Map.toList targets) $ \(name, target) ->
case target of
STUnknown -> fail $
packageNameString name ++ " isn't a known local page"
STNonLocal -> fail $
"Expected a local package, but " ++
packageNameString name ++
" is either an extra-dep or in the snapshot."
STLocalComps comps -> do
pkgPath <- hpcPkgPath name
forM (toList comps) $ \nc ->
case nc of
CTest testName ->
liftM (pkgPath </>) $ parseRelFile (T.unpack testName ++ ".tix")
_ -> fail $
"Can't specify anything except test-suites as hpc report targets (" ++
packageNameString name ++
" is used with a non test-suite target)"
STLocalAll -> do
pkgPath <- hpcPkgPath name
exists <- doesDirExist pkgPath
if exists
then do
(_, files) <- listDir pkgPath
return (filter ((".tix" `isSuffixOf`) . toFilePath) files)
else return []
tixPaths <- liftM (++ targetTixFiles) $ mapM (resolveFile' . T.unpack) tixFiles
when (null tixPaths) $
fail "Not generating combined report, because no targets or tix files are specified."
reportDir <- case hroptsDestDir opts of
Nothing -> liftM (</> $(mkRelDir "combined/custom")) hpcReportDir
Just destDir -> do
dest <- resolveDir' destDir
ensureDir dest
return dest
generateUnionReport "combined report" reportDir tixPaths
generateHpcUnifiedReport :: (MonadIO m,MonadReader env m,MonadLogger m,MonadBaseControl IO m,MonadMask m,HasEnvConfig env)
=> m ()
generateHpcUnifiedReport = do
outputDir <- hpcReportDir
ensureDir outputDir
(dirs, _) <- listDir outputDir
tixFiles <- liftM (concat . concat) $ forM (filter (("combined" /=) . dirnameString) dirs) $ \dir -> do
(dirs', _) <- listDir dir
forM dirs' $ \dir' -> do
(_, files) <- listDir dir'
return (filter ((".tix" `isSuffixOf`) . toFilePath) files)
let reportDir = outputDir </> $(mkRelDir "combined/all")
if length tixFiles < 2
then $logInfo $ T.concat
[ if null tixFiles then "No tix files" else "Only one tix file"
, " found in "
, T.pack (toFilePath outputDir)
, ", so not generating a unified coverage report."
]
else generateUnionReport "unified report" reportDir tixFiles
generateUnionReport :: (MonadIO m,MonadReader env m,MonadLogger m,MonadBaseControl IO m,MonadMask m,HasEnvConfig env)
=> Text -> Path Abs Dir -> [Path Abs File] -> m ()
generateUnionReport report reportDir tixFiles = do
(errs, tix) <- fmap (unionTixes . map removeExeModules) (mapMaybeM readTixOrLog tixFiles)
$logDebug $ "Using the following tix files: " <> T.pack (show tixFiles)
unless (null errs) $ $logWarn $ T.concat $
"The following modules are left out of the " : report : " due to version mismatches: " :
intersperse ", " (map T.pack errs)
tixDest <- liftM (reportDir </>) $ parseRelFile (dirnameString reportDir ++ ".tix")
ensureDir (parent tixDest)
liftIO $ writeTix (toFilePath tixDest) tix
generateHpcReportInternal tixDest reportDir report [] []
readTixOrLog :: (MonadLogger m, MonadIO m, MonadBaseControl IO m) => Path b File -> m (Maybe Tix)
readTixOrLog path = do
mtix <- liftIO (readTix (toFilePath path)) `catch` \errorCall -> do
$logError $ "Error while reading tix: " <> T.pack (show (errorCall :: ErrorCall))
return Nothing
when (isNothing mtix) $
$logError $ "Failed to read tix file " <> T.pack (toFilePath path)
return mtix
-- | Module names which contain '/' have a package name, and so they weren't built into the
-- executable.
removeExeModules :: Tix -> Tix
removeExeModules (Tix ms) = Tix (filter (\(TixModule name _ _ _) -> '/' `elem` name) ms)
unionTixes :: [Tix] -> ([String], Tix)
unionTixes tixes = (Map.keys errs, Tix (Map.elems outputs))
where
(errs, outputs) = Map.mapEither id $ Map.unionsWith merge $ map toMap tixes
toMap (Tix ms) = Map.fromList (map (\x@(TixModule k _ _ _) -> (k, Right x)) ms)
merge (Right (TixModule k hash1 len1 tix1))
(Right (TixModule _ hash2 len2 tix2))
| hash1 == hash2 && len1 == len2 = Right (TixModule k hash1 len1 (zipWith (+) tix1 tix2))
merge _ _ = Left ()
generateHpcMarkupIndex :: (MonadIO m,MonadReader env m,MonadLogger m,MonadMask m,HasEnvConfig env)
=> m ()
generateHpcMarkupIndex = do
outputDir <- hpcReportDir
let outputFile = outputDir </> $(mkRelFile "index.html")
ensureDir outputDir
(dirs, _) <- listDir outputDir
rows <- liftM (catMaybes . concat) $ forM dirs $ \dir -> do
(subdirs, _) <- listDir dir
forM subdirs $ \subdir -> do
let indexPath = subdir </> $(mkRelFile "hpc_index.html")
exists' <- doesFileExist indexPath
if not exists' then return Nothing else do
relPath <- stripDir outputDir indexPath
let package = dirname dir
testsuite = dirname subdir
return $ Just $ T.concat
[ "<tr><td>"
, pathToHtml package
, "</td><td><a href=\""
, pathToHtml relPath
, "\">"
, pathToHtml testsuite
, "</a></td></tr>"
]
liftIO $ T.writeFile (toFilePath outputFile) $ T.concat $
[ "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
-- Part of the css from HPC's output HTML
, "<style type=\"text/css\">"
, "table.dashboard { border-collapse: collapse; border: solid 1px black }"
, ".dashboard td { border: solid 1px black }"
, ".dashboard th { border: solid 1px black }"
, "</style>"
, "</head>"
, "<body>"
] ++
(if null rows
then
[ "<b>No hpc_index.html files found in \""
, pathToHtml outputDir
, "\".</b>"
]
else
[ "<table class=\"dashboard\" width=\"100%\" boder=\"1\"><tbody>"
, "<p><b>NOTE: This is merely a listing of the html files found in the coverage reports directory. Some of these reports may be old.</b></p>"
, "<tr><th>Package</th><th>TestSuite</th><th>Modification Time</th></tr>"
] ++
rows ++
["</tbody></table>"]) ++
["</body></html>"]
unless (null rows) $
$logInfo $ "\nAn index of the generated HTML coverage reports is available at " <>
T.pack (toFilePath outputFile)
generateHpcErrorReport :: MonadIO m => Path Abs Dir -> Text -> m ()
generateHpcErrorReport dir err = do
ensureDir dir
liftIO $ T.writeFile (toFilePath (dir </> $(mkRelFile "hpc_index.html"))) $ T.concat
[ "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head><body>"
, "<h1>HPC Report Generation Error</h1>"
, "<p>"
, err
, "</p>"
, "</body></html>"
]
pathToHtml :: Path b t -> Text
pathToHtml = T.dropWhileEnd (=='/') . sanitize . toFilePath
sanitize :: String -> Text
sanitize = LT.toStrict . htmlEscape . LT.pack
dirnameString :: Path r Dir -> String
dirnameString = dropWhileEnd isPathSeparator . toFilePath . dirname
findPackageFieldForBuiltPackage :: (MonadIO m,MonadBaseControl IO m,MonadReader env m,MonadThrow m,MonadLogger m,HasEnvConfig env) => Path Abs Dir -> PackageIdentifier -> Text -> m (Either Text Text)
findPackageFieldForBuiltPackage pkgDir pkgId field = do
distDir <- distDirFromDir pkgDir
let inplaceDir = distDir </> $(mkRelDir "package.conf.inplace")
pkgIdStr = packageIdentifierString pkgId
notFoundErr = return $ Left $ "Failed to find package key for " <> T.pack pkgIdStr
extractField path = do
contents <- liftIO $ T.readFile (toFilePath path)
case asum (map (T.stripPrefix (field <> ": ")) (T.lines contents)) of
Just result -> return $ Right result
Nothing -> notFoundErr
cabalVer <- asks (envConfigCabalVersion . getEnvConfig)
if cabalVer < $(mkVersion "1.24")
then do
path <- liftM (inplaceDir </>) $ parseRelFile (pkgIdStr ++ "-inplace.conf")
$logDebug $ "Parsing config in Cabal < 1.24 location: " <> T.pack (toFilePath path)
exists <- doesFileExist path
if exists then extractField path else notFoundErr
else do
-- With Cabal-1.24, it's in a different location.
$logDebug $ "Scanning " <> T.pack (toFilePath inplaceDir) <> " for files matching " <> T.pack pkgIdStr
(_, files) <- handleIO (const $ return ([], [])) $ listDir inplaceDir
$logDebug $ T.pack (show files)
case mapMaybe (\file -> fmap (const file) . (T.stripSuffix ".conf" <=< T.stripPrefix (T.pack (pkgIdStr ++ "-")))
. T.pack . toFilePath . filename $ file) files of
[] -> notFoundErr
[path] -> extractField path
_ -> return $ Left $ "Multiple files matching " <> T.pack (pkgIdStr ++ "-*.conf") <> " found in " <>
T.pack (toFilePath inplaceDir) <> ". Maybe try 'stack clean' on this package?"
|
AndrewRademacher/stack
|
src/Stack/Coverage.hs
|
bsd-3-clause
| 21,815
| 0
| 28
| 7,000
| 5,013
| 2,541
| 2,472
| 366
| 9
|
module HsParser
{-# DEPRECATED "This module has moved to Language.Haskell.Parser" #-}
(module Language.Haskell.Parser) where
import Language.Haskell.Parser
|
alekar/hugs
|
fptools/hslibs/hssource/HsParser.hs
|
bsd-3-clause
| 156
| 0
| 5
| 16
| 20
| 14
| 6
| 4
| 0
|
{-# LANGUAGE RecursiveDo, RankNTypes, NamedFieldPuns, RecordWildCards #-}
module Distribution.Server.Features.Upload (
UploadFeature(..),
UploadResource(..),
initUploadFeature,
UploadResult(..),
) where
import Distribution.Server.Framework
import Distribution.Server.Framework.BackupDump
import Distribution.Server.Features.Upload.State
import Distribution.Server.Features.Upload.Backup
import Distribution.Server.Features.Core
import Distribution.Server.Features.Users
import Distribution.Server.Users.Backup
import Distribution.Server.Packages.Types
import qualified Distribution.Server.Users.Types as Users
import qualified Distribution.Server.Users.Group as Group
import Distribution.Server.Users.Group (UserGroup(..), GroupDescription(..), nullDescription)
import qualified Distribution.Server.Framework.BlobStorage as BlobStorage
import qualified Distribution.Server.Packages.Unpack as Upload
import Distribution.Server.Packages.PackageIndex (PackageIndex)
import qualified Distribution.Server.Packages.PackageIndex as PackageIndex
import Data.Maybe (fromMaybe)
import Data.Time.Clock (getCurrentTime)
import Data.Function (fix)
import Data.ByteString.Lazy (ByteString)
import Distribution.Package
import Distribution.PackageDescription (GenericPackageDescription)
import Distribution.Text (display)
import qualified Distribution.Server.Util.GZip as GZip
data UploadFeature = UploadFeature {
-- | The package upload `HackageFeature`.
uploadFeatureInterface :: HackageFeature,
-- | Upload resources.
uploadResource :: UploadResource,
-- | The main upload routine. This uses extractPackage on a multipart
-- request to get contextual information.
uploadPackage :: ServerPartE UploadResult,
--TODO: consider moving the trustee and/or per-package maintainer groups
-- lower down in the feature hierarchy; many other features want to
-- use the trustee group purely for auth decisions
-- | The group of Hackage trustees.
trusteesGroup :: UserGroup,
-- | The group of package uploaders.
uploadersGroup :: UserGroup,
-- | The group of maintainers for a given package.
maintainersGroup :: PackageName -> UserGroup,
-- | Requiring being logged in as the maintainer of a package.
guardAuthorisedAsMaintainer :: PackageName -> ServerPartE (),
-- | Requiring being logged in as the maintainer of a package or a trustee.
guardAuthorisedAsMaintainerOrTrustee :: PackageName -> ServerPartE (),
-- | Takes an upload request and, depending on the result of the
-- passed-in function, either commits the uploaded tarball to the blob
-- storage or throws it away and yields an error.
extractPackage :: (Users.UserId -> UploadResult -> IO (Maybe ErrorResponse))
-> ServerPartE (Users.UserId, UploadResult, PkgTarball)
}
instance IsHackageFeature UploadFeature where
getFeatureInterface = uploadFeatureInterface
data UploadResource = UploadResource {
-- | The page for uploading a package, the same as `corePackagesPage`.
uploadIndexPage :: Resource,
-- | The page for deleting a package, the same as `corePackagePage`.
--
-- This is fairly dangerous and is not currently used.
deletePackagePage :: Resource,
-- | The maintainers group for each package.
maintainersGroupResource :: GroupResource,
-- | The trustee group.
trusteesGroupResource :: GroupResource,
-- | The allowed-uploaders group.
uploadersGroupResource :: GroupResource,
-- | URI for `maintainersGroupResource` given a format and `PackageId`.
packageMaintainerUri :: String -> PackageId -> String,
-- | URI for `trusteesGroupResource` given a format.
trusteeUri :: String -> String,
-- | URI for `uploadersGroupResource` given a format.
uploaderUri :: String -> String
}
-- | The representation of an intermediate result in the upload process,
-- indicating a package which meets the requirements to go into Hackage.
data UploadResult = UploadResult {
-- The parsed Cabal file.
uploadDesc :: !GenericPackageDescription,
-- The text of the Cabal file.
uploadCabal :: !ByteString,
-- Any warnings from unpacking the tarball.
uploadWarnings :: ![String]
}
initUploadFeature :: ServerEnv
-> IO (UserFeature -> CoreFeature -> IO UploadFeature)
initUploadFeature env@ServerEnv{serverStateDir} = do
-- Canonical state
trusteesState <- trusteesStateComponent serverStateDir
uploadersState <- uploadersStateComponent serverStateDir
maintainersState <- maintainersStateComponent serverStateDir
return $ \user@UserFeature{..} core@CoreFeature{..} -> do
-- Recusively tie the knot: the feature contains new user group resources
-- but we make the functions needed to create those resources along with
-- the feature
rec let (feature,
trusteesGroupDescription, uploadersGroupDescription,
maintainersGroupDescription)
= uploadFeature env core user
trusteesState trusteesGroup trusteesGroupResource
uploadersState uploadersGroup uploadersGroupResource
maintainersState maintainersGroup maintainersGroupResource
(trusteesGroup, trusteesGroupResource) <-
groupResourceAt "/packages/trustees" trusteesGroupDescription
(uploadersGroup, uploadersGroupResource) <-
groupResourceAt "/packages/uploaders" uploadersGroupDescription
pkgNames <- PackageIndex.packageNames <$> queryGetPackageIndex
(maintainersGroup, maintainersGroupResource) <-
groupResourcesAt "/package/:package/maintainers"
maintainersGroupDescription
(\pkgname -> [("package", display pkgname)])
(packageInPath coreResource)
pkgNames
return feature
trusteesStateComponent :: FilePath -> IO (StateComponent AcidState HackageTrustees)
trusteesStateComponent stateDir = do
st <- openLocalStateFrom (stateDir </> "db" </> "HackageTrustees") initialHackageTrustees
return StateComponent {
stateDesc = "Trustees"
, stateHandle = st
, getState = query st GetHackageTrustees
, putState = update st . ReplaceHackageTrustees . trusteeList
, backupState = \_ (HackageTrustees trustees) -> [csvToBackup ["trustees.csv"] $ groupToCSV trustees]
, restoreState = HackageTrustees <$> groupBackup ["trustees.csv"]
, resetState = trusteesStateComponent
}
uploadersStateComponent :: FilePath -> IO (StateComponent AcidState HackageUploaders)
uploadersStateComponent stateDir = do
st <- openLocalStateFrom (stateDir </> "db" </> "HackageUploaders") initialHackageUploaders
return StateComponent {
stateDesc = "Uploaders"
, stateHandle = st
, getState = query st GetHackageUploaders
, putState = update st . ReplaceHackageUploaders . uploaderList
, backupState = \_ (HackageUploaders uploaders) -> [csvToBackup ["uploaders.csv"] $ groupToCSV uploaders]
, restoreState = HackageUploaders <$> groupBackup ["uploaders.csv"]
, resetState = uploadersStateComponent
}
maintainersStateComponent :: FilePath -> IO (StateComponent AcidState PackageMaintainers)
maintainersStateComponent stateDir = do
st <- openLocalStateFrom (stateDir </> "db" </> "PackageMaintainers") initialPackageMaintainers
return StateComponent {
stateDesc = "Package maintainers"
, stateHandle = st
, getState = query st AllPackageMaintainers
, putState = update st . ReplacePackageMaintainers
, backupState = \_ (PackageMaintainers mains) -> [maintToExport mains]
, restoreState = maintainerBackup
, resetState = maintainersStateComponent
}
uploadFeature :: ServerEnv
-> CoreFeature
-> UserFeature
-> StateComponent AcidState HackageTrustees -> UserGroup -> GroupResource
-> StateComponent AcidState HackageUploaders -> UserGroup -> GroupResource
-> StateComponent AcidState PackageMaintainers -> (PackageName -> UserGroup) -> GroupResource
-> (UploadFeature,
UserGroup,
UserGroup,
PackageName -> UserGroup)
uploadFeature ServerEnv{serverBlobStore = store}
CoreFeature{ coreResource
, queryGetPackageIndex
, updateAddPackage
}
UserFeature{..}
trusteesState trusteesGroup trusteesGroupResource
uploadersState uploadersGroup uploadersGroupResource
maintainersState maintainersGroup maintainersGroupResource
= ( UploadFeature {..}
, trusteesGroupDescription, uploadersGroupDescription, maintainersGroupDescription)
where
uploadFeatureInterface = (emptyHackageFeature "upload") {
featureDesc = "Support for package uploads, and define groups for trustees, uploaders, and package maintainers"
, featureResources =
[ uploadIndexPage uploadResource
, groupResource maintainersGroupResource
, groupUserResource maintainersGroupResource
, groupResource trusteesGroupResource
, groupUserResource trusteesGroupResource
, groupResource uploadersGroupResource
, groupUserResource uploadersGroupResource
]
, featureState = [
abstractAcidStateComponent trusteesState
, abstractAcidStateComponent uploadersState
, abstractAcidStateComponent maintainersState
]
}
uploadResource = UploadResource
{ uploadIndexPage = (extendResource (corePackagesPage coreResource)) { resourcePost = [] }
, deletePackagePage = (extendResource (corePackagePage coreResource)) { resourceDelete = [] }
, maintainersGroupResource = maintainersGroupResource
, trusteesGroupResource = trusteesGroupResource
, uploadersGroupResource = uploadersGroupResource
, packageMaintainerUri = \format pkgname -> renderResource
(groupResource maintainersGroupResource) [display pkgname, format]
, trusteeUri = \format -> renderResource (groupResource trusteesGroupResource) [format]
, uploaderUri = \format -> renderResource (groupResource uploadersGroupResource) [format]
}
--------------------------------------------------------------------------------
-- User groups and authentication
trusteesGroupDescription :: UserGroup
trusteesGroupDescription = UserGroup {
groupDesc = trusteeDescription,
queryUserList = queryState trusteesState GetTrusteesList,
addUserList = updateState trusteesState . AddHackageTrustee,
removeUserList = updateState trusteesState . RemoveHackageTrustee,
canAddGroup = [adminGroup],
canRemoveGroup = [adminGroup]
}
uploadersGroupDescription :: UserGroup
uploadersGroupDescription = UserGroup {
groupDesc = uploaderDescription,
queryUserList = queryState uploadersState GetUploadersList,
addUserList = updateState uploadersState . AddHackageUploader,
removeUserList = updateState uploadersState . RemoveHackageUploader,
canAddGroup = [adminGroup],
canRemoveGroup = [adminGroup]
}
maintainersGroupDescription :: PackageName -> UserGroup
maintainersGroupDescription name = fix $ \u -> UserGroup {
groupDesc = maintainerDescription name,
queryUserList = queryState maintainersState $ GetPackageMaintainers name,
addUserList = updateState maintainersState . AddPackageMaintainer name,
removeUserList = updateState maintainersState . RemovePackageMaintainer name,
canAddGroup = [u, adminGroup],
canRemoveGroup = [u, adminGroup]
}
maintainerDescription :: PackageName -> GroupDescription
maintainerDescription pkgname = GroupDescription
{ groupTitle = "Maintainers"
, groupEntity = Just (pname, Just $ "/package/" ++ pname)
, groupPrologue = "Maintainers for a package can upload new versions and adjust other attributes in the package database."
}
where pname = display pkgname
trusteeDescription :: GroupDescription
trusteeDescription = nullDescription { groupTitle = "Package trustees", groupPrologue = "The role of trustees is to help to curate the whole package collection. Trustees have a limited ability to edit package information, for the entire package database (as opposed to package maintainers who have full control over individual packages). Trustees can edit .cabal files, edit other package metadata and upload documentation but they cannot upload new package versions." }
uploaderDescription :: GroupDescription
uploaderDescription = nullDescription { groupTitle = "Package uploaders", groupPrologue = "Package uploaders are allowed to upload packages. Note that if a package already exists then you also need to be in the maintainer group for that package." }
guardAuthorisedAsMaintainer :: PackageName -> ServerPartE ()
guardAuthorisedAsMaintainer pkgname =
guardAuthorised_ [InGroup (maintainersGroup pkgname)]
guardAuthorisedAsMaintainerOrTrustee :: PackageName -> ServerPartE ()
guardAuthorisedAsMaintainerOrTrustee pkgname =
guardAuthorised_ [InGroup (maintainersGroup pkgname), InGroup trusteesGroup]
----------------------------------------------------
-- This is the upload function. It returns a generic result for multiple formats.
uploadPackage :: ServerPartE UploadResult
uploadPackage = do
guardAuthorised_ [InGroup uploadersGroup]
pkgIndex <- queryGetPackageIndex
(uid, uresult, tarball) <- extractPackage $ \uid info ->
processUpload pkgIndex uid info
now <- liftIO getCurrentTime
let (UploadResult pkg pkgStr _) = uresult
pkgid = packageId pkg
cabalfile = CabalFileText pkgStr
uploadinfo = (now, uid)
success <- updateAddPackage pkgid cabalfile uploadinfo (Just tarball)
if success
then do
-- make package maintainers group for new package
let existedBefore = packageExists pkgIndex pkgid
when (not existedBefore) $
liftIO $ addUserList (maintainersGroup (packageName pkgid)) uid
return uresult
-- this is already checked in processUpload, and race conditions are highly unlikely but imaginable
else errForbidden "Upload failed" [MText "Package already exists."]
-- This is a processing funtion for extractPackage that checks upload-specific requirements.
-- Does authentication, though not with requirePackageAuth, because it has to be IO.
-- Some other checks can be added, e.g. if a package with a later version exists
processUpload :: PackageIndex PkgInfo -> Users.UserId -> UploadResult -> IO (Maybe ErrorResponse)
processUpload state uid res = do
let pkg = packageId (uploadDesc res)
pkgGroup <- queryUserList (maintainersGroup (packageName pkg))
if packageIdExists state pkg
then uploadError versionExists --allow trustees to do this?
else if packageExists state pkg && not (uid `Group.member` pkgGroup)
then uploadError (notMaintainer pkg)
else return Nothing
where
uploadError = return . Just . ErrorResponse 403 [] "Upload failed" . return . MText
versionExists = "This version of the package has already been uploaded.\n\nAs a matter of "
++ "policy we do not allow package tarballs to be changed after a release "
++ "(so we can guarantee stable md5sums etc). The usual recommendation is "
++ "to upload a new version, and if necessary blacklist the existing one. "
++ "In extraordinary circumstances, contact the administrators."
notMaintainer pkg = "You are not authorised to upload new versions of this package. The "
++ "package '" ++ display (packageName pkg) ++ "' exists already and you "
++ "are not a member of the maintainer group for this package.\n\n"
++ "If you believe you should be a member of the maintainer group for this "
++ "package, then ask an existing maintainer to add you to the group. If "
++ "this is a package name clash, please pick another name or talk to the "
++ "maintainers of the existing package."
-- This function generically extracts a package, useful for uploading, checking,
-- and anything else in the standard user-upload pipeline.
extractPackage :: (Users.UserId -> UploadResult -> IO (Maybe ErrorResponse))
-> ServerPartE (Users.UserId, UploadResult, PkgTarball)
extractPackage processFunc =
withDataFn (lookInput "package") $ \input ->
case inputValue input of -- HS6 this has been updated to use the new file upload support in HS6, but has not been tested at all
(Right _) -> errBadRequest "Upload failed" [MText "package field in form data is not a file."]
(Left file) ->
let fileName = (fromMaybe "noname" $ inputFilename input)
in upload fileName file
where
upload name file =
do -- initial check to ensure logged in.
--FIXME: this should have been covered earlier
uid <- guardAuthenticated
now <- liftIO getCurrentTime
let processPackage :: ByteString -> IO (Either ErrorResponse (UploadResult, BlobStorage.BlobId))
processPackage content' = do
-- as much as it would be nice to do requirePackageAuth in here,
-- processPackage is run in a handle bracket
case Upload.unpackPackage now name content' of
Left err -> return . Left $ ErrorResponse 400 [] "Invalid package" [MText err]
Right ((pkg, pkgStr), warnings) -> do
let uresult = UploadResult pkg pkgStr warnings
res <- processFunc uid uresult
case res of
Nothing ->
do let decompressedContent = GZip.decompressNamed file content'
blobIdDecompressed <- BlobStorage.add store decompressedContent
return . Right $ (uresult, blobIdDecompressed)
Just err -> return . Left $ err
mres <- liftIO $ BlobStorage.consumeFileWith store file processPackage
case mres of
Left err -> throwError err
Right ((res, blobIdDecompressed), blobId) ->
return (uid, res, tarball)
where
tarball = PkgTarball { pkgTarballGz = blobId,
pkgTarballNoGz = blobIdDecompressed }
|
snoyberg/hackage-server
|
Distribution/Server/Features/Upload.hs
|
bsd-3-clause
| 19,553
| 0
| 30
| 5,112
| 3,080
| 1,689
| 1,391
| 278
| 8
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.PackageDescription
-- Copyright : Isaac Jones 2003-2005
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This defines the data structure for the @.cabal@ file format. There are
-- several parts to this structure. It has top level info and then 'Library',
-- 'Executable', 'TestSuite', and 'Benchmark' sections each of which have
-- associated 'BuildInfo' data that's used to build the library, exe, test, or
-- benchmark. To further complicate things there is both a 'PackageDescription'
-- and a 'GenericPackageDescription'. This distinction relates to cabal
-- configurations. When we initially read a @.cabal@ file we get a
-- 'GenericPackageDescription' which has all the conditional sections.
-- Before actually building a package we have to decide
-- on each conditional. Once we've done that we get a 'PackageDescription'.
-- It was done this way initially to avoid breaking too much stuff when the
-- feature was introduced. It could probably do with being rationalised at some
-- point to make it simpler.
module Distribution.PackageDescription (
-- * Package descriptions
PackageDescription(..),
emptyPackageDescription,
specVersion,
descCabalVersion,
BuildType(..),
knownBuildTypes,
-- ** Renaming
ModuleRenaming(..),
defaultRenaming,
lookupRenaming,
-- ** Libraries
Library(..),
ModuleReexport(..),
emptyLibrary,
withLib,
hasLibs,
libModules,
-- ** Executables
Executable(..),
emptyExecutable,
withExe,
hasExes,
exeModules,
-- * Tests
TestSuite(..),
TestSuiteInterface(..),
TestType(..),
testType,
knownTestTypes,
emptyTestSuite,
hasTests,
withTest,
testModules,
enabledTests,
-- * Benchmarks
Benchmark(..),
BenchmarkInterface(..),
BenchmarkType(..),
benchmarkType,
knownBenchmarkTypes,
emptyBenchmark,
hasBenchmarks,
withBenchmark,
benchmarkModules,
enabledBenchmarks,
-- * Build information
BuildInfo(..),
emptyBuildInfo,
allBuildInfo,
allLanguages,
allExtensions,
usedExtensions,
hcOptions,
hcProfOptions,
hcSharedOptions,
-- ** Supplementary build information
HookedBuildInfo,
emptyHookedBuildInfo,
updatePackageDescription,
-- * package configuration
GenericPackageDescription(..),
Flag(..), FlagName(..), FlagAssignment,
CondTree(..), ConfVar(..), Condition(..),
-- * Source repositories
SourceRepo(..),
RepoKind(..),
RepoType(..),
knownRepoTypes,
-- * Custom setup build information
SetupBuildInfo(..),
) where
import Distribution.Compat.Binary (Binary)
import Data.Data (Data)
import Data.Foldable (traverse_)
import Data.List (nub, intercalate)
import Data.Maybe (fromMaybe, maybeToList)
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Applicative((<*>), pure))
import Data.Monoid (Monoid(mempty, mappend))
import Data.Foldable (Foldable(foldMap))
import Data.Traversable (Traversable(traverse))
#endif
import Data.Typeable ( Typeable )
import Control.Monad (MonadPlus(mplus))
import GHC.Generics (Generic)
import Text.PrettyPrint as Disp
import qualified Distribution.Compat.ReadP as Parse
import Distribution.Compat.ReadP ((<++))
import qualified Data.Char as Char (isAlphaNum, isDigit, toLower)
import qualified Data.Map as Map
import Data.Map (Map)
import Distribution.Package
( PackageName(PackageName), PackageIdentifier(PackageIdentifier)
, Dependency, Package(..), PackageName, packageName )
import Distribution.ModuleName ( ModuleName )
import Distribution.Version
( Version(Version), VersionRange, anyVersion, orLaterVersion
, asVersionIntervals, LowerBound(..) )
import Distribution.License (License(UnspecifiedLicense))
import Distribution.Compiler (CompilerFlavor)
import Distribution.System (OS, Arch)
import Distribution.Text
( Text(..), display )
import Language.Haskell.Extension
( Language, Extension )
-- -----------------------------------------------------------------------------
-- The PackageDescription type
-- | This data type is the internal representation of the file @pkg.cabal@.
-- It contains two kinds of information about the package: information
-- which is needed for all packages, such as the package name and version, and
-- information which is needed for the simple build system only, such as
-- the compiler options and library name.
--
data PackageDescription
= PackageDescription {
-- the following are required by all packages:
package :: PackageIdentifier,
license :: License,
licenseFiles :: [FilePath],
copyright :: String,
maintainer :: String,
author :: String,
stability :: String,
testedWith :: [(CompilerFlavor,VersionRange)],
homepage :: String,
pkgUrl :: String,
bugReports :: String,
sourceRepos :: [SourceRepo],
synopsis :: String, -- ^A one-line summary of this package
description :: String, -- ^A more verbose description of this package
category :: String,
customFieldsPD :: [(String,String)], -- ^Custom fields starting
-- with x-, stored in a
-- simple assoc-list.
-- | YOU PROBABLY DON'T WANT TO USE THIS FIELD. This field is
-- special! Depending on how far along processing the
-- PackageDescription we are, the contents of this field are
-- either nonsense, or the collected dependencies of *all* the
-- components in this package. buildDepends is initialized by
-- 'finalizePackageDescription' and 'flattenPackageDescription';
-- prior to that, dependency info is stored in the 'CondTree'
-- built around a 'GenericPackageDescription'. When this
-- resolution is done, dependency info is written to the inner
-- 'BuildInfo' and this field. This is all horrible, and #2066
-- tracks progress to get rid of this field.
buildDepends :: [Dependency],
-- | The version of the Cabal spec that this package description uses.
-- For historical reasons this is specified with a version range but
-- only ranges of the form @>= v@ make sense. We are in the process of
-- transitioning to specifying just a single version, not a range.
specVersionRaw :: Either Version VersionRange,
buildType :: Maybe BuildType,
setupBuildInfo :: Maybe SetupBuildInfo,
-- components
library :: Maybe Library,
executables :: [Executable],
testSuites :: [TestSuite],
benchmarks :: [Benchmark],
dataFiles :: [FilePath],
dataDir :: FilePath,
extraSrcFiles :: [FilePath],
extraTmpFiles :: [FilePath],
extraDocFiles :: [FilePath]
}
deriving (Generic, Show, Read, Eq, Typeable, Data)
instance Binary PackageDescription
instance Package PackageDescription where
packageId = package
-- | The version of the Cabal spec that this package should be interpreted
-- against.
--
-- Historically we used a version range but we are switching to using a single
-- version. Currently we accept either. This function converts into a single
-- version by ignoring upper bounds in the version range.
--
specVersion :: PackageDescription -> Version
specVersion pkg = case specVersionRaw pkg of
Left version -> version
Right versionRange -> case asVersionIntervals versionRange of
[] -> Version [0] []
((LowerBound version _, _):_) -> version
-- | The range of versions of the Cabal tools that this package is intended to
-- work with.
--
-- This function is deprecated and should not be used for new purposes, only to
-- support old packages that rely on the old interpretation.
--
descCabalVersion :: PackageDescription -> VersionRange
descCabalVersion pkg = case specVersionRaw pkg of
Left version -> orLaterVersion version
Right versionRange -> versionRange
{-# DEPRECATED descCabalVersion "Use specVersion instead" #-}
emptyPackageDescription :: PackageDescription
emptyPackageDescription
= PackageDescription {
package = PackageIdentifier (PackageName "")
(Version [] []),
license = UnspecifiedLicense,
licenseFiles = [],
specVersionRaw = Right anyVersion,
buildType = Nothing,
copyright = "",
maintainer = "",
author = "",
stability = "",
testedWith = [],
buildDepends = [],
homepage = "",
pkgUrl = "",
bugReports = "",
sourceRepos = [],
synopsis = "",
description = "",
category = "",
customFieldsPD = [],
setupBuildInfo = Nothing,
library = Nothing,
executables = [],
testSuites = [],
benchmarks = [],
dataFiles = [],
dataDir = "",
extraSrcFiles = [],
extraTmpFiles = [],
extraDocFiles = []
}
-- | The type of build system used by this package.
data BuildType
= Simple -- ^ calls @Distribution.Simple.defaultMain@
| Configure -- ^ calls @Distribution.Simple.defaultMainWithHooks defaultUserHooks@,
-- which invokes @configure@ to generate additional build
-- information used by later phases.
| Make -- ^ calls @Distribution.Make.defaultMain@
| Custom -- ^ uses user-supplied @Setup.hs@ or @Setup.lhs@ (default)
| UnknownBuildType String
-- ^ a package that uses an unknown build type cannot actually
-- be built. Doing it this way rather than just giving a
-- parse error means we get better error messages and allows
-- you to inspect the rest of the package description.
deriving (Generic, Show, Read, Eq, Typeable, Data)
instance Binary BuildType
knownBuildTypes :: [BuildType]
knownBuildTypes = [Simple, Configure, Make, Custom]
instance Text BuildType where
disp (UnknownBuildType other) = Disp.text other
disp other = Disp.text (show other)
parse = do
name <- Parse.munch1 Char.isAlphaNum
return $ case name of
"Simple" -> Simple
"Configure" -> Configure
"Custom" -> Custom
"Make" -> Make
_ -> UnknownBuildType name
-- ---------------------------------------------------------------------------
-- The SetupBuildInfo type
-- One can see this as a very cut-down version of BuildInfo below.
-- To keep things simple for tools that compile Setup.hs we limit the
-- options authors can specify to just Haskell package dependencies.
data SetupBuildInfo = SetupBuildInfo {
setupDepends :: [Dependency]
}
deriving (Generic, Show, Eq, Read, Typeable, Data)
instance Binary SetupBuildInfo
instance Monoid SetupBuildInfo where
mempty = SetupBuildInfo {
setupDepends = mempty
}
mappend a b = SetupBuildInfo {
setupDepends = combine setupDepends
}
where combine field = field a `mappend` field b
-- ---------------------------------------------------------------------------
-- Module renaming
-- | Renaming applied to the modules provided by a package.
-- The boolean indicates whether or not to also include all of the
-- original names of modules. Thus, @ModuleRenaming False []@ is
-- "don't expose any modules, and @ModuleRenaming True [("Data.Bool", "Bool")]@
-- is, "expose all modules, but also expose @Data.Bool@ as @Bool@".
--
data ModuleRenaming = ModuleRenaming Bool [(ModuleName, ModuleName)]
deriving (Show, Read, Eq, Ord, Typeable, Data, Generic)
defaultRenaming :: ModuleRenaming
defaultRenaming = ModuleRenaming True []
lookupRenaming :: Package pkg => pkg -> Map PackageName ModuleRenaming -> ModuleRenaming
lookupRenaming = Map.findWithDefault defaultRenaming . packageName
instance Binary ModuleRenaming where
instance Monoid ModuleRenaming where
ModuleRenaming b rns `mappend` ModuleRenaming b' rns'
= ModuleRenaming (b || b') (rns ++ rns') -- ToDo: dedupe?
mempty = ModuleRenaming False []
-- NB: parentheses are mandatory, because later we may extend this syntax
-- to allow "hiding (A, B)" or other modifier words.
instance Text ModuleRenaming where
disp (ModuleRenaming True []) = Disp.empty
disp (ModuleRenaming b vs) = (if b then text "with" else Disp.empty) <+> dispRns
where dispRns = Disp.parens
(Disp.hsep
(Disp.punctuate Disp.comma (map dispEntry vs)))
dispEntry (orig, new)
| orig == new = disp orig
| otherwise = disp orig <+> text "as" <+> disp new
parse = do Parse.string "with" >> Parse.skipSpaces
fmap (ModuleRenaming True) parseRns
<++ fmap (ModuleRenaming False) parseRns
<++ return (ModuleRenaming True [])
where parseRns = do
rns <- Parse.between (Parse.char '(') (Parse.char ')') parseList
Parse.skipSpaces
return rns
parseList =
Parse.sepBy parseEntry (Parse.char ',' >> Parse.skipSpaces)
parseEntry :: Parse.ReadP r (ModuleName, ModuleName)
parseEntry = do
orig <- parse
Parse.skipSpaces
(do _ <- Parse.string "as"
Parse.skipSpaces
new <- parse
Parse.skipSpaces
return (orig, new)
<++
return (orig, orig))
-- ---------------------------------------------------------------------------
-- The Library type
data Library = Library {
exposedModules :: [ModuleName],
reexportedModules :: [ModuleReexport],
requiredSignatures:: [ModuleName], -- ^ What sigs need implementations?
exposedSignatures:: [ModuleName], -- ^ What sigs are visible to users?
libExposed :: Bool, -- ^ Is the lib to be exposed by default?
libBuildInfo :: BuildInfo
}
deriving (Generic, Show, Eq, Read, Typeable, Data)
instance Binary Library
instance Monoid Library where
mempty = Library {
exposedModules = mempty,
reexportedModules = mempty,
requiredSignatures = mempty,
exposedSignatures = mempty,
libExposed = True,
libBuildInfo = mempty
}
mappend a b = Library {
exposedModules = combine exposedModules,
reexportedModules = combine reexportedModules,
requiredSignatures = combine requiredSignatures,
exposedSignatures = combine exposedSignatures,
libExposed = libExposed a && libExposed b, -- so False propagates
libBuildInfo = combine libBuildInfo
}
where combine field = field a `mappend` field b
emptyLibrary :: Library
emptyLibrary = mempty
-- |does this package have any libraries?
hasLibs :: PackageDescription -> Bool
hasLibs p = maybe False (buildable . libBuildInfo) (library p)
-- |'Maybe' version of 'hasLibs'
maybeHasLibs :: PackageDescription -> Maybe Library
maybeHasLibs p =
library p >>= \lib -> if buildable (libBuildInfo lib)
then Just lib
else Nothing
-- |If the package description has a library section, call the given
-- function with the library build info as argument.
withLib :: PackageDescription -> (Library -> IO ()) -> IO ()
withLib pkg_descr f =
traverse_ f (maybeHasLibs pkg_descr)
-- | Get all the module names from the library (exposed and internal modules)
-- which need to be compiled. (This does not include reexports, which
-- do not need to be compiled.)
libModules :: Library -> [ModuleName]
libModules lib = exposedModules lib
++ otherModules (libBuildInfo lib)
++ exposedSignatures lib
++ requiredSignatures lib
-- -----------------------------------------------------------------------------
-- Module re-exports
data ModuleReexport = ModuleReexport {
moduleReexportOriginalPackage :: Maybe PackageName,
moduleReexportOriginalName :: ModuleName,
moduleReexportName :: ModuleName
}
deriving (Eq, Generic, Read, Show, Typeable, Data)
instance Binary ModuleReexport
instance Text ModuleReexport where
disp (ModuleReexport mpkgname origname newname) =
maybe Disp.empty (\pkgname -> disp pkgname <> Disp.char ':') mpkgname
<> disp origname
<+> if newname == origname
then Disp.empty
else Disp.text "as" <+> disp newname
parse = do
mpkgname <- Parse.option Nothing $ do
pkgname <- parse
_ <- Parse.char ':'
return (Just pkgname)
origname <- parse
newname <- Parse.option origname $ do
Parse.skipSpaces
_ <- Parse.string "as"
Parse.skipSpaces
parse
return (ModuleReexport mpkgname origname newname)
-- ---------------------------------------------------------------------------
-- The Executable type
data Executable = Executable {
exeName :: String,
modulePath :: FilePath,
buildInfo :: BuildInfo
}
deriving (Generic, Show, Read, Eq, Typeable, Data)
instance Binary Executable
instance Monoid Executable where
mempty = Executable {
exeName = mempty,
modulePath = mempty,
buildInfo = mempty
}
mappend a b = Executable{
exeName = combine' exeName,
modulePath = combine modulePath,
buildInfo = combine buildInfo
}
where combine field = field a `mappend` field b
combine' field = case (field a, field b) of
("","") -> ""
("", x) -> x
(x, "") -> x
(x, y) -> error $ "Ambiguous values for executable field: '"
++ x ++ "' and '" ++ y ++ "'"
emptyExecutable :: Executable
emptyExecutable = mempty
-- |does this package have any executables?
hasExes :: PackageDescription -> Bool
hasExes p = any (buildable . buildInfo) (executables p)
-- | Perform the action on each buildable 'Executable' in the package
-- description.
withExe :: PackageDescription -> (Executable -> IO ()) -> IO ()
withExe pkg_descr f =
sequence_ [f exe | exe <- executables pkg_descr, buildable (buildInfo exe)]
-- | Get all the module names from an exe
exeModules :: Executable -> [ModuleName]
exeModules exe = otherModules (buildInfo exe)
-- ---------------------------------------------------------------------------
-- The TestSuite type
-- | A \"test-suite\" stanza in a cabal file.
--
data TestSuite = TestSuite {
testName :: String,
testInterface :: TestSuiteInterface,
testBuildInfo :: BuildInfo,
testEnabled :: Bool
-- TODO: By having a 'testEnabled' field in the PackageDescription, we
-- are mixing build status information (i.e., arguments to 'configure')
-- with static package description information. This is undesirable, but
-- a better solution is waiting on the next overhaul to the
-- GenericPackageDescription -> PackageDescription resolution process.
}
deriving (Generic, Show, Read, Eq, Typeable, Data)
instance Binary TestSuite
-- | The test suite interfaces that are currently defined. Each test suite must
-- specify which interface it supports.
--
-- More interfaces may be defined in future, either new revisions or totally
-- new interfaces.
--
data TestSuiteInterface =
-- | Test interface \"exitcode-stdio-1.0\". The test-suite takes the form
-- of an executable. It returns a zero exit code for success, non-zero for
-- failure. The stdout and stderr channels may be logged. It takes no
-- command line parameters and nothing on stdin.
--
TestSuiteExeV10 Version FilePath
-- | Test interface \"detailed-0.9\". The test-suite takes the form of a
-- library containing a designated module that exports \"tests :: [Test]\".
--
| TestSuiteLibV09 Version ModuleName
-- | A test suite that does not conform to one of the above interfaces for
-- the given reason (e.g. unknown test type).
--
| TestSuiteUnsupported TestType
deriving (Eq, Generic, Read, Show, Typeable, Data)
instance Binary TestSuiteInterface
instance Monoid TestSuite where
mempty = TestSuite {
testName = mempty,
testInterface = mempty,
testBuildInfo = mempty,
testEnabled = False
}
mappend a b = TestSuite {
testName = combine' testName,
testInterface = combine testInterface,
testBuildInfo = combine testBuildInfo,
testEnabled = testEnabled a || testEnabled b
}
where combine field = field a `mappend` field b
combine' f = case (f a, f b) of
("", x) -> x
(x, "") -> x
(x, y) -> error "Ambiguous values for test field: '"
++ x ++ "' and '" ++ y ++ "'"
instance Monoid TestSuiteInterface where
mempty = TestSuiteUnsupported (TestTypeUnknown mempty (Version [] []))
mappend a (TestSuiteUnsupported _) = a
mappend _ b = b
emptyTestSuite :: TestSuite
emptyTestSuite = mempty
-- | Does this package have any test suites?
hasTests :: PackageDescription -> Bool
hasTests = any (buildable . testBuildInfo) . testSuites
-- | Get all the enabled test suites from a package.
enabledTests :: PackageDescription -> [TestSuite]
enabledTests = filter testEnabled . testSuites
-- | Perform an action on each buildable 'TestSuite' in a package.
withTest :: PackageDescription -> (TestSuite -> IO ()) -> IO ()
withTest pkg_descr f =
mapM_ f $ filter (buildable . testBuildInfo) $ enabledTests pkg_descr
-- | Get all the module names from a test suite.
testModules :: TestSuite -> [ModuleName]
testModules test = (case testInterface test of
TestSuiteLibV09 _ m -> [m]
_ -> [])
++ otherModules (testBuildInfo test)
-- | The \"test-type\" field in the test suite stanza.
--
data TestType = TestTypeExe Version -- ^ \"type: exitcode-stdio-x.y\"
| TestTypeLib Version -- ^ \"type: detailed-x.y\"
| TestTypeUnknown String Version -- ^ Some unknown test type e.g. \"type: foo\"
deriving (Generic, Show, Read, Eq, Typeable, Data)
instance Binary TestType
knownTestTypes :: [TestType]
knownTestTypes = [ TestTypeExe (Version [1,0] [])
, TestTypeLib (Version [0,9] []) ]
stdParse :: Text ver => (ver -> String -> res) -> Parse.ReadP r res
stdParse f = do
cs <- Parse.sepBy1 component (Parse.char '-')
_ <- Parse.char '-'
ver <- parse
let name = intercalate "-" cs
return $! f ver (lowercase name)
where
component = do
cs <- Parse.munch1 Char.isAlphaNum
if all Char.isDigit cs then Parse.pfail else return cs
-- each component must contain an alphabetic character, to avoid
-- ambiguity in identifiers like foo-1 (the 1 is the version number).
instance Text TestType where
disp (TestTypeExe ver) = text "exitcode-stdio-" <> disp ver
disp (TestTypeLib ver) = text "detailed-" <> disp ver
disp (TestTypeUnknown name ver) = text name <> char '-' <> disp ver
parse = stdParse $ \ver name -> case name of
"exitcode-stdio" -> TestTypeExe ver
"detailed" -> TestTypeLib ver
_ -> TestTypeUnknown name ver
testType :: TestSuite -> TestType
testType test = case testInterface test of
TestSuiteExeV10 ver _ -> TestTypeExe ver
TestSuiteLibV09 ver _ -> TestTypeLib ver
TestSuiteUnsupported testtype -> testtype
-- ---------------------------------------------------------------------------
-- The Benchmark type
-- | A \"benchmark\" stanza in a cabal file.
--
data Benchmark = Benchmark {
benchmarkName :: String,
benchmarkInterface :: BenchmarkInterface,
benchmarkBuildInfo :: BuildInfo,
benchmarkEnabled :: Bool
-- TODO: See TODO for 'testEnabled'.
}
deriving (Generic, Show, Read, Eq, Typeable, Data)
instance Binary Benchmark
-- | The benchmark interfaces that are currently defined. Each
-- benchmark must specify which interface it supports.
--
-- More interfaces may be defined in future, either new revisions or
-- totally new interfaces.
--
data BenchmarkInterface =
-- | Benchmark interface \"exitcode-stdio-1.0\". The benchmark
-- takes the form of an executable. It returns a zero exit code
-- for success, non-zero for failure. The stdout and stderr
-- channels may be logged. It takes no command line parameters
-- and nothing on stdin.
--
BenchmarkExeV10 Version FilePath
-- | A benchmark that does not conform to one of the above
-- interfaces for the given reason (e.g. unknown benchmark type).
--
| BenchmarkUnsupported BenchmarkType
deriving (Eq, Generic, Read, Show, Typeable, Data)
instance Binary BenchmarkInterface
instance Monoid Benchmark where
mempty = Benchmark {
benchmarkName = mempty,
benchmarkInterface = mempty,
benchmarkBuildInfo = mempty,
benchmarkEnabled = False
}
mappend a b = Benchmark {
benchmarkName = combine' benchmarkName,
benchmarkInterface = combine benchmarkInterface,
benchmarkBuildInfo = combine benchmarkBuildInfo,
benchmarkEnabled = benchmarkEnabled a || benchmarkEnabled b
}
where combine field = field a `mappend` field b
combine' f = case (f a, f b) of
("", x) -> x
(x, "") -> x
(x, y) -> error "Ambiguous values for benchmark field: '"
++ x ++ "' and '" ++ y ++ "'"
instance Monoid BenchmarkInterface where
mempty = BenchmarkUnsupported (BenchmarkTypeUnknown mempty (Version [] []))
mappend a (BenchmarkUnsupported _) = a
mappend _ b = b
emptyBenchmark :: Benchmark
emptyBenchmark = mempty
-- | Does this package have any benchmarks?
hasBenchmarks :: PackageDescription -> Bool
hasBenchmarks = any (buildable . benchmarkBuildInfo) . benchmarks
-- | Get all the enabled benchmarks from a package.
enabledBenchmarks :: PackageDescription -> [Benchmark]
enabledBenchmarks = filter benchmarkEnabled . benchmarks
-- | Perform an action on each buildable 'Benchmark' in a package.
withBenchmark :: PackageDescription -> (Benchmark -> IO ()) -> IO ()
withBenchmark pkg_descr f =
mapM_ f $ filter (buildable . benchmarkBuildInfo) $ enabledBenchmarks pkg_descr
-- | Get all the module names from a benchmark.
benchmarkModules :: Benchmark -> [ModuleName]
benchmarkModules benchmark = otherModules (benchmarkBuildInfo benchmark)
-- | The \"benchmark-type\" field in the benchmark stanza.
--
data BenchmarkType = BenchmarkTypeExe Version
-- ^ \"type: exitcode-stdio-x.y\"
| BenchmarkTypeUnknown String Version
-- ^ Some unknown benchmark type e.g. \"type: foo\"
deriving (Generic, Show, Read, Eq, Typeable, Data)
instance Binary BenchmarkType
knownBenchmarkTypes :: [BenchmarkType]
knownBenchmarkTypes = [ BenchmarkTypeExe (Version [1,0] []) ]
instance Text BenchmarkType where
disp (BenchmarkTypeExe ver) = text "exitcode-stdio-" <> disp ver
disp (BenchmarkTypeUnknown name ver) = text name <> char '-' <> disp ver
parse = stdParse $ \ver name -> case name of
"exitcode-stdio" -> BenchmarkTypeExe ver
_ -> BenchmarkTypeUnknown name ver
benchmarkType :: Benchmark -> BenchmarkType
benchmarkType benchmark = case benchmarkInterface benchmark of
BenchmarkExeV10 ver _ -> BenchmarkTypeExe ver
BenchmarkUnsupported benchmarktype -> benchmarktype
-- ---------------------------------------------------------------------------
-- The BuildInfo type
-- Consider refactoring into executable and library versions.
data BuildInfo = BuildInfo {
buildable :: Bool, -- ^ component is buildable here
buildTools :: [Dependency], -- ^ tools needed to build this bit
cppOptions :: [String], -- ^ options for pre-processing Haskell code
ccOptions :: [String], -- ^ options for C compiler
ldOptions :: [String], -- ^ options for linker
pkgconfigDepends :: [Dependency], -- ^ pkg-config packages that are used
frameworks :: [String], -- ^support frameworks for Mac OS X
cSources :: [FilePath],
jsSources :: [FilePath],
hsSourceDirs :: [FilePath], -- ^ where to look for the Haskell module hierarchy
otherModules :: [ModuleName], -- ^ non-exposed or non-main modules
defaultLanguage :: Maybe Language,-- ^ language used when not explicitly specified
otherLanguages :: [Language], -- ^ other languages used within the package
defaultExtensions :: [Extension], -- ^ language extensions used by all modules
otherExtensions :: [Extension], -- ^ other language extensions used within the package
oldExtensions :: [Extension], -- ^ the old extensions field, treated same as 'defaultExtensions'
extraLibs :: [String], -- ^ what libraries to link with when compiling a program that uses your package
extraGHCiLibs :: [String], -- ^ if present, overrides extraLibs when package is loaded with GHCi.
extraLibDirs :: [String],
includeDirs :: [FilePath], -- ^directories to find .h files
includes :: [FilePath], -- ^ The .h files to be found in includeDirs
installIncludes :: [FilePath], -- ^ .h files to install with the package
options :: [(CompilerFlavor,[String])],
profOptions :: [(CompilerFlavor,[String])],
sharedOptions :: [(CompilerFlavor,[String])],
customFieldsBI :: [(String,String)], -- ^Custom fields starting
-- with x-, stored in a
-- simple assoc-list.
targetBuildDepends :: [Dependency], -- ^ Dependencies specific to a library or executable target
targetBuildRenaming :: Map PackageName ModuleRenaming
}
deriving (Generic, Show, Read, Eq, Typeable, Data)
instance Binary BuildInfo
instance Monoid BuildInfo where
mempty = BuildInfo {
buildable = True,
buildTools = [],
cppOptions = [],
ccOptions = [],
ldOptions = [],
pkgconfigDepends = [],
frameworks = [],
cSources = [],
jsSources = [],
hsSourceDirs = [],
otherModules = [],
defaultLanguage = Nothing,
otherLanguages = [],
defaultExtensions = [],
otherExtensions = [],
oldExtensions = [],
extraLibs = [],
extraGHCiLibs = [],
extraLibDirs = [],
includeDirs = [],
includes = [],
installIncludes = [],
options = [],
profOptions = [],
sharedOptions = [],
customFieldsBI = [],
targetBuildDepends = [],
targetBuildRenaming = Map.empty
}
mappend a b = BuildInfo {
buildable = buildable a && buildable b,
buildTools = combine buildTools,
cppOptions = combine cppOptions,
ccOptions = combine ccOptions,
ldOptions = combine ldOptions,
pkgconfigDepends = combine pkgconfigDepends,
frameworks = combineNub frameworks,
cSources = combineNub cSources,
jsSources = combineNub jsSources,
hsSourceDirs = combineNub hsSourceDirs,
otherModules = combineNub otherModules,
defaultLanguage = combineMby defaultLanguage,
otherLanguages = combineNub otherLanguages,
defaultExtensions = combineNub defaultExtensions,
otherExtensions = combineNub otherExtensions,
oldExtensions = combineNub oldExtensions,
extraLibs = combine extraLibs,
extraGHCiLibs = combine extraGHCiLibs,
extraLibDirs = combineNub extraLibDirs,
includeDirs = combineNub includeDirs,
includes = combineNub includes,
installIncludes = combineNub installIncludes,
options = combine options,
profOptions = combine profOptions,
sharedOptions = combine sharedOptions,
customFieldsBI = combine customFieldsBI,
targetBuildDepends = combineNub targetBuildDepends,
targetBuildRenaming = combineMap targetBuildRenaming
}
where
combine field = field a `mappend` field b
combineNub field = nub (combine field)
combineMby field = field b `mplus` field a
combineMap field = Map.unionWith mappend (field a) (field b)
emptyBuildInfo :: BuildInfo
emptyBuildInfo = mempty
-- | The 'BuildInfo' for the library (if there is one and it's buildable), and
-- all buildable executables, test suites and benchmarks. Useful for gathering
-- dependencies.
allBuildInfo :: PackageDescription -> [BuildInfo]
allBuildInfo pkg_descr = [ bi | Just lib <- [library pkg_descr]
, let bi = libBuildInfo lib
, buildable bi ]
++ [ bi | exe <- executables pkg_descr
, let bi = buildInfo exe
, buildable bi ]
++ [ bi | tst <- testSuites pkg_descr
, let bi = testBuildInfo tst
, buildable bi
, testEnabled tst ]
++ [ bi | tst <- benchmarks pkg_descr
, let bi = benchmarkBuildInfo tst
, buildable bi
, benchmarkEnabled tst ]
--FIXME: many of the places where this is used, we actually want to look at
-- unbuildable bits too, probably need separate functions
-- | The 'Language's used by this component
--
allLanguages :: BuildInfo -> [Language]
allLanguages bi = maybeToList (defaultLanguage bi)
++ otherLanguages bi
-- | The 'Extension's that are used somewhere by this component
--
allExtensions :: BuildInfo -> [Extension]
allExtensions bi = usedExtensions bi
++ otherExtensions bi
-- | The 'Extensions' that are used by all modules in this component
--
usedExtensions :: BuildInfo -> [Extension]
usedExtensions bi = oldExtensions bi
++ defaultExtensions bi
type HookedBuildInfo = (Maybe BuildInfo, [(String, BuildInfo)])
emptyHookedBuildInfo :: HookedBuildInfo
emptyHookedBuildInfo = (Nothing, [])
-- |Select options for a particular Haskell compiler.
hcOptions :: CompilerFlavor -> BuildInfo -> [String]
hcOptions = lookupHcOptions options
hcProfOptions :: CompilerFlavor -> BuildInfo -> [String]
hcProfOptions = lookupHcOptions profOptions
hcSharedOptions :: CompilerFlavor -> BuildInfo -> [String]
hcSharedOptions = lookupHcOptions sharedOptions
lookupHcOptions :: (BuildInfo -> [(CompilerFlavor,[String])])
-> CompilerFlavor -> BuildInfo -> [String]
lookupHcOptions f hc bi = [ opt | (hc',opts) <- f bi
, hc' == hc
, opt <- opts ]
-- ------------------------------------------------------------
-- * Source repos
-- ------------------------------------------------------------
-- | Information about the source revision control system for a package.
--
-- When specifying a repo it is useful to know the meaning or intention of the
-- information as doing so enables automation. There are two obvious common
-- purposes: one is to find the repo for the latest development version, the
-- other is to find the repo for this specific release. The 'ReopKind'
-- specifies which one we mean (or another custom one).
--
-- A package can specify one or the other kind or both. Most will specify just
-- a head repo but some may want to specify a repo to reconstruct the sources
-- for this package release.
--
-- The required information is the 'RepoType' which tells us if it's using
-- 'Darcs', 'Git' for example. The 'repoLocation' and other details are
-- interpreted according to the repo type.
--
data SourceRepo = SourceRepo {
-- | The kind of repo. This field is required.
repoKind :: RepoKind,
-- | The type of the source repository system for this repo, eg 'Darcs' or
-- 'Git'. This field is required.
repoType :: Maybe RepoType,
-- | The location of the repository. For most 'RepoType's this is a URL.
-- This field is required.
repoLocation :: Maybe String,
-- | 'CVS' can put multiple \"modules\" on one server and requires a
-- module name in addition to the location to identify a particular repo.
-- Logically this is part of the location but unfortunately has to be
-- specified separately. This field is required for the 'CVS' 'RepoType' and
-- should not be given otherwise.
repoModule :: Maybe String,
-- | The name or identifier of the branch, if any. Many source control
-- systems have the notion of multiple branches in a repo that exist in the
-- same location. For example 'Git' and 'CVS' use this while systems like
-- 'Darcs' use different locations for different branches. This field is
-- optional but should be used if necessary to identify the sources,
-- especially for the 'RepoThis' repo kind.
repoBranch :: Maybe String,
-- | The tag identify a particular state of the repository. This should be
-- given for the 'RepoThis' repo kind and not for 'RepoHead' kind.
--
repoTag :: Maybe String,
-- | Some repositories contain multiple projects in different subdirectories
-- This field specifies the subdirectory where this packages sources can be
-- found, eg the subdirectory containing the @.cabal@ file. It is interpreted
-- relative to the root of the repository. This field is optional. If not
-- given the default is \".\" ie no subdirectory.
repoSubdir :: Maybe FilePath
}
deriving (Eq, Generic, Read, Show, Typeable, Data)
instance Binary SourceRepo
-- | What this repo info is for, what it represents.
--
data RepoKind =
-- | The repository for the \"head\" or development version of the project.
-- This repo is where we should track the latest development activity or
-- the usual repo people should get to contribute patches.
RepoHead
-- | The repository containing the sources for this exact package version
-- or release. For this kind of repo a tag should be given to give enough
-- information to re-create the exact sources.
| RepoThis
| RepoKindUnknown String
deriving (Eq, Generic, Ord, Read, Show, Typeable, Data)
instance Binary RepoKind
-- | An enumeration of common source control systems. The fields used in the
-- 'SourceRepo' depend on the type of repo. The tools and methods used to
-- obtain and track the repo depend on the repo type.
--
data RepoType = Darcs | Git | SVN | CVS
| Mercurial | GnuArch | Bazaar | Monotone
| OtherRepoType String
deriving (Eq, Generic, Ord, Read, Show, Typeable, Data)
instance Binary RepoType
knownRepoTypes :: [RepoType]
knownRepoTypes = [Darcs, Git, SVN, CVS
,Mercurial, GnuArch, Bazaar, Monotone]
repoTypeAliases :: RepoType -> [String]
repoTypeAliases Bazaar = ["bzr"]
repoTypeAliases Mercurial = ["hg"]
repoTypeAliases GnuArch = ["arch"]
repoTypeAliases _ = []
instance Text RepoKind where
disp RepoHead = Disp.text "head"
disp RepoThis = Disp.text "this"
disp (RepoKindUnknown other) = Disp.text other
parse = do
name <- ident
return $ case lowercase name of
"head" -> RepoHead
"this" -> RepoThis
_ -> RepoKindUnknown name
instance Text RepoType where
disp (OtherRepoType other) = Disp.text other
disp other = Disp.text (lowercase (show other))
parse = fmap classifyRepoType ident
classifyRepoType :: String -> RepoType
classifyRepoType s =
fromMaybe (OtherRepoType s) $ lookup (lowercase s) repoTypeMap
where
repoTypeMap = [ (name, repoType')
| repoType' <- knownRepoTypes
, name <- display repoType' : repoTypeAliases repoType' ]
ident :: Parse.ReadP r String
ident = Parse.munch1 (\c -> Char.isAlphaNum c || c == '_' || c == '-')
lowercase :: String -> String
lowercase = map Char.toLower
-- ------------------------------------------------------------
-- * Utils
-- ------------------------------------------------------------
updatePackageDescription :: HookedBuildInfo -> PackageDescription -> PackageDescription
updatePackageDescription (mb_lib_bi, exe_bi) p
= p{ executables = updateExecutables exe_bi (executables p)
, library = updateLibrary mb_lib_bi (library p)
}
where
updateLibrary :: Maybe BuildInfo -> Maybe Library -> Maybe Library
updateLibrary (Just bi) (Just lib) = Just (lib{libBuildInfo = bi `mappend` libBuildInfo lib})
updateLibrary Nothing mb_lib = mb_lib
updateLibrary (Just _) Nothing = Nothing
updateExecutables :: [(String, BuildInfo)] -- ^[(exeName, new buildinfo)]
-> [Executable] -- ^list of executables to update
-> [Executable] -- ^list with exeNames updated
updateExecutables exe_bi' executables' = foldr updateExecutable executables' exe_bi'
updateExecutable :: (String, BuildInfo) -- ^(exeName, new buildinfo)
-> [Executable] -- ^list of executables to update
-> [Executable] -- ^list with exeName updated
updateExecutable _ [] = []
updateExecutable exe_bi'@(name,bi) (exe:exes)
| exeName exe == name = exe{buildInfo = bi `mappend` buildInfo exe} : exes
| otherwise = exe : updateExecutable exe_bi' exes
-- ---------------------------------------------------------------------------
-- The GenericPackageDescription type
data GenericPackageDescription =
GenericPackageDescription {
packageDescription :: PackageDescription,
genPackageFlags :: [Flag],
condLibrary :: Maybe (CondTree ConfVar [Dependency] Library),
condExecutables :: [(String, CondTree ConfVar [Dependency] Executable)],
condTestSuites :: [(String, CondTree ConfVar [Dependency] TestSuite)],
condBenchmarks :: [(String, CondTree ConfVar [Dependency] Benchmark)]
}
deriving (Show, Eq, Typeable, Data)
instance Package GenericPackageDescription where
packageId = packageId . packageDescription
--TODO: make PackageDescription an instance of Text.
-- | A flag can represent a feature to be included, or a way of linking
-- a target against its dependencies, or in fact whatever you can think of.
data Flag = MkFlag
{ flagName :: FlagName
, flagDescription :: String
, flagDefault :: Bool
, flagManual :: Bool
}
deriving (Show, Eq, Typeable, Data)
-- | A 'FlagName' is the name of a user-defined configuration flag
newtype FlagName = FlagName String
deriving (Eq, Generic, Ord, Show, Read, Typeable, Data)
instance Binary FlagName
-- | A 'FlagAssignment' is a total or partial mapping of 'FlagName's to
-- 'Bool' flag values. It represents the flags chosen by the user or
-- discovered during configuration. For example @--flags=foo --flags=-bar@
-- becomes @[("foo", True), ("bar", False)]@
--
type FlagAssignment = [(FlagName, Bool)]
-- | A @ConfVar@ represents the variable type used.
data ConfVar = OS OS
| Arch Arch
| Flag FlagName
| Impl CompilerFlavor VersionRange
deriving (Eq, Show, Typeable, Data)
-- | A boolean expression parameterized over the variable type used.
data Condition c = Var c
| Lit Bool
| CNot (Condition c)
| COr (Condition c) (Condition c)
| CAnd (Condition c) (Condition c)
deriving (Show, Eq, Typeable, Data)
instance Functor Condition where
f `fmap` Var c = Var (f c)
_ `fmap` Lit c = Lit c
f `fmap` CNot c = CNot (fmap f c)
f `fmap` COr c d = COr (fmap f c) (fmap f d)
f `fmap` CAnd c d = CAnd (fmap f c) (fmap f d)
instance Foldable Condition where
f `foldMap` Var c = f c
_ `foldMap` Lit _ = mempty
f `foldMap` CNot c = foldMap f c
f `foldMap` COr c d = foldMap f c `mappend` foldMap f d
f `foldMap` CAnd c d = foldMap f c `mappend` foldMap f d
instance Traversable Condition where
f `traverse` Var c = Var `fmap` f c
_ `traverse` Lit c = pure $ Lit c
f `traverse` CNot c = CNot `fmap` traverse f c
f `traverse` COr c d = COr `fmap` traverse f c <*> traverse f d
f `traverse` CAnd c d = CAnd `fmap` traverse f c <*> traverse f d
data CondTree v c a = CondNode
{ condTreeData :: a
, condTreeConstraints :: c
, condTreeComponents :: [( Condition v
, CondTree v c a
, Maybe (CondTree v c a))]
}
deriving (Show, Eq, Typeable, Data)
|
Helkafen/cabal
|
Cabal/Distribution/PackageDescription.hs
|
bsd-3-clause
| 47,042
| 0
| 16
| 13,252
| 8,722
| 4,896
| 3,826
| 747
| 4
|
module StaticFlags where
import System.Environment
import System.IO.Unsafe
{-# NOINLINE aSSERTIONS #-}
aSSERTIONS :: Bool
aSSERTIONS = not $ "--no-assertions" `elem` unsafePerformIO getArgs
{-# NOINLINE qUIET #-}
qUIET :: Bool
qUIET = "-v0" `elem` unsafePerformIO getArgs
|
batterseapower/mini-ghc
|
StaticFlags.hs
|
bsd-3-clause
| 276
| 0
| 6
| 39
| 59
| 36
| 23
| 9
| 1
|
{- | Module : $Header$
- Description : Implementation of logic formula parser
- Copyright : (c) Georgel Calin & Lutz Schroeder, DFKI Lab Bremen
- License : GPLv2 or higher, see LICENSE.txt
- Maintainer : g.calin@jacobs-university.de
- Stability : provisional
- Portability : portable
-
- Provides the implementation of the generic parser for the Boole datatype
-}
module Parser where
import Text.ParserCombinators.Parsec
-- import GenericSequent
import ModalLogic
import CombLogic
data ModalOperator = Sqr | Ang | None deriving Eq
{- | Main parser
par5er :: ModalOperator -> [GenParser Char st a] -> GenParser Char st (Boole a) -}
par5er = implFormula
{- | Parser which translates all implications in disjunctions & conjunctions
implFormula :: ModalOperator -> [GenParser Char st a] -> GenParser Char st (Boole a) -}
implFormula flag logics = do
f <- orFormula flag logics
option f (do string "->"
spaces
i <- implFormula flag logics
return $ Not (And f (Not i))
<|> do try (string "<->")
spaces
i <- implFormula flag logics
return $ And (Not (And f (Not i))) (Not (And (Not f) i))
<|> do string "<-"
spaces
i <- implFormula flag logics
return $ And (Not f) i
<|> return f
<?> "GMPParser.implFormula")
{- | Parser for disjunction - used for handling binding order
orFormula :: ModalOperator -> [GenParser Char st a] -> GenParser Char st (Boole a) -}
orFormula flag logics = do
f <- andFormula flag logics
option f $ do
string "\\/"
spaces
g <- orFormula flag logics
return $ Not (And (Not f) (Not g))
<?> "GMPParser.orFormula"
{- | Parser for conjunction - used for handling the binding order
andFormula :: ModalOperator -> [GenParser Char st a] -> GenParser Char st (Boole a) -}
andFormula flag logics = do
f <- primFormula flag logics
option f $ do
string "/\\"
spaces
g <- andFormula flag logics
return $ And f g
<?> "GMPParser.andFormula"
{- | Parse a primitive formula: T, F, ~f, <i>f, [i]f,
- where i stands for an index, f for a formula/boolean expression
primFormula :: ModalOperator -> [GenParser Char st a] -> GenParser Char st (Boole a) -}
primFormula flag logics = do string "T"
spaces
return T
<|> do string "F"
spaces
return F
<|> parenFormula flag logics
<|> do string "~"
spaces
f <- primFormula flag logics
return $ Not f
<|> atomFormula flag logics
<?> "GMPParser.primFormula"
-- modalAtom :: ModalOperator -> [Int] -> GenParser Char st (Boole a)
atomFormula flag logics = do char '<'
spaces
let h = head logics
let t = tail logics
case h of
1 -> do parseKindex
spaces
char '>'
spaces
f <- primFormula flag $ t ++ [h]
case flag of
-- FIXME: cannot construct the infinite type
Ang -> return $ At (K f) -- M i f
Sqr -> return $ Not (At (K (Not f)))
_ -> return $ At (K f)
{-
2 -> do parseKDindex
spaces
char '>'
spaces
f <- primFormula flag $ t ++ [h]
case flag of
Ang -> return $ At (KD f)--M i f
Sqr -> return $ Not (At (KD (Not f)))
_ -> return $ At (KD f)
_ -> do aux <- parseGindex
return aux
<|> do char '['
spaces
i <- head pa
spaces
char ']'
spaces
f <- primFormula flag $ tail pa ++ [head pa]
case flag of
Ang -> return $ Not (At (Not (Box i f)))
Sqr -> return $ At (Box i f)
_ -> return $ At (Box i f)
-}
{- | Parser for un-parenthesizing a formula
parenFormula :: ModalOperator -> [GenParser Char st a] -> GenParser Char st (Boole a) -}
parenFormula flag logics = do char '('
spaces
f <- par5er flag logics
spaces
char ')'
spaces
return f
<?> "GMPParser.parenFormula"
-- | Parse integer number
natural :: GenParser Char st Integer
natural = fmap read $ many1 digit
-- | Parser for Coalition Logic index
parseCindex :: Parser [Int]
parseCindex = do -- checks whether there are more numbers to be parsed
let stopParser = do char ','
return False
<|> do char '}'
return True
<?> "Parser.parseCindex.stop"
-- checks whether the index is of the for x1,..,x&
let normalParser l = do x <- natural
let n = fromInteger x
spaces
q <- stopParser
spaces
if q then normalParser (n : l)
else return (n : l)
<?> "Parser.parseCindex.normal"
char '{'
try (normalParser [])
<|> do -- checks whether the index is of the form "n..m"
let shortParser = do x <- natural
let n = fromInteger x
spaces
string ".."
spaces
y <- natural
let m = fromInteger y
return [n .. m]
<?> "Parser.parseCindex.short"
try shortParser
<?> "Parser.parseCindex"
-- | Parser for Graded Modal Logic index
parseGindex :: Parser Int
parseGindex = do n <- natural
return $ fromInteger n
<?> "Parser.parseGindex"
-- | Parser for Hennesy-Milner Modal Logic index
parseHMindex :: Parser Char
parseHMindex = letter
<?> "Parser.parseHMindex"
-- | Parser for K Modal Logic index
parseKindex :: Parser ()
parseKindex = return ()
-- | Parser for KD Modal Logic index
parseKDindex :: Parser ()
parseKDindex = return ()
-- | Parser for Probability Logic index
parsePindex :: Parser Rational
parsePindex =
do x <- natural
let auxP n = do char '/'
m <- natural
return $ toRational (fromInteger n / fromInteger m)
<|> do char '.'
m <- natural
let noDig n = let tmp = n < 10
in if tmp then 1
else 1 + noDig (div n 10)
let rat n = toRational (fromInteger n /
fromInteger (10 ^ noDig n))
let res = toRational n + rat m
return res
<|> return (toRational n)
<?> "Parser.parsePindex.auxP"
auxP x
-- | Parser for Monotonic Modal Logic index
parseMindex :: Parser ()
parseMindex = return ()
|
mariefarrell/Hets
|
GMP/Parser.hs
|
gpl-2.0
| 8,690
| 0
| 24
| 4,407
| 1,357
| 619
| 738
| 135
| 3
|
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable #-}
{-
Copyright (C) 2014 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.MediaBag
Copyright : Copyright (C) 2014 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Definition of a MediaBag object to hold binary resources, and an
interface for interacting with it.
-}
module Text.Pandoc.MediaBag (
MediaBag,
lookupMedia,
insertMedia,
mediaDirectory,
extractMediaBag
) where
import System.FilePath
import qualified System.FilePath.Posix as Posix
import System.Directory (createDirectoryIfMissing)
import qualified Data.Map as M
import qualified Data.ByteString.Lazy as BL
import Data.Monoid (Monoid)
import Control.Monad (when)
import Text.Pandoc.MIME (MimeType, getMimeTypeDef)
import qualified Text.Pandoc.UTF8 as UTF8
import Data.Maybe (fromMaybe)
import System.IO (stderr)
import Data.Data (Data)
import Data.Typeable (Typeable)
-- | A container for a collection of binary resources, with names and
-- mime types. Note that a 'MediaBag' is a Monoid, so 'mempty'
-- can be used for an empty 'MediaBag', and '<>' can be used to append
-- two 'MediaBag's.
newtype MediaBag = MediaBag (M.Map [String] (MimeType, BL.ByteString))
deriving (Monoid, Data, Typeable)
instance Show MediaBag where
show bag = "MediaBag " ++ show (mediaDirectory bag)
-- | Insert a media item into a 'MediaBag', replacing any existing
-- value with the same name.
insertMedia :: FilePath -- ^ relative path and canonical name of resource
-> Maybe MimeType -- ^ mime type (Nothing = determine from extension)
-> BL.ByteString -- ^ contents of resource
-> MediaBag
-> MediaBag
insertMedia fp mbMime contents (MediaBag mediamap) =
MediaBag (M.insert (splitDirectories fp) (mime, contents) mediamap)
where mime = fromMaybe fallback mbMime
fallback = case takeExtension fp of
".gz" -> getMimeTypeDef $ dropExtension fp
_ -> getMimeTypeDef fp
-- | Lookup a media item in a 'MediaBag', returning mime type and contents.
lookupMedia :: FilePath
-> MediaBag
-> Maybe (MimeType, BL.ByteString)
lookupMedia fp (MediaBag mediamap) = M.lookup (splitDirectories fp) mediamap
-- | Get a list of the file paths stored in a 'MediaBag', with
-- their corresponding mime types and the lengths in bytes of the contents.
mediaDirectory :: MediaBag -> [(String, MimeType, Int)]
mediaDirectory (MediaBag mediamap) =
M.foldWithKey (\fp (mime,contents) ->
(((Posix.joinPath fp), mime, fromIntegral $ BL.length contents):)) [] mediamap
-- | Extract contents of MediaBag to a given directory. Print informational
-- messages if 'verbose' is true.
extractMediaBag :: Bool
-> FilePath
-> MediaBag
-> IO ()
extractMediaBag verbose dir (MediaBag mediamap) = do
sequence_ $ M.foldWithKey
(\fp (_ ,contents) ->
((writeMedia verbose dir (Posix.joinPath fp, contents)):)) [] mediamap
writeMedia :: Bool -> FilePath -> (FilePath, BL.ByteString) -> IO ()
writeMedia verbose dir (subpath, bs) = do
-- we join and split to convert a/b/c to a\b\c on Windows;
-- in zip containers all paths use /
let fullpath = dir </> normalise subpath
createDirectoryIfMissing True $ takeDirectory fullpath
when verbose $ UTF8.hPutStrLn stderr $ "pandoc: extracting " ++ fullpath
BL.writeFile fullpath bs
|
ddssff/pandoc
|
src/Text/Pandoc/MediaBag.hs
|
gpl-2.0
| 4,381
| 0
| 16
| 1,003
| 713
| 397
| 316
| 57
| 2
|
-- | This is a simple line-based protocol used for communication between
-- a local and remote propellor. It's sent over a ssh channel, and lines of
-- the protocol can be interspersed with other, non-protocol lines
-- that should be passed through to be displayed.
--
-- Avoid making backwards-incompatible changes to this protocol,
-- since propellor needs to use this protocol to update itself to new
-- versions speaking newer versions of the protocol.
module Propellor.Protocol where
import Data.List
import Propellor.Base
data Stage = NeedGitClone | NeedRepoUrl | NeedPrivData | NeedGitPush | NeedPrecompiled
deriving (Read, Show, Eq)
type Marker = String
type Marked = String
statusMarker :: Marker
statusMarker = "STATUS"
privDataMarker :: String
privDataMarker = "PRIVDATA "
repoUrlMarker :: String
repoUrlMarker = "REPOURL "
gitPushMarker :: String
gitPushMarker = "GITPUSH"
toMarked :: Marker -> String -> String
toMarked = (++)
fromMarked :: Marker -> Marked -> Maybe String
fromMarked marker s
| marker `isPrefixOf` s = Just $ drop (length marker) s
| otherwise = Nothing
sendMarked :: Handle -> Marker -> String -> IO ()
sendMarked h marker s = do
debug ["sent marked", marker]
sendMarked' h marker s
sendMarked' :: Handle -> Marker -> String -> IO ()
sendMarked' h marker s = do
-- Prefix string with newline because sometimes a
-- incomplete line has been output, and the marker needs to
-- come at the start of a line.
hPutStrLn h ("\n" ++ toMarked marker s)
hFlush h
getMarked :: Handle -> Marker -> IO (Maybe String)
getMarked h marker = go =<< catchMaybeIO (hGetLine h)
where
go Nothing = return Nothing
go (Just l) = case fromMarked marker l of
Nothing -> do
unless (null l) $
hPutStrLn stderr l
getMarked h marker
Just v -> do
debug ["received marked", marker]
return (Just v)
req :: Stage -> Marker -> (String -> IO ()) -> IO ()
req stage marker a = do
debug ["requested marked", marker]
sendMarked' stdout statusMarker (show stage)
maybe noop a =<< getMarked stdin marker
|
ArchiveTeam/glowing-computing-machine
|
src/Propellor/Protocol.hs
|
bsd-2-clause
| 2,048
| 4
| 15
| 389
| 555
| 284
| 271
| 45
| 3
|
f [] y = y; f (x : xs) y = let z = g x y in f xs z
|
mpickering/hlint-refactor
|
tests/examples/ListRec7.hs
|
bsd-3-clause
| 50
| 0
| 9
| 20
| 52
| 25
| 27
| 1
| 1
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="fr-FR">
<title>MacOS WebDrivers</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/webdrivers/webdrivermacos/src/main/javahelp/org/zaproxy/zap/extension/webdrivermacos/resources/help_fr_FR/helpset_fr_FR.hs
|
apache-2.0
| 961
| 77
| 66
| 156
| 407
| 206
| 201
| -1
| -1
|
module ComplexParamIn2 where
--The application of a function is replaced by the right-hand side of the definition,
--with actual parameters replacing formals.
data Tup a b = Tup a b
--In this example, unfold the first 'sq' in 'sumSquares'
--This example aims to test unfolding a definition with guards.
sumSquares x y = (case (x, y) of
(m, n) -> sq (Tup n m))
sq (Tup n m) = m^n
|
kmate/HaRe
|
old/testing/foldDef/ComplexParamIn2_TokOut.hs
|
bsd-3-clause
| 409
| 0
| 11
| 100
| 87
| 50
| 37
| 5
| 1
|
module Main(main) where
main = sequence_ [ f x y | x <- [0,
1000,
1000000000000, -- > 2^32
1000000000000000000000000, -- > 2^64
-1000,
-1000000000000, -- < -2^32
-1000000000000000000000000] -- < -2^64
, y <- [0, -10, 10] ]
f :: Integer -> Int -> IO ()
f x y = do putStrLn "------------------------"
print x
print y
let d :: Double
d = encodeFloat x y
(xd, yd) = decodeFloat d
{- let f :: Float
f = encodeFloat x y
(xf, yf) = decodeFloat f -}
print d
print xd
print yd
-- print f
-- print xf
-- print yf
|
k-bx/ghcjs
|
test/pkg/base/Numeric/num010.hs
|
mit
| 922
| 0
| 10
| 522
| 185
| 97
| 88
| 19
| 1
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
-- | A representation where all bindings are annotated with aliasing
-- information.
module Futhark.IR.Aliases
( -- * The representation definition
Aliases,
AliasDec (..),
VarAliases,
ConsumedInExp,
BodyAliasing,
module Futhark.IR.Prop.Aliases,
-- * Module re-exports
module Futhark.IR.Prop,
module Futhark.IR.Traversals,
module Futhark.IR.Pretty,
module Futhark.IR.Syntax,
-- * Adding aliases
addAliasesToPat,
mkAliasedLetStm,
mkAliasedBody,
mkPatAliases,
mkBodyAliases,
-- * Removing aliases
removeProgAliases,
removeFunDefAliases,
removeExpAliases,
removeStmAliases,
removeLambdaAliases,
removePatAliases,
removeScopeAliases,
-- * Tracking aliases
AliasesAndConsumed,
trackAliases,
mkStmsAliases,
)
where
import Control.Monad.Identity
import Control.Monad.Reader
import qualified Data.Map.Strict as M
import Data.Maybe
import Futhark.Analysis.Rephrase
import Futhark.Builder
import Futhark.IR.Pretty
import Futhark.IR.Prop
import Futhark.IR.Prop.Aliases
import Futhark.IR.Syntax
import Futhark.IR.Traversals
import Futhark.Transform.Rename
import Futhark.Transform.Substitute
import qualified Futhark.Util.Pretty as PP
-- | The rep for the basic representation.
data Aliases rep
-- | A wrapper around 'AliasDec' to get around the fact that we need an
-- 'Ord' instance, which 'AliasDec does not have.
newtype AliasDec = AliasDec {unAliases :: Names}
deriving (Show)
instance Semigroup AliasDec where
x <> y = AliasDec $ unAliases x <> unAliases y
instance Monoid AliasDec where
mempty = AliasDec mempty
instance Eq AliasDec where
_ == _ = True
instance Ord AliasDec where
_ `compare` _ = EQ
instance Rename AliasDec where
rename (AliasDec names) = AliasDec <$> rename names
instance Substitute AliasDec where
substituteNames substs (AliasDec names) = AliasDec $ substituteNames substs names
instance FreeIn AliasDec where
freeIn' = const mempty
instance PP.Pretty AliasDec where
ppr = PP.braces . PP.commasep . map PP.ppr . namesToList . unAliases
-- | The aliases of the let-bound variable.
type VarAliases = AliasDec
-- | Everything consumed in the expression.
type ConsumedInExp = AliasDec
-- | The aliases of what is returned by the t'Body', and what is
-- consumed inside of it.
type BodyAliasing = ([VarAliases], ConsumedInExp)
instance (RepTypes rep, CanBeAliased (Op rep)) => RepTypes (Aliases rep) where
type LetDec (Aliases rep) = (VarAliases, LetDec rep)
type ExpDec (Aliases rep) = (ConsumedInExp, ExpDec rep)
type BodyDec (Aliases rep) = (BodyAliasing, BodyDec rep)
type FParamInfo (Aliases rep) = FParamInfo rep
type LParamInfo (Aliases rep) = LParamInfo rep
type RetType (Aliases rep) = RetType rep
type BranchType (Aliases rep) = BranchType rep
type Op (Aliases rep) = OpWithAliases (Op rep)
instance AliasesOf (VarAliases, dec) where
aliasesOf = unAliases . fst
instance FreeDec AliasDec
withoutAliases ::
(HasScope (Aliases rep) m, Monad m) =>
ReaderT (Scope rep) m a ->
m a
withoutAliases m = do
scope <- asksScope removeScopeAliases
runReaderT m scope
instance (ASTRep rep, CanBeAliased (Op rep)) => ASTRep (Aliases rep) where
expTypesFromPat =
withoutAliases . expTypesFromPat . removePatAliases
instance (ASTRep rep, CanBeAliased (Op rep)) => Aliased (Aliases rep) where
bodyAliases = map unAliases . fst . fst . bodyDec
consumedInBody = unAliases . snd . fst . bodyDec
instance (ASTRep rep, CanBeAliased (Op rep)) => PrettyRep (Aliases rep) where
ppExpDec (consumed, inner) e =
maybeComment . catMaybes $
[exp_dec, merge_dec, ppExpDec inner $ removeExpAliases e]
where
merge_dec =
case e of
DoLoop merge _ body ->
let mergeParamAliases fparam als
| primType (paramType fparam) =
Nothing
| otherwise =
resultAliasComment (paramName fparam) als
in maybeComment . catMaybes $
zipWith mergeParamAliases (map fst merge) $
bodyAliases body
_ -> Nothing
exp_dec = case namesToList $ unAliases consumed of
[] -> Nothing
als ->
Just $
PP.oneLine $
PP.text "-- Consumes " <> PP.commasep (map PP.ppr als)
maybeComment :: [PP.Doc] -> Maybe PP.Doc
maybeComment [] = Nothing
maybeComment cs = Just $ PP.folddoc (PP.</>) cs
resultAliasComment :: PP.Pretty a => a -> Names -> Maybe PP.Doc
resultAliasComment name als =
case namesToList als of
[] -> Nothing
als' ->
Just $
PP.oneLine $
PP.text "-- Result for " <> PP.ppr name <> PP.text " aliases "
<> PP.commasep (map PP.ppr als')
removeAliases :: CanBeAliased (Op rep) => Rephraser Identity (Aliases rep) rep
removeAliases =
Rephraser
{ rephraseExpDec = return . snd,
rephraseLetBoundDec = return . snd,
rephraseBodyDec = return . snd,
rephraseFParamDec = return,
rephraseLParamDec = return,
rephraseRetType = return,
rephraseBranchType = return,
rephraseOp = return . removeOpAliases
}
removeScopeAliases :: Scope (Aliases rep) -> Scope rep
removeScopeAliases = M.map unAlias
where
unAlias (LetName (_, dec)) = LetName dec
unAlias (FParamName dec) = FParamName dec
unAlias (LParamName dec) = LParamName dec
unAlias (IndexName it) = IndexName it
removeProgAliases ::
CanBeAliased (Op rep) =>
Prog (Aliases rep) ->
Prog rep
removeProgAliases = runIdentity . rephraseProg removeAliases
removeFunDefAliases ::
CanBeAliased (Op rep) =>
FunDef (Aliases rep) ->
FunDef rep
removeFunDefAliases = runIdentity . rephraseFunDef removeAliases
removeExpAliases ::
CanBeAliased (Op rep) =>
Exp (Aliases rep) ->
Exp rep
removeExpAliases = runIdentity . rephraseExp removeAliases
removeStmAliases ::
CanBeAliased (Op rep) =>
Stm (Aliases rep) ->
Stm rep
removeStmAliases = runIdentity . rephraseStm removeAliases
removeLambdaAliases ::
CanBeAliased (Op rep) =>
Lambda (Aliases rep) ->
Lambda rep
removeLambdaAliases = runIdentity . rephraseLambda removeAliases
removePatAliases ::
Pat (AliasDec, a) ->
Pat a
removePatAliases = runIdentity . rephrasePat (return . snd)
addAliasesToPat ::
(ASTRep rep, CanBeAliased (Op rep), Typed dec) =>
Pat dec ->
Exp (Aliases rep) ->
Pat (VarAliases, dec)
addAliasesToPat pat e =
Pat $ mkPatAliases pat e
mkAliasedBody ::
(ASTRep rep, CanBeAliased (Op rep)) =>
BodyDec rep ->
Stms (Aliases rep) ->
Result ->
Body (Aliases rep)
mkAliasedBody dec stms res =
Body (mkBodyAliases stms res, dec) stms res
mkPatAliases ::
(Aliased rep, Typed dec) =>
Pat dec ->
Exp rep ->
[PatElem (VarAliases, dec)]
mkPatAliases pat e =
let als = expAliases e ++ repeat mempty
in -- In case the pattern has
-- more elements (this
-- implies a type error).
zipWith annotatePatElem (patElems pat) als
where
annotatePatElem bindee names =
bindee `setPatElemDec` (AliasDec names', patElemDec bindee)
where
names' =
case patElemType bindee of
Array {} -> names
Mem _ -> names
_ -> mempty
mkBodyAliases ::
Aliased rep =>
Stms rep ->
Result ->
BodyAliasing
mkBodyAliases stms res =
-- We need to remove the names that are bound in stms from the alias
-- and consumption sets. We do this by computing the transitive
-- closure of the alias map (within stms), then removing anything
-- bound in stms.
let (aliases, consumed) = mkStmsAliases stms res
boundNames = foldMap (namesFromList . patNames . stmPat) stms
aliases' = map (`namesSubtract` boundNames) aliases
consumed' = consumed `namesSubtract` boundNames
in (map AliasDec aliases', AliasDec consumed')
-- | The aliases of the result and everything consumed in the given
-- statements.
mkStmsAliases ::
Aliased rep =>
Stms rep ->
Result ->
([Names], Names)
mkStmsAliases stms res = delve mempty $ stmsToList stms
where
delve (aliasmap, consumed) [] =
( map (aliasClosure aliasmap . subExpAliases . resSubExp) res,
consumed
)
delve (aliasmap, consumed) (stm : stms') =
delve (trackAliases (aliasmap, consumed) stm) stms'
aliasClosure aliasmap names =
names <> mconcat (map look $ namesToList names)
where
look k = M.findWithDefault mempty k aliasmap
type AliasesAndConsumed =
( M.Map VName Names,
Names
)
trackAliases ::
Aliased rep =>
AliasesAndConsumed ->
Stm rep ->
AliasesAndConsumed
trackAliases (aliasmap, consumed) stm =
let pat = stmPat stm
pe_als =
zip (patNames pat) $ map addAliasesOfAliases $ patAliases pat
als = M.fromList pe_als
rev_als = foldMap revAls pe_als
revAls (v, v_als) =
M.fromList $ map (,oneName v) $ namesToList v_als
comb = M.unionWith (<>)
aliasmap' = rev_als `comb` als `comb` aliasmap
consumed' = consumed <> addAliasesOfAliases (consumedInStm stm)
in (aliasmap', consumed')
where
addAliasesOfAliases names = names <> aliasesOfAliases names
aliasesOfAliases = mconcat . map look . namesToList
look k = M.findWithDefault mempty k aliasmap
mkAliasedLetStm ::
(ASTRep rep, CanBeAliased (Op rep)) =>
Pat (LetDec rep) ->
StmAux (ExpDec rep) ->
Exp (Aliases rep) ->
Stm (Aliases rep)
mkAliasedLetStm pat (StmAux cs attrs dec) e =
Let
(addAliasesToPat pat e)
(StmAux cs attrs (AliasDec $ consumedInExp e, dec))
e
instance (Buildable rep, CanBeAliased (Op rep)) => Buildable (Aliases rep) where
mkExpDec pat e =
let dec = mkExpDec (removePatAliases pat) $ removeExpAliases e
in (AliasDec $ consumedInExp e, dec)
mkExpPat ids e =
addAliasesToPat (mkExpPat ids $ removeExpAliases e) e
mkLetNames names e = do
env <- asksScope removeScopeAliases
flip runReaderT env $ do
Let pat dec _ <- mkLetNames names $ removeExpAliases e
return $ mkAliasedLetStm pat dec e
mkBody stms res =
let Body bodyrep _ _ = mkBody (fmap removeStmAliases stms) res
in mkAliasedBody bodyrep stms res
instance (ASTRep (Aliases rep), Buildable (Aliases rep)) => BuilderOps (Aliases rep)
|
diku-dk/futhark
|
src/Futhark/IR/Aliases.hs
|
isc
| 10,513
| 0
| 20
| 2,411
| 3,105
| 1,610
| 1,495
| -1
| -1
|
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module ZoomHub.Web.Types.EmbedId
( EmbedId,
unEmbedId,
)
where
import Data.Bifunctor (first)
import qualified Data.ByteString.Char8 as BC
import qualified Data.Text as T
import Network.HTTP.Types (decodePath)
import Servant (FromHttpApiData, parseUrlPiece)
import System.FilePath (splitExtension)
import ZoomHub.Types.ContentId (ContentId)
import qualified ZoomHub.Types.ContentId as ContentId
newtype EmbedId = EmbedId {unEmbedId :: ContentId} deriving (Eq, Show)
fromString :: String -> Either String EmbedId
fromString s = case maybeContentId of
Just contentId -> Right $ EmbedId contentId
_ -> Left "Invalid embed ID"
where
pathAndQuery = decodePath (BC.pack s)
(pathSegments, _) = pathAndQuery
maybeContentId = case pathSegments of
[p] ->
let idParts = splitExtension . T.unpack $ p
in case idParts of
(cId, ".js") -> Just $ ContentId.fromString cId
_ -> Nothing
_ -> Nothing
-- Text
instance FromHttpApiData EmbedId where
parseUrlPiece p = first T.pack $ fromString . T.unpack $ p
|
zoomhub/zoomhub
|
src/ZoomHub/Web/Types/EmbedId.hs
|
mit
| 1,144
| 0
| 17
| 231
| 315
| 179
| 136
| 29
| 4
|
module P033Spec where
import qualified P033 as P
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "solveBasic" $
it "勘違いの約分をしても正しくなる分数の積の分母" $
P.solveBasic `shouldBe` 100
describe "solve" $
it "勘違いの約分をしても正しくなる分数の積の分母" $
P.solve `shouldBe` 100
|
yyotti/euler_haskell
|
test/P033Spec.hs
|
mit
| 392
| 0
| 10
| 70
| 93
| 50
| 43
| 13
| 1
|
module Proteome.Project where
import qualified Control.Lens as Lens (element, firstOf)
import Path (Abs, Dir, Path, dirname, parent)
import Proteome.Data.Env (Env)
import qualified Proteome.Data.Env as Env (currentProjectIndex, mainProject, projects)
import Proteome.Data.Project (Project)
import Proteome.Data.ProjectName (ProjectName(ProjectName))
import Proteome.Data.ProjectRoot (ProjectRoot(ProjectRoot))
import Proteome.Data.ProjectType (ProjectType(ProjectType))
import Proteome.Path (dropSlash)
allProjects ::
MonadDeepState s Env m =>
m [Project]
allProjects = do
main <- getL @Env Env.mainProject
extra <- getL @Env Env.projects
return $ main : extra
currentProject ::
MonadDeepState s Env m =>
m (Maybe Project)
currentProject = do
index <- getL @Env Env.currentProjectIndex
Lens.firstOf (Lens.element index) <$> allProjects
pathData :: Path Abs Dir -> (ProjectRoot, ProjectName, ProjectType)
pathData root =
(
ProjectRoot root,
ProjectName . dropSlash . dirname $ root,
ProjectType . dropSlash . dirname . parent $ root
)
|
tek/proteome
|
packages/proteome/lib/Proteome/Project.hs
|
mit
| 1,075
| 0
| 11
| 166
| 346
| 194
| 152
| -1
| -1
|
{-|
Module : Day21
Description : <http://adventofcode.com/2016/day/21 Day 21: Scrambled Letters and Hash>
-}
{-# LANGUAGE FlexibleInstances, GADTs, ViewPatterns #-}
{-# OPTIONS_HADDOCK ignore-exports #-}
module Day21 (main) where
import Common (readDataFile)
import Control.Monad (liftM2)
import Data.Char (isAlpha, isDigit)
import Data.List (elemIndex, foldl')
import System.IO.Unsafe (unsafePerformIO)
import Text.ParserCombinators.ReadP (char, choice, between, munch1, optional, satisfy, string)
import Text.ParserCombinators.ReadPrec (lift)
import Text.Read (Read(readPrec))
input :: [Instruction Char]
input = map read $ lines $ unsafePerformIO $ readDataFile "day21.txt"
data Instruction a where
SwapPositions :: Int -> Int -> Instruction a
SwapLetters :: a -> a -> Instruction a
RotateLeft :: Int -> Instruction a
RotateRight :: Int -> Instruction a
RotateLetter :: a -> Instruction a
ReversePositions :: Int -> Int -> Instruction a
MovePosition :: Int -> Int -> Instruction a
instance Read (Instruction Char) where
readPrec = lift $ choice
[ liftM2 SwapPositions (string "swap position " >> read <$> munch1 isDigit)
(string " with position " >> read <$> munch1 isDigit)
, liftM2 SwapLetters (string "swap letter " >> satisfy isAlpha)
(string " with letter " >> satisfy isAlpha)
, RotateLeft <$> between (string "rotate left ") (string " step" >> optional (char 's'))
(read <$> munch1 isDigit)
, RotateRight <$> between (string "rotate right ") (string " step" >> optional (char 's'))
(read <$> munch1 isDigit)
, string "rotate based on position of letter " >> RotateLetter <$> satisfy isAlpha
, liftM2 ReversePositions (string "reverse positions " >> read <$> munch1 isDigit)
(string " through " >> read <$> munch1 isDigit)
, liftM2 MovePosition (string "move position " >> read <$> munch1 isDigit)
(string " to position " >> read <$> munch1 isDigit)
]
scramble, unscramble :: (Eq c) => Instruction c -> [c] -> [c]
scramble (SwapPositions x y)
(splitAt (min x y) -> (begin, a : (splitAt (abs (x - y) - 1) -> (mid, b : end)))) =
begin ++ b : mid ++ a : end
scramble (SwapLetters a b) s = [if c == a then b else if c == b then a else c | c <- s]
scramble (RotateLeft n) s@(length -> l) = uncurry (flip (++)) $ splitAt (mod n l) s
scramble (RotateRight n) s = scramble (RotateLeft $ negate n) s
scramble (RotateLetter c) s@ ~(elemIndex c -> Just n) =
scramble (RotateRight $ n + if n < 4 then 1 else 2) s
scramble (ReversePositions x y)
(splitAt (min x y) -> (begin, splitAt (abs (x - y) + 1) -> (mid, end))) =
begin ++ reverse mid ++ end
scramble (MovePosition from to) (splitAt from -> (begin, c : end)) =
uncurry ((. (c :)) . (++)) $ splitAt to $ begin ++ end
unscramble (RotateLeft n) s = scramble (RotateRight n) s
unscramble (RotateRight n) s = scramble (RotateLeft n) s
unscramble (RotateLetter c) s@ ~(elemIndex c -> Just n) = head
[ scramble (RotateLeft $ n - m) s
| m <- [0..], (2 * m + if m < 4 then 1 else 2) `mod` length s == n ]
unscramble ins@(MovePosition x y) s = scramble (MovePosition y x) s
unscramble ins s = scramble ins s
main :: IO ()
main = do
putStrLn $ foldl' (flip scramble) "abcdefgh" input
putStrLn $ foldr unscramble "fbgdceah" input
|
ephemient/aoc2016
|
src/Day21.hs
|
mit
| 3,381
| 0
| 17
| 757
| 1,314
| 683
| 631
| 61
| 4
|
module GHCJS.DOM.SVGFETileElement (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/SVGFETileElement.hs
|
mit
| 46
| 0
| 3
| 7
| 10
| 7
| 3
| 1
| 0
|
module Util.String where
import Data.Char
import Data.List ( intersperse )
data Color = Black | Red | Green | Yellow | Blue | Magenta | Cyan | White deriving (Enum, Bounded)
escapeString n = "\ESC[" ++ (show n) ++ "m"
reset = escapeString 0
blackNum = 30
colorStringThenSwitchToColor :: Color -> Color -> String -> String
colorStringThenSwitchToColor highlight standard str = (escapeString $ blackNum + fromEnum highlight) ++ str ++ (escapeString $ blackNum + fromEnum standard)
-- | Outputs the string argument in the color provided by the color argument. /Note that this assumes that the original text color was white/. If this is not the case use 'colorStringThenSwitchToColor'
color :: Color -> String -> String
color c str = (escapeString $ blackNum + fromEnum c) ++ str ++ reset
doubleQuotes :: String -> String
doubleQuotes str = "\"" ++ str ++ "\""
singleQuotes :: String -> String
singleQuotes str = "'" ++ str ++ "'"
curlyBraces :: String -> String
curlyBraces str = "{" ++ str ++ "}"
parentheses :: String -> String
parentheses str = "(" ++ str ++ ")"
angleBrackets :: String -> String
angleBrackets str = "<" ++ str ++ ">"
stringOrNone :: String -> String
stringOrNone str | all isSpace str = "None"
| otherwise = str
joinWith :: String -> [String] -> String
joinWith sep ls = concat $ intersperse sep ls
|
sgord512/Utilities
|
Util/String.hs
|
mit
| 1,405
| 0
| 9
| 316
| 403
| 212
| 191
| 26
| 1
|
module Main where
import DataStructures
import Split
import Move
main :: IO ()
main = print "jajajaja"
|
axelGschaider/ttofu
|
bin/Main.hs
|
mit
| 108
| 0
| 6
| 22
| 31
| 18
| 13
| 6
| 1
|
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.XPathEvaluator
(newXPathEvaluator, createExpression, createExpression_,
createNSResolver, createNSResolver_, evaluate, evaluate_,
XPathEvaluator(..), gTypeXPathEvaluator)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathEvaluator Mozilla XPathEvaluator documentation>
newXPathEvaluator :: (MonadDOM m) => m XPathEvaluator
newXPathEvaluator
= liftDOM (XPathEvaluator <$> new (jsg "XPathEvaluator") ())
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathEvaluator.createExpression Mozilla XPathEvaluator.createExpression documentation>
createExpression ::
(MonadDOM m, ToJSString expression) =>
XPathEvaluator ->
Maybe expression -> Maybe XPathNSResolver -> m XPathExpression
createExpression self expression resolver
= liftDOM
((self ^. jsf "createExpression"
[toJSVal expression, toJSVal resolver])
>>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathEvaluator.createExpression Mozilla XPathEvaluator.createExpression documentation>
createExpression_ ::
(MonadDOM m, ToJSString expression) =>
XPathEvaluator -> Maybe expression -> Maybe XPathNSResolver -> m ()
createExpression_ self expression resolver
= liftDOM
(void
(self ^. jsf "createExpression"
[toJSVal expression, toJSVal resolver]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathEvaluator.createNSResolver Mozilla XPathEvaluator.createNSResolver documentation>
createNSResolver ::
(MonadDOM m, IsNode nodeResolver) =>
XPathEvaluator -> Maybe nodeResolver -> m XPathNSResolver
createNSResolver self nodeResolver
= liftDOM
((self ^. jsf "createNSResolver" [toJSVal nodeResolver]) >>=
fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathEvaluator.createNSResolver Mozilla XPathEvaluator.createNSResolver documentation>
createNSResolver_ ::
(MonadDOM m, IsNode nodeResolver) =>
XPathEvaluator -> Maybe nodeResolver -> m ()
createNSResolver_ self nodeResolver
= liftDOM
(void (self ^. jsf "createNSResolver" [toJSVal nodeResolver]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathEvaluator.evaluate Mozilla XPathEvaluator.evaluate documentation>
evaluate ::
(MonadDOM m, ToJSString expression, IsNode contextNode) =>
XPathEvaluator ->
Maybe expression ->
Maybe contextNode ->
Maybe XPathNSResolver ->
Maybe Word -> Maybe XPathResult -> m XPathResult
evaluate self expression contextNode resolver type' inResult
= liftDOM
((self ^. jsf "evaluate"
[toJSVal expression, toJSVal contextNode, toJSVal resolver,
toJSVal type', toJSVal inResult])
>>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathEvaluator.evaluate Mozilla XPathEvaluator.evaluate documentation>
evaluate_ ::
(MonadDOM m, ToJSString expression, IsNode contextNode) =>
XPathEvaluator ->
Maybe expression ->
Maybe contextNode ->
Maybe XPathNSResolver -> Maybe Word -> Maybe XPathResult -> m ()
evaluate_ self expression contextNode resolver type' inResult
= liftDOM
(void
(self ^. jsf "evaluate"
[toJSVal expression, toJSVal contextNode, toJSVal resolver,
toJSVal type', toJSVal inResult]))
|
ghcjs/jsaddle-dom
|
src/JSDOM/Generated/XPathEvaluator.hs
|
mit
| 4,518
| 0
| 13
| 919
| 962
| 532
| 430
| 78
| 1
|
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.Navigator
(requestMediaKeySystemAccess, requestMediaKeySystemAccess_,
getGamepads, getGamepads_, getUserMedia, registerProtocolHandler,
isProtocolHandlerRegistered, isProtocolHandlerRegistered_,
unregisterProtocolHandler, vibratePattern, vibratePattern_,
vibrate, vibrate_, javaEnabled, javaEnabled_, getStorageUpdates,
getGeolocation, getMediaDevices, getWebkitTemporaryStorage,
getWebkitPersistentStorage, getWebdriver, getPlugins, getMimeTypes,
getCookieEnabled, Navigator(..), gTypeNavigator)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.requestMediaKeySystemAccess Mozilla Navigator.requestMediaKeySystemAccess documentation>
requestMediaKeySystemAccess ::
(MonadDOM m, ToJSString keySystem) =>
Navigator ->
keySystem ->
[MediaKeySystemConfiguration] -> m MediaKeySystemAccess
requestMediaKeySystemAccess self keySystem supportedConfiguration
= liftDOM
(((self ^. jsf "requestMediaKeySystemAccess"
[toJSVal keySystem, toJSVal (array supportedConfiguration)])
>>= readPromise)
>>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.requestMediaKeySystemAccess Mozilla Navigator.requestMediaKeySystemAccess documentation>
requestMediaKeySystemAccess_ ::
(MonadDOM m, ToJSString keySystem) =>
Navigator -> keySystem -> [MediaKeySystemConfiguration] -> m ()
requestMediaKeySystemAccess_ self keySystem supportedConfiguration
= liftDOM
(void
(self ^. jsf "requestMediaKeySystemAccess"
[toJSVal keySystem, toJSVal (array supportedConfiguration)]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.getGamepads Mozilla Navigator.getGamepads documentation>
getGamepads :: (MonadDOM m) => Navigator -> m [Gamepad]
getGamepads self
= liftDOM ((self ^. jsf "getGamepads" ()) >>= fromJSArrayUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.getGamepads Mozilla Navigator.getGamepads documentation>
getGamepads_ :: (MonadDOM m) => Navigator -> m ()
getGamepads_ self = liftDOM (void (self ^. jsf "getGamepads" ()))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.getUserMedia Mozilla Navigator.getUserMedia documentation>
getUserMedia ::
(MonadDOM m) =>
Navigator ->
MediaStreamConstraints ->
NavigatorUserMediaSuccessCallback ->
NavigatorUserMediaErrorCallback -> m ()
getUserMedia self constraints successCallback errorCallback
= liftDOM
(void
(self ^. jsf "getUserMedia"
[toJSVal constraints, toJSVal successCallback,
toJSVal errorCallback]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.registerProtocolHandler Mozilla Navigator.registerProtocolHandler documentation>
registerProtocolHandler ::
(MonadDOM m, ToJSString scheme, ToJSString url,
ToJSString title) =>
Navigator -> scheme -> url -> title -> m ()
registerProtocolHandler self scheme url title
= liftDOM
(void
(self ^. jsf "registerProtocolHandler"
[toJSVal scheme, toJSVal url, toJSVal title]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.isProtocolHandlerRegistered Mozilla Navigator.isProtocolHandlerRegistered documentation>
isProtocolHandlerRegistered ::
(MonadDOM m, ToJSString scheme, ToJSString url,
FromJSString result) =>
Navigator -> scheme -> url -> m result
isProtocolHandlerRegistered self scheme url
= liftDOM
((self ^. jsf "isProtocolHandlerRegistered"
[toJSVal scheme, toJSVal url])
>>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.isProtocolHandlerRegistered Mozilla Navigator.isProtocolHandlerRegistered documentation>
isProtocolHandlerRegistered_ ::
(MonadDOM m, ToJSString scheme, ToJSString url) =>
Navigator -> scheme -> url -> m ()
isProtocolHandlerRegistered_ self scheme url
= liftDOM
(void
(self ^. jsf "isProtocolHandlerRegistered"
[toJSVal scheme, toJSVal url]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.unregisterProtocolHandler Mozilla Navigator.unregisterProtocolHandler documentation>
unregisterProtocolHandler ::
(MonadDOM m, ToJSString scheme, ToJSString url) =>
Navigator -> scheme -> url -> m ()
unregisterProtocolHandler self scheme url
= liftDOM
(void
(self ^. jsf "unregisterProtocolHandler"
[toJSVal scheme, toJSVal url]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.vibrate Mozilla Navigator.vibrate documentation>
vibratePattern :: (MonadDOM m) => Navigator -> [Word] -> m Bool
vibratePattern self pattern'
= liftDOM
((self ^. jsf "vibrate" [toJSVal (array pattern')]) >>= valToBool)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.vibrate Mozilla Navigator.vibrate documentation>
vibratePattern_ :: (MonadDOM m) => Navigator -> [Word] -> m ()
vibratePattern_ self pattern'
= liftDOM (void (self ^. jsf "vibrate" [toJSVal (array pattern')]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.vibrate Mozilla Navigator.vibrate documentation>
vibrate :: (MonadDOM m) => Navigator -> Word -> m Bool
vibrate self time
= liftDOM ((self ^. jsf "vibrate" [toJSVal time]) >>= valToBool)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.vibrate Mozilla Navigator.vibrate documentation>
vibrate_ :: (MonadDOM m) => Navigator -> Word -> m ()
vibrate_ self time
= liftDOM (void (self ^. jsf "vibrate" [toJSVal time]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.javaEnabled Mozilla Navigator.javaEnabled documentation>
javaEnabled :: (MonadDOM m) => Navigator -> m Bool
javaEnabled self
= liftDOM ((self ^. jsf "javaEnabled" ()) >>= valToBool)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.javaEnabled Mozilla Navigator.javaEnabled documentation>
javaEnabled_ :: (MonadDOM m) => Navigator -> m ()
javaEnabled_ self = liftDOM (void (self ^. jsf "javaEnabled" ()))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.getStorageUpdates Mozilla Navigator.getStorageUpdates documentation>
getStorageUpdates :: (MonadDOM m) => Navigator -> m ()
getStorageUpdates self
= liftDOM (void (self ^. jsf "getStorageUpdates" ()))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.geolocation Mozilla Navigator.geolocation documentation>
getGeolocation :: (MonadDOM m) => Navigator -> m Geolocation
getGeolocation self
= liftDOM ((self ^. js "geolocation") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.mediaDevices Mozilla Navigator.mediaDevices documentation>
getMediaDevices :: (MonadDOM m) => Navigator -> m MediaDevices
getMediaDevices self
= liftDOM ((self ^. js "mediaDevices") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.webkitTemporaryStorage Mozilla Navigator.webkitTemporaryStorage documentation>
getWebkitTemporaryStorage ::
(MonadDOM m) => Navigator -> m StorageQuota
getWebkitTemporaryStorage self
= liftDOM
((self ^. js "webkitTemporaryStorage") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.webkitPersistentStorage Mozilla Navigator.webkitPersistentStorage documentation>
getWebkitPersistentStorage ::
(MonadDOM m) => Navigator -> m StorageQuota
getWebkitPersistentStorage self
= liftDOM
((self ^. js "webkitPersistentStorage") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.webdriver Mozilla Navigator.webdriver documentation>
getWebdriver :: (MonadDOM m) => Navigator -> m Bool
getWebdriver self
= liftDOM ((self ^. js "webdriver") >>= valToBool)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.plugins Mozilla Navigator.plugins documentation>
getPlugins :: (MonadDOM m) => Navigator -> m PluginArray
getPlugins self
= liftDOM ((self ^. js "plugins") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.mimeTypes Mozilla Navigator.mimeTypes documentation>
getMimeTypes :: (MonadDOM m) => Navigator -> m MimeTypeArray
getMimeTypes self
= liftDOM ((self ^. js "mimeTypes") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Navigator.cookieEnabled Mozilla Navigator.cookieEnabled documentation>
getCookieEnabled :: (MonadDOM m) => Navigator -> m Bool
getCookieEnabled self
= liftDOM ((self ^. js "cookieEnabled") >>= valToBool)
|
ghcjs/jsaddle-dom
|
src/JSDOM/Generated/Navigator.hs
|
mit
| 10,055
| 0
| 16
| 1,837
| 1,974
| 1,071
| 903
| 144
| 1
|
{-# htermination zipWithM_ :: (a -> b -> IO c) -> [a] -> [b] -> IO () #-}
import Monad
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Monad_zipWithM__4.hs
|
mit
| 87
| 0
| 3
| 20
| 5
| 3
| 2
| 1
| 0
|
{-# LANGUAGE PackageImports #-}
{-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-}
-- | Reexports "Data.String.Compat"
-- from a globally unique namespace.
module Data.String.Compat.Repl.Batteries (
module Data.String.Compat
) where
import "this" Data.String.Compat
|
haskell-compat/base-compat
|
base-compat-batteries/src/Data/String/Compat/Repl/Batteries.hs
|
mit
| 286
| 0
| 5
| 31
| 29
| 22
| 7
| 5
| 0
|
module Bonawitz_3_21a
where
import Blaze
sr :: String -> State
sr s = collectStates dummyState $ (scs s) : sgps
sgps :: [State]
sgps = mkDoubleParams ["mu","sigma"] [1.0, 1.0]
scs :: String -> State
scs s = collectStates dummyCState comps `tag` "scs"
where comps = map mkComp $ lines s
mkComp :: String -> State
mkComp s = collectStates dummyState (csx : params) `tag` t
where (t:ns) = words s
csx = collectStates dummyCState $
zipWith (flip tag) (((t ++) . show) `fmap` [1..]) $
map (mkDoubleData . read) ns
params = mkDoubleParams ["mu","sigma"] [0.0,1.0]
dr :: Density
dr = mkACDensity (productDensity [dparam,dcomp]) ["scs"] [["mu"],["sigma"]]
where dparam = mkDensity [] [["mu"]] [["dso","mu"],["dso","sigma"]] normal
dcomp = mkACDensity ddatum [""] [["mu"],["sigma"]]
ddatum = mkDensity [] [[]] [["dso","mu"],["dso","sigma"]] normal
buildMachine :: String -> (Entropy -> Machine)
buildMachine s e = Machine sr' dr kr e
where sr' = sr s
kr = mkMHKernel $
mkCMKernel [0.2,0.2,0.48,0.11,0.01] $
[kgmu,kgsigma,kcomp,kreassign,kreassign']
kgmu = mkGPKernel 1.5 ["mu"]
kgsigma = mkGPKernel 1.5 ["sigma"]
kcomp = mkVMKernel ["scs"] $
mkASTKernel "scs" $ mkASBKernel $
mkGPKernel 0.3 ["mu"]
kreassign = mkEGKernel $ mkRDSLKernel ["scs"]
kreassign' = mkEGKernel $ mkCCKernel [kreassign,kreassign]
main :: IO ()
main = do
s <- readFile "cluster.dat"
let paramLocs = [ ([],"mu"), ([],"sigma") ]
run (buildMachine s) 1000 [ trace paramLocs, burnin 100 $ dump paramLocs ]
|
othercriteria/blaze
|
Bonawitz_3_21a.hs
|
mit
| 1,758
| 0
| 14
| 514
| 680
| 374
| 306
| 39
| 1
|
-- | uprolog
module UProlog
( module UProlog.Val
, module UProlog.State
, module UProlog.Util
) where
import Prelude hiding (any, all, and, or)
import UProlog.Val
import UProlog.State
import UProlog.Util
|
lukegrehan/uprolog
|
src/UProlog.hs
|
mit
| 206
| 0
| 5
| 31
| 58
| 38
| 20
| 8
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module MacFinder.Types (
Mac(..),
newMac,
deconstructMac
) where
import qualified Data.Text.Lazy as T
import qualified Data.ByteString as B
import MacFinder.Util (convertByteStringToText, convertTextToByteString)
data Mac = Mac { name :: T.Text
, mac :: T.Text
} deriving (Show, Eq)
emptyMac :: Mac
emptyMac = Mac "" ""
newMac :: [(B.ByteString, B.ByteString)] -> Maybe Mac
newMac [] = Nothing
newMac xs = Just $ foldr fillMac emptyMac xs
where fillMac ("name", val) struct = struct { name = convertByteStringToText val }
fillMac ("mac", val) struct = struct { mac = convertByteStringToText val }
fillMac _ struct = struct
deconstructMac :: Mac -> (B.ByteString, [(B.ByteString, B.ByteString)])
deconstructMac m = (B.concat ["macs:", convertTextToByteString . mac $ m], [("mac", convertTextToByteString . mac $ m), ("name", convertTextToByteString . name $ m)])
|
tlunter/MacFinder
|
src/MacFinder/Types.hs
|
mit
| 983
| 0
| 9
| 215
| 320
| 185
| 135
| 21
| 3
|
{-# LANGUAGE OverloadedStrings, QuasiQuotes, ExistentialQuantification, ScopedTypeVariables #-}
module Expressions where
import Text.Parsec hiding (many, (<|>))
import Data.Maybe (fromJust, fromMaybe)
import Data.Monoid
import Data.List (intersperse)
import Data.List.Split
import Data.Scientific
import Data.Aeson
import Data.Aeson.Types
import Data.Text (Text)
import qualified Data.Text as T
import Control.Applicative
import qualified Data.HashMap.Lazy as HM
import qualified Data.Vector as V
import qualified Data.ByteString.Lazy.Char8 as B
import Test.HUnit
import Data.String.QQ
import Data.Functor.Identity (Identity )
import qualified Data.Map.Strict as M
-- see doc for AngularJS expressions https://docs.angularjs.org/guide/expression
data TmplExprTopLevel = TmplExprTopLevel TmplExpr
deriving (Show, Eq)
data TmplExpr = TmplKeyPath [JSKey]
| Or TmplExpr TmplExpr
| And TmplExpr TmplExpr
| Neg TmplExpr
| Compare String TmplExpr TmplExpr
-- map is used by templateClass: https://docs.angularjs.org/api/ng/directive/templateClass
-- A map of class names to boolean values. In the case of a map,
-- the names of the properties whose values are truthy will be added
-- as css classes to the element.
| TmplMap (M.Map String TmplExpr)
| TmplLiteral Value
deriving (Show, Eq)
data JSKey = ObjectKey Text
| ArrayIndex Int
| Method Text [Text] -- method name and arguments
deriving (Show, Eq)
data TextChunk = PassThrough String | Interpolation String
deriving (Show, Eq)
data ComparableValue = ComparableNumberValue Scientific
| ComparableStritemplateValue Text
| ComparableBoolValue Bool
| ComparableNullValue
deriving (Ord, Eq, Show)
type TmplExprParser = ParsecT String () Identity
symbol s = spaces *> string s <* spaces
templateExprTopLevel = TmplExprTopLevel <$> templateExpr
templateExpr = do
templateMap <|> (do
maybeNeg <- optionMaybe (symbol "!")
expr1' <- templateExprTerm
let expr1 = case maybeNeg of
Just "!" -> Neg expr1'
_ -> expr1'
try (do symbol "&&"; expr2 <- templateExpr; return $ And expr1 expr2)
<|> try (do symbol "||"; expr2 <- templateExpr; return $ Or expr1 expr2)
<|> try (do op <- comparisonOp; expr2 <- templateExpr; return $ Compare op expr1 expr2)
<|> return expr1)
templateMap = do
char '{' >> spaces
pairs :: [(String, TmplExpr)] <- sepBy1 ((,) <$> templateVarName <*> (char ':' >> spaces >> templateExpr <* spaces)) (char ',' >> spaces)
spaces >> char '}' >> spaces
return $ TmplMap $ M.fromList pairs
comparisonOp = choice $ map (try . symbol) [">=", "<=", "!=", ">", "<", "=="]
templateExprTerm = (char '(' *> templateExpr <* char ')') <|> templateLiteral <|> templateKeyPath
templateKeyPath :: TmplExprParser TmplExpr
templateKeyPath = do
ks <- sepBy1 templateKeyPathComponent (char '.' <|> char '[')
return $ TmplKeyPath ks
templateKeyPathComponent :: TmplExprParser JSKey
templateKeyPathComponent =
(ArrayIndex . read <$> many1 digit <* char ']') <|>
(try templateKeyPathMethodWithArgs) <|>
(toJSKey . T.pack <$> templateVarName)
templateVarName = many1 (alphaNum <|> char '$' <|> char '_')
templateLiteral = TmplLiteral <$> (templateNumber <|> templateString <|> templateBool)
-- just integers for now
templateNumber = Number . read <$> many1 digit
-- dumb simple implementation that does not deal with escaping
templateString = String . T.pack <$> ((char '"' *> many (noneOf "\"") <* char '"') <|> (char '\'' *> many (noneOf "'") <* char '\''))
templateBool = Bool <$> ((try (string "true") *> pure True) <|> (try (string "false") *> pure False))
------------------------------------------------------------------------
-- | function to evaluate a template expression and a object value context
-- e.g. Value -> "item.name" -> "John"
templateEvalToString :: Value -> String -> String
templateEvalToString context exprString = valToString . templateExprEval (runParse templateExpr exprString) $ context
templateEvalToBool :: Value -> Text -> Bool
templateEvalToBool context exprString =
let expr = runParse templateExpr (T.unpack exprString)
val = templateExprEval expr context
in valueToBool val
valueToBool :: Value -> Bool
valueToBool (String "") = False
valueToBool (Bool False) = False
valueToBool Null = False
valueToBool (Bool True) = True -- not strictly necessary pattern
valueToBool _ = True
evalText :: Value -> TextChunk -> String
evalText v (PassThrough s) = s
evalText v (Interpolation s) = templateEvalToString v s
templateEval :: [Text] -> Value -> Value
templateEval keyPath context = templateExprEval (TmplKeyPath $ map toJSKey keyPath) context
templateExprEval :: TmplExpr -> Value -> Value
templateExprEval (TmplLiteral x) _ = x
templateExprEval (TmplKeyPath ks) v = templateEvaluate ks v
templateExprEval (Or x y) v =
let vx = templateExprEval x v
in if (valueToBool vx) then vx else (templateExprEval y v)
templateExprEval (And x y) v =
let vx = templateExprEval x v
in if (valueToBool vx) then (templateExprEval y v) else (Bool False)
templateExprEval (Neg x) v =
let vx = templateExprEval x v
in case vx of
Null -> Bool True
Bool False -> Bool True
String "" -> Bool True -- ? is this right?
_ -> Bool False
templateExprEval (TmplMap ngmap) v =
let xs :: [(String, TmplExpr)] = M.toList ngmap
trueKeys = [k | (k,expr) <- xs, (valueToBool $ templateExprEval expr v)]
-- return all true keys concatenated interspersed with spaces
in case trueKeys of
[] -> Null
xs -> String $ mconcat $ intersperse " " $ map T.pack xs
templateExprEval (Compare op x y) v =
let vx = comparableValue $ templateExprEval x v
vy = comparableValue $ templateExprEval y v
in case op of
">" -> Bool $ vx > vy
"<" -> Bool $ vx < vy
">=" -> Bool $ vx >= vy
"<=" -> Bool $ vx <= vy
"==" -> Bool $ vx == vy
"!=" -> Bool $ vx /= vy
comparableValue :: Value -> ComparableValue
comparableValue (Number x) = ComparableNumberValue x
comparableValue (String x) = ComparableStritemplateValue x
comparableValue (Bool x) = ComparableBoolValue x
comparableValue Null = ComparableNullValue
comparableValue x = error $ "can't make comparable value for " ++ show x
-- evaluates the a JS key path against a Value context to a leaf Value
templateEvaluate :: [JSKey] -> Value -> Value
templateEvaluate [] x@(String _) = x
templateEvaluate [] x@Null = x
templateEvaluate [] x@(Number _) = x
templateEvaluate [] x@(Bool _) = x
templateEvaluate [] x@(Object _) = x
templateEvaluate [] x@(Array _) = x
templateEvaluate ((ObjectKey key):(Method "length" []):[]) (Object s) =
case (HM.lookup key s) of
(Just (Array vs)) -> toJSON $ V.length vs
_ -> Null
templateEvaluate ((ObjectKey key):(Method "join" [separator]):[]) (Object s) =
case (HM.lookup key s) of
(Just (Array vs)) -> String $ mconcat $ intersperse separator $ map (T.pack . valToString) $ V.toList vs
_ -> Null
templateEvaluate ((ObjectKey key):xs) (Object s) = templateEvaluate xs (HM.lookupDefault Null key s)
templateEvaluate ((ArrayIndex idx):xs) (Array v) = case V.length v > 0 of
True -> templateEvaluate xs (v V.! idx)
False -> Null
templateEvaluate _ _ = Null
-- CHANGE TO PARSEC
toJSKey :: Text -> JSKey
toJSKey "length" = Method "length" []
toJSKey x = ObjectKey x
templateKeyPathMethodWithArgs :: TmplExprParser JSKey
templateKeyPathMethodWithArgs = do
methodName <- T.pack <$> templateVarName
char '('
-- simplistic argument parser.
-- Messes up in an argument is a string with a comma in it.
args <- pStritemplateMethodArgument `sepBy1` (spaces >> char ',' >> spaces)
char ')'
return $ Method methodName args
pStritemplateMethodArgument :: TmplExprParser Text
pStritemplateMethodArgument = do
spaces
arg <- between (char '\'') (char '\'') (many1 (noneOf "'"))
<|> between (char '"') (char '"') (many1 (noneOf "\""))
return . T.pack $ arg
valToString :: Value -> String
valToString (String x) = T.unpack x
valToString Null = ""
valToString (Bool True) = "true"
valToString (Bool False) = "false"
valToString (Number x) =
case floatingOrInteger x of
Left float -> show float
Right int -> show int
valToString x = debugJSON x
-- parse String to find interpolation expressions
runParse parser inp =
case Text.Parsec.parse parser "" inp of
Left x -> error $ "parser failed: " ++ show x
Right xs -> xs
parseText :: String -> [TextChunk]
parseText = runParse (many templateTextChunk)
parseKeyExpr :: String -> [JSKey]
parseKeyExpr s =
let (TmplKeyPath ks) = runParse templateKeyPath s
in ks
templateTextChunk :: TmplExprParser TextChunk
templateTextChunk = interpolationChunk <|> passThroughChunk
interpolationChunk = do
try (string "{{")
spaces
xs <- manyTill anyChar (lookAhead $ try (string "}}"))
spaces
string "}}"
return $ Interpolation xs
passThroughChunk = PassThrough <$> passThrough
passThrough = do
-- a lead single { char. This is guaranteed not to be part of {{
t <- optionMaybe (string "{")
xs <- many1 (noneOf "{")
x <- (eof *> pure "{{") <|> lookAhead (try (string "{{") <|> string "{")
res <- case x of
"{{" -> return []
"{" -> ('{':) <$> passThrough
return $ (fromMaybe "" t) ++ xs ++ res
-- for debugging
debugJSON = B.unpack . encode
jsonToValue :: B.ByteString -> Value
jsonToValue = fromJust . decode
------------------------------------------------------------------------
-- Tests
t = runTestTT tests
testContext1 = jsonToValue [s|{"item":"apple","another":10}|]
testContext2 = jsonToValue [s|{"item":{"name":"apple"}}|]
testContext3 = jsonToValue [s|{"items":[1,2,3]}|]
testContext4 = jsonToValue [s|{"item":{"active":false,"canceled":true}}|]
testContext5 = jsonToValue [s|{"person":{"species":"hobbit"}}|]
tests = test [
"parseKeyExpr" ~: [ObjectKey "item"] @=? parseKeyExpr "item"
, "templateEvalToString" ~: "apple" @=? templateEvalToString testContext1 "item"
, "templateEvalToString2" ~: "apple" @=? templateEvalToString testContext2 "item.name"
, "parse array keypath" ~: [ObjectKey "items",ArrayIndex 1] @=? parseKeyExpr "items[1]"
, "eval array index" ~: "2" @=? templateEvalToString testContext3 "items[1]"
, "array index" ~: "2" @=? templateEvalToString testContext3 "items[1]"
, "parse ng map" ~: TmplMap (M.fromList [("testKey",TmplKeyPath [ObjectKey "item",ObjectKey "name"])])
@=? runParse templateExpr "{testKey: item.name}"
, "parse ng map 2" ~: TmplMap (M.fromList [("dwarf",Compare "==" (TmplKeyPath [ObjectKey "person",ObjectKey "species"]) (TmplLiteral (String "dwarf"))),("hobbit",Compare "==" (TmplKeyPath [ObjectKey "person",ObjectKey "species"]) (TmplLiteral (String "hobbit")))])
@=? runParse templateExpr "{dwarf: person.species == 'dwarf', hobbit: person.species == 'hobbit'}"
, "parse length method" ~: [ObjectKey "items",Method "length" []] @=? parseKeyExpr "items.length"
, "parse join method with arg"
~: [ObjectKey "items",Method "join" [","]]
@=? parseKeyExpr "items.join(\",\")"
, "parse join method with arg, single quotes"
~: [ObjectKey "items",Method "join" [","]]
@=? parseKeyExpr "items.join(',')"
, "eval length method" ~: "3"
@=? templateEvalToString testContext3 "items.length"
, "eval join method with arg"
~: "1,2,3"
@=? templateEvalToString testContext3 "items.join(\",\")"
, "parse ngexpr 1" ~: TmplKeyPath [ObjectKey "test"]
@=? runParse templateExpr "test"
, "parse ngexpr 2" ~: (Or (TmplKeyPath [ObjectKey "test"]) (TmplKeyPath [ObjectKey "test2"]))
@=? runParse templateExpr "test || test2"
, "parse ngexpr 3" ~: (Or (TmplKeyPath [ObjectKey "test"]) (TmplKeyPath [ObjectKey "test2"]))
@=? runParse templateExpr "(test || test2)"
, "parse ngexpr 4" ~:
And (Or (TmplKeyPath [ObjectKey "test1"]) (TmplKeyPath [ObjectKey "test2"])) (TmplKeyPath [ObjectKey "test3"])
@=? runParse templateExpr "(test1 || test2) && test3"
, "parse literal" ~: TmplLiteral (Number 2) @=? runParse templateExpr "2"
, "parse negation" ~: Neg (TmplKeyPath [ObjectKey "test"]) @=? runParse templateExpr "!test"
, "parse comparison" ~: Compare ">" (TmplKeyPath [ObjectKey "test"]) (TmplKeyPath [ObjectKey "test2"])
@=? runParse templateExpr "test > test2"
, "parse comparison with literal" ~:
Compare "==" (TmplKeyPath [ObjectKey "test"]) (TmplLiteral (Number 1))
@=? runParse templateExpr "test == 1"
, "parse top level ng expr" ~:
TmplExprTopLevel (TmplKeyPath [ObjectKey "item",ObjectKey "price"])
@=? runParse templateExprTopLevel "item.price | number:2"
, "disjunction left" ~: "apple" @=? templateEvalToString testContext1 "item || another"
, "disjunction right" ~: "10" @=? templateEvalToString testContext1 "blah || another"
, "disjunction in parens" ~: "apple" @=? templateEvalToString testContext2 "(item.color || item.name)"
, "length" ~: Number 3 @=? templateEval ["items","length"] testContext3
, "ngmap eval 1" ~: "canceled" @=? templateEvalToString testContext4 "{active: item.active, canceled:item.canceled}"
, "ngmap eval 2" ~: "hobbit" @=? templateEvalToString testContext5 "{dwarf: person.species == 'dwarf', hobbit: person.species == 'hobbit'}"
, "compare length == again" ~: Bool True
@=? templateExprEval (runParse templateExpr "items.length == 3") testContext3
, "compare length != " ~: Bool False
@=? templateExprEval (runParse templateExpr "items.length != 3") testContext3
, "compare length >" ~: Bool True
@=? templateExprEval (runParse templateExpr "items.length > 1") testContext3
, "compare length >=" ~: Bool True
@=? templateExprEval (runParse templateExpr "items.length >= 1") testContext3
, "compare to string" ~: "true"
@=? templateEvalToString testContext1 "item == 'apple'"
, "text chunk 1" ~: Interpolation "test" @=? runParse interpolationChunk "{{test}}"
, "text chunk 2" ~: PassThrough "test" @=? runParse passThroughChunk "test"
, "text chunk 3" ~: PassThrough " test" @=? runParse templateTextChunk " test"
, "text chunk 4" ~: " test" @=? runParse passThrough " test"
, "text chunks" ~: [PassThrough " test ",Interpolation "test2",PassThrough " test"] @=? parseText " test {{test2}} test"
, "text empty" ~: [] @=? parseText ""
]
|
danchoi/transparent
|
Expressions.hs
|
mit
| 15,935
| 0
| 19
| 4,183
| 4,329
| 2,199
| 2,130
| 279
| 12
|
module Util where
import Types
import qualified Data.Map as M
-- NB. Overwrites prefer the first state!
-- O(n+m)
mergeBindings :: FievelState -> FievelState -> FievelState
mergeBindings (FievelState ts es) (FievelState ts' es') =
FievelState (ts `M.union` ts') (es `M.union` es')
|
5outh/fievel
|
Util.hs
|
gpl-2.0
| 285
| 0
| 7
| 45
| 83
| 49
| 34
| 6
| 1
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Types
-- License : GPL-2
-- Maintainer : yi-devel@googlegroups.com
-- Stability : experimental
-- Portability : portable
--
-- This module is the host of the most prevalent types throughout Yi.
-- It is unfortunately a necessary evil to avoid use of bootfiles.
--
-- You're encouraged to import from more idiomatic modules which will
-- re-export these where appropriate.
module Yi.Types where
import Control.Applicative
import Control.Concurrent
import Control.Monad.Base
import Control.Monad.RWS.Strict (RWS, MonadWriter)
import Control.Monad.Reader
import Control.Monad.State
import qualified Data.DynamicState as ConfigState
import qualified Data.DynamicState.Serializable as DynamicState
import Data.Binary (Binary)
import qualified Data.Binary as B
import Data.Default
import qualified Data.DelayList as DelayList
import Data.Foldable
import Data.Function (on)
import Data.List.NonEmpty
import Data.List.PointedList
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.Text.Encoding as E
import Data.Time
import Data.Traversable
import Data.Typeable
import Data.Word
#ifdef FRONTEND_VTY
import qualified Graphics.Vty as Vty
#endif
import Yi.Buffer.Basic (BufferRef, WindowRef)
import Yi.Buffer.Implementation
import Yi.Buffer.Undo
import Yi.Config.Misc
import Yi.Event
import qualified Yi.Interact as I
import Yi.KillRing
import Yi.Layout
import Yi.Monad
import Yi.Process (SubprocessInfo, SubprocessId)
import qualified Yi.Rope as R
import Yi.Style
import Yi.Style.Library
import Yi.Syntax
import Yi.Tab
import Yi.UI.Common
import Yi.Window
-- Yi.Keymap
-- TODO: refactor this!
data Action = forall a. Show a => YiA (YiM a)
| forall a. Show a => EditorA (EditorM a)
| forall a. Show a => BufferA (BufferM a)
deriving Typeable
emptyAction :: Action
emptyAction = BufferA (return ())
class (Default a, Binary a, Typeable a) => YiVariable a
class (Default a, Typeable a) => YiConfigVariable a
instance Eq Action where
_ == _ = False
instance Show Action where
show (YiA _) = "@Y"
show (EditorA _) = "@E"
show (BufferA _) = "@B"
type Interact ev a = I.I ev Action a
type KeymapM a = Interact Event a
type Keymap = KeymapM ()
type KeymapEndo = Keymap -> Keymap
type KeymapProcess = I.P Event Action
data IsRefreshNeeded = MustRefresh | NoNeedToRefresh
deriving (Show, Eq)
data Yi = Yi { yiUi :: UI Editor
, yiInput :: [Event] -> IO () -- ^ input stream
, yiOutput :: IsRefreshNeeded -> [Action] -> IO () -- ^ output stream
, yiConfig :: Config
-- TODO: this leads to anti-patterns and seems like one itself
-- too coarse for actual concurrency, otherwise pointless
-- And MVars can be empty so this causes soundness problems
-- Also makes code a bit opaque
, yiVar :: MVar YiVar -- ^ The only mutable state in the program
}
deriving Typeable
data YiVar = YiVar { yiEditor :: !Editor
, yiSubprocessIdSupply :: !SubprocessId
, yiSubprocesses :: !(M.Map SubprocessId SubprocessInfo)
}
-- | The type of user-bindable functions
-- TODO: doc how these are actually user-bindable
-- are they?
newtype YiM a = YiM {runYiM :: ReaderT Yi IO a}
deriving (Monad, Applicative, MonadReader Yi, MonadBase IO, Typeable, Functor)
instance MonadState Editor YiM where
get = yiEditor <$> (liftBase . readMVar =<< yiVar <$> ask)
put v = liftBase . flip modifyMVar_ (\x -> return $ x {yiEditor = v}) =<< yiVar <$> ask
instance MonadEditor YiM where
askCfg = yiConfig <$> ask
withEditor f = do
r <- asks yiVar
cfg <- asks yiConfig
liftBase $ unsafeWithEditor cfg r f
unsafeWithEditor :: Config -> MVar YiVar -> EditorM a -> IO a
unsafeWithEditor cfg r f = modifyMVar r $ \var -> do
let e = yiEditor var
let (e',a) = runEditor cfg f e
-- Make sure that the result of runEditor is evaluated before
-- replacing the editor state. Otherwise, we might replace e
-- with an exception-producing thunk, which makes it impossible
-- to look at or update the editor state.
-- Maybe this could also be fixed by -fno-state-hack flag?
-- TODO: can we simplify this?
e' `seq` a `seq` return (var {yiEditor = e'}, a)
data KeymapSet = KeymapSet
{ topKeymap :: Keymap -- ^ Content of the top-level loop.
, insertKeymap :: Keymap -- ^ For insertion-only modes
}
extractTopKeymap :: KeymapSet -> Keymap
extractTopKeymap kms = forever (topKeymap kms)
-- Note the use of "forever": this has quite subtle implications, as it means that
-- failures in one iteration can yield to jump to the next iteration seamlessly.
-- eg. in emacs keybinding, failures in incremental search, like <left>, will "exit"
-- incremental search and immediately move to the left.
-- Yi.Buffer.Misc
-- | The BufferM monad writes the updates performed.
newtype BufferM a = BufferM { fromBufferM :: RWS Window [Update] FBuffer a }
deriving (Monad, Functor, MonadWriter [Update], MonadState FBuffer, MonadReader Window, Typeable)
-- | Currently duplicates some of Vim's indent settings. Allowing a
-- buffer to specify settings that are more dynamic, perhaps via
-- closures, could be useful.
data IndentSettings = IndentSettings
{ expandTabs :: Bool -- ^ Insert spaces instead of tabs as possible
, tabSize :: Int -- ^ Size of a Tab
, shiftWidth :: Int -- ^ Indent by so many columns
} deriving (Eq, Show, Typeable)
instance Applicative BufferM where
pure = return
(<*>) = ap
data FBuffer = forall syntax.
FBuffer { bmode :: !(Mode syntax)
, rawbuf :: !(BufferImpl syntax)
, attributes :: !Yi.Types.Attributes
}
deriving Typeable
instance Eq FBuffer where
(==) = (==) `on` bkey__ . attributes
type WinMarks = MarkSet Mark
data MarkSet a = MarkSet { fromMark, insMark, selMark :: !a }
deriving (Traversable, Foldable, Functor)
instance Binary a => Binary (MarkSet a) where
put (MarkSet f i s) = B.put f >> B.put i >> B.put s
get = liftM3 MarkSet B.get B.get B.get
data Attributes = Attributes
{ ident :: !BufferId
, bkey__ :: !BufferRef -- ^ immutable unique key
, undos :: !URList -- ^ undo/redo list
, bufferDynamic :: !DynamicState.DynamicState -- ^ dynamic components
, preferCol :: !(Maybe Int) -- ^ prefered column to arrive at when we do a lineDown / lineUp
, pendingUpdates :: ![UIUpdate] -- ^ updates that haven't been synched in the UI yet
, selectionStyle :: !SelectionStyle
, keymapProcess :: !KeymapProcess
, winMarks :: !(M.Map WindowRef WinMarks)
, lastActiveWindow :: !Window
, lastSyncTime :: !UTCTime -- ^ time of the last synchronization with disk
, readOnly :: !Bool -- ^ read-only flag
, inserting :: !Bool -- ^ the keymap is ready for insertion into this buffer
, directoryContent :: !Bool -- ^ does buffer contain directory contents
, pointFollowsWindow :: !(WindowRef -> Bool)
, updateTransactionInFlight :: !Bool
, updateTransactionAccum :: ![Update]
, fontsizeVariation :: !Int
, encodingConverterName :: Maybe R.ConverterName
-- ^ How many points (frontend-specific) to change
-- the font by in this buffer
} deriving Typeable
instance Binary Yi.Types.Attributes where
put (Yi.Types.Attributes n b u bd pc pu selectionStyle_
_proc wm law lst ro ins _dc _pfw isTransacPresent transacAccum fv cn) = do
let putTime (UTCTime x y) = B.put (fromEnum x) >> B.put (fromEnum y)
B.put n >> B.put b >> B.put u >> B.put bd
B.put pc >> B.put pu >> B.put selectionStyle_ >> B.put wm
B.put law >> putTime lst >> B.put ro >> B.put ins >> B.put _dc
B.put isTransacPresent >> B.put transacAccum >> B.put fv >> B.put cn
get = Yi.Types.Attributes <$> B.get <*> B.get <*> B.get <*>
B.get <*> B.get <*> B.get <*> B.get <*> pure I.End <*> B.get <*> B.get
<*> getTime <*> B.get <*> B.get <*> B.get
<*> pure (const False) <*> B.get <*> B.get <*> B.get <*> B.get
where
getTime = UTCTime <$> (toEnum <$> B.get) <*> (toEnum <$> B.get)
data BufferId = MemBuffer T.Text
| FileBuffer FilePath
deriving (Show, Eq)
instance Binary BufferId where
get = B.get >>= \case
(0 :: Word8) -> MemBuffer . E.decodeUtf8 <$> B.get
1 -> FileBuffer <$> B.get
x -> fail $ "Binary failed on BufferId, tag: " ++ show x
put (MemBuffer t) = B.put (0 :: Word8) >> B.put (E.encodeUtf8 t)
put (FileBuffer t) = B.put (1 :: Word8) >> B.put t
data SelectionStyle = SelectionStyle
{ highlightSelection :: !Bool
, rectangleSelection :: !Bool
} deriving Typeable
instance Binary SelectionStyle where
put (SelectionStyle h r) = B.put h >> B.put r
get = SelectionStyle <$> B.get <*> B.get
data AnyMode = forall syntax. AnyMode (Mode syntax)
deriving Typeable
-- | A Mode customizes the Yi interface for editing a particular data
-- format. It specifies when the mode should be used and controls
-- file-specific syntax highlighting and command input, among other
-- things.
data Mode syntax = Mode
{ modeName :: T.Text
-- ^ so this can be serialized, debugged.
, modeApplies :: FilePath -> R.YiString -> Bool
-- ^ What type of files does this mode apply to?
, modeHL :: ExtHL syntax
-- ^ Syntax highlighter
, modePrettify :: syntax -> BufferM ()
-- ^ Prettify current \"paragraph\"
, modeKeymap :: KeymapSet -> KeymapSet
-- ^ Buffer-local keymap modification
, modeIndent :: syntax -> IndentBehaviour -> BufferM ()
-- ^ emacs-style auto-indent line
, modeAdjustBlock :: syntax -> Int -> BufferM ()
-- ^ adjust the indentation after modification
, modeFollow :: syntax -> Action
-- ^ Follow a \"link\" in the file. (eg. go to location of error message)
, modeIndentSettings :: IndentSettings
, modeToggleCommentSelection :: Maybe (BufferM ())
, modeGetStrokes :: syntax -> Point -> Point -> Point -> [Stroke]
-- ^ Strokes that should be applied when displaying a syntax element
-- should this be an Action instead?
, modeOnLoad :: BufferM ()
-- ^ An action that is to be executed when this mode is set
, modeModeLine :: [T.Text] -> BufferM T.Text
-- ^ buffer-local modeline formatting method
, modeGotoDeclaration :: BufferM ()
-- ^ go to the point where the variable is declared
}
-- | Used to specify the behaviour of the automatic indent command.
data IndentBehaviour =
IncreaseCycle -- ^ Increase the indentation to the next higher indentation
-- hint. If we are currently at the highest level of
-- indentation then cycle back to the lowest.
| DecreaseCycle -- ^ Decrease the indentation to the next smaller indentation
-- hint. If we are currently at the smallest level then
-- cycle back to the largest
| IncreaseOnly -- ^ Increase the indentation to the next higher hint
-- if no such hint exists do nothing.
| DecreaseOnly -- ^ Decrease the indentation to the next smaller indentation
-- hint, if no such hint exists do nothing.
deriving (Eq, Show)
-- Yi.Editor
type Status = ([T.Text], StyleName)
type Statuses = DelayList.DelayList Status
-- | The Editor state
data Editor = Editor
{ bufferStack :: !(NonEmpty BufferRef)
-- ^ Stack of all the buffers.
-- Invariant: first buffer is the current one.
, buffers :: !(M.Map BufferRef FBuffer)
, refSupply :: !Int -- ^ Supply for buffer, window and tab ids.
, tabs_ :: !(PointedList Tab)
-- ^ current tab contains the visible windows pointed list.
, dynamic :: !DynamicState.DynamicState -- ^ dynamic components
, statusLines :: !Statuses
, maxStatusHeight :: !Int
, killring :: !Killring
, currentRegex :: !(Maybe SearchExp)
-- ^ currently highlighted regex (also most recent regex for use
-- in vim bindings)
, searchDirection :: !Direction
, pendingEvents :: ![Event]
-- ^ Processed events that didn't yield any action yet.
, onCloseActions :: !(M.Map BufferRef (EditorM ()))
-- ^ Actions to be run when the buffer is closed; should be scrapped.
} deriving Typeable
newtype EditorM a = EditorM {fromEditorM :: ReaderT Config (State Editor) a}
deriving (Monad, Applicative, MonadState Editor,
MonadReader Config, Functor)
instance MonadEditor EditorM where
askCfg = ask
withEditor = id
#if __GLASGOW_HASKELL__ < 708
deriving instance Typeable1 EditorM
#else
deriving instance Typeable EditorM
#endif
class (Monad m, MonadState Editor m) => MonadEditor m where
askCfg :: m Config
withEditor :: EditorM a -> m a
withEditor f = do
cfg <- askCfg
getsAndModify (runEditor cfg f)
withEditor_ :: EditorM a -> m ()
withEditor_ = withEditor . void
runEditor :: Config -> EditorM a -> Editor -> (Editor, a)
runEditor cfg f e = let (a, e') = runState (runReaderT (fromEditorM f) cfg) e
in (e',a)
-- Yi.Config
data UIConfig = UIConfig {
#ifdef FRONTEND_VTY
configVty :: Vty.Config,
#endif
configFontName :: Maybe String, -- ^ Font name, for the UI that support it.
configFontSize :: Maybe Int, -- ^ Font size, for the UI that support it.
configScrollStyle :: Maybe ScrollStyle,
-- ^ Style of scroll
configScrollWheelAmount :: Int, -- ^ Amount to move the buffer when using the scroll wheel
configLeftSideScrollBar :: Bool, -- ^ Should the scrollbar be shown on the left side?
configAutoHideScrollBar :: Bool, -- ^ Hide scrollbar automatically if text fits on one page.
configAutoHideTabBar :: Bool, -- ^ Hide the tabbar automatically if only one tab is present
configLineWrap :: Bool, -- ^ Wrap lines at the edge of the window if too long to display.
configCursorStyle :: CursorStyle,
configWindowFill :: Char,
-- ^ The char with which to fill empty window space. Usually '~' for vi-like
-- editors, ' ' for everything else.
configTheme :: Theme -- ^ UI colours
}
type UIBoot = Config -> ([Event] -> IO ())
-> ([Action] -> IO ()) -> Editor -> IO (UI Editor)
-- | When should we use a "fat" cursor (i.e. 2 pixels wide, rather than 1)? Fat
-- cursors have only been implemented for the Pango frontend.
data CursorStyle = AlwaysFat
| NeverFat
| FatWhenFocused
| FatWhenFocusedAndInserting
-- | Configuration record. All Yi hooks can be set here.
data Config = Config {startFrontEnd :: UIBoot,
-- ^ UI to use.
configUI :: UIConfig,
-- ^ UI-specific configuration.
startActions :: [Action],
-- ^ Actions to run when the editor is started.
initialActions :: [Action],
-- ^ Actions to run after startup (after startActions) or reload.
defaultKm :: KeymapSet,
-- ^ Default keymap to use.
configInputPreprocess :: I.P Event Event,
modeTable :: [AnyMode],
-- ^ List modes by order of preference.
debugMode :: Bool,
-- ^ Produce a .yi.dbg file with a lot of debug information.
configRegionStyle :: RegionStyle,
-- ^ Set to 'Exclusive' for an emacs-like behaviour.
configKillringAccumulate :: Bool,
-- ^ Set to 'True' for an emacs-like behaviour, where
-- all deleted text is accumulated in a killring.
configCheckExternalChangesObsessively :: Bool,
bufferUpdateHandler :: [[Update] -> BufferM ()],
layoutManagers :: [AnyLayoutManager],
-- ^ List of layout managers for 'cycleLayoutManagersNext'
configVars :: ConfigState.DynamicState
-- ^ Custom configuration, containing the 'YiConfigVariable's. Configure with 'configVariableA'.
}
-- Yi.Buffer.Normal
-- Region styles are relative to the buffer contents.
-- They likely should be considered a TextUnit.
data RegionStyle = LineWise
| Inclusive
| Exclusive
| Block
deriving (Eq, Typeable, Show)
instance Binary RegionStyle where
put LineWise = B.put (0 :: Word8)
put Inclusive = B.put (1 :: Word8)
put Exclusive = B.put (2 :: Word8)
put Block = B.put (3 :: Word8)
get = B.get >>= \case
(0 :: Word8) -> return LineWise
1 -> return Inclusive
2 -> return Exclusive
3 -> return Block
n -> fail $ "Binary RegionStyle fail with " ++ show n
-- TODO: put in the buffer state proper.
instance Default RegionStyle where
def = Inclusive
instance YiVariable RegionStyle
|
atsukotakahashi/wi
|
src/library/Yi/Types.hs
|
gpl-2.0
| 18,404
| 0
| 25
| 5,270
| 3,598
| 2,030
| 1,568
| -1
| -1
|
{-# LANGUAGE UnicodeSyntax, NoImplicitPrelude #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE TemplateHaskell #-}
module Tmk where
import BasePrelude hiding (toList)
import Prelude.Unicode hiding ((∈))
import Data.Foldable.Unicode ((∈))
import Data.List.Unicode ((∖))
import Data.Monoid.Unicode ((⊕))
import qualified Data.Set.Unicode as S
import Util (show', toString, (>$>), filterOnFst, groupWith', versionStr)
import WithBar (WithBar(..))
import WithPlus (WithPlus(..))
import Control.Monad.State (State, runState, get, gets, modify)
import Control.Monad.Writer (tell)
import Data.Foldable (toList)
import qualified Data.List.NonEmpty as NE
import Data.Map (Map)
import qualified Data.Map as M
import Data.Set (Set)
import qualified Data.Set as S
import Lens.Micro.Platform (view, over, makeLenses, _1, _2)
import Layout.Key (Key(..), getLevel, filterKeyOnShiftstatesM)
import Layout.Layout
import Layout.Modifier (toBaseModifier, getEqualModifiers)
import Layout.ModifierEffect (defaultModifierEffect)
import Layout.Types
import Lookup.Linux (actionAndRedirect, charAndString)
import Lookup.Tmk
import PresetLayout (defaultKeys, defaultFullLayout)
prepareLayout ∷ Logger m ⇒ Layout → m Layout
prepareLayout =
addSingletonKeysAsKeys >>>
addDefaultKeys defaultKeys >>>
_keys
( filterM (supportedPos ∘ view _pos) >=>
traverse (filterKeyOnShiftstatesM supportedShiftstate)
)
supportedPos ∷ Logger m ⇒ Pos → m Bool
supportedPos pos
| pos S.∈ __usedPosses unimap = pure True
| otherwise = False <$ tell [show' pos ⊕ " is not supported in TMK"]
supportedShiftstate ∷ Logger m ⇒ Shiftstate → m Bool
supportedShiftstate = fmap and ∘ traverse supportedModifier ∘ toList
supportedModifier ∷ Logger m ⇒ Modifier → m Bool
supportedModifier modifier
| defaultModifierEffect modifier ≡ Shift = pure True
| otherwise = False <$ tell [show' modifier ⊕ " is not supported for layer selection in TMK"]
data TmkLetter
= TmkAction String
| TmkFn String
| TmkModifier Modifier
| TmkMacro String [String] [String]
deriving (Eq, Show, Read)
isTmkModifier ∷ TmkLetter → Bool
isTmkModifier (TmkModifier _) = True
isTmkModifier _ = False
toMacro ∷ TmkLetter → Maybe (String, [String], [String])
toMacro (TmkMacro mId press release) = Just (mId, press, release)
toMacro _ = Nothing
type Tmk = State [String]
printTmkLetter ∷ Set Modifier → TmkLetter → Tmk String
printTmkLetter _ (TmkAction s) = pure s
printTmkLetter _ (TmkFn s) = writeAction s
printTmkLetter modifiersInfluenced (TmkModifier modifier)
| modifier ∈ modifiersInfluenced
= writeAction ("ACTION_FUNCTION_OPT(F_MODIFIER, MOD_" ⊕ map toUpper (toString modifier) ⊕ ")")
| otherwise = pure $ fromMaybe "NO" (lookup modifier modifierAndKeycode)
printTmkLetter _ (TmkMacro macroId _ _) = writeAction ("ACTION_MACRO(" ⊕ macroId ⊕ ")")
writeAction ∷ String → Tmk String
writeAction s = findIndex (≡ s) <$> get >>= maybe
(gets (("FN" ⊕) ∘ show ∘ length) <* modify (⧺ [s]))
(pure ∘ ("FN" ⊕) ∘ show)
data TmkLayer = TmkLayer
{ __tmkShiftstate ∷ Shiftstate
, __tmkLetters ∷ Map Pos TmkLetter
} deriving (Show, Read)
makeLenses ''TmkLayer
printTmkLayer ∷ Set Modifier → Int → (Map Pos TmkLetter, Shiftlevel) → Tmk [String]
printTmkLayer modifiersInfluenced i (tmkLetters, shiftlevel) = do
actions ← zipWithM (zipWithM printPos) (__sizes unimap) (__posses unimap)
pure (
[ "// " ⊕ toString shiftlevel
, "[" ⊕ show i ⊕ "] = " ⊕ __name unimap ⊕ "("
] ⧺ addCommas (map (intercalate ",") actions) ⧺
[ "),"
])
where
printPos size =
printTmkLetter modifiersInfluenced ∘ getTmkLetter >$>
printf ("%" ⊕ show size ⊕ "s")
getTmkLetter pos
| i ≡ 0 = fromMaybe (TmkAction "NO") $ asum
[ M.lookup pos tmkLetters
, TmkModifier <$> lookup pos posAndModifier
, TmkAction <$> lookup pos posAndTmkAction
]
| otherwise = fromMaybe (TmkAction "TRNS") $ M.lookup pos tmkLetters
addCommas [] = []
addCommas [x] = [x]
addCommas (x:xs) = x ⊕ "," : addCommas xs
data TmkKeymap = TmkKeymap
{ __tmkGetMaxIndex ∷ Shiftstate → Int
, __tmkLayers ∷ [TmkLayer]
}
makeLenses ''TmkKeymap
printTmkKeymap ∷ TmkKeymap → String
printTmkKeymap (TmkKeymap getMaxIndex layers') = unlines $
[ "// Generated by KLFC " ⊕ versionStr
, "// https://github.com/39aldo39/klfc"
, ""
, "#include \"unimap_trans.h\""
, "#include \"action_util.h\""
, "#include \"action_layer.h\""
, ""
, "enum function_id {"
, " F_MODIFIER,"
, "};"
, ""
] ⧺ bool (
[ "enum macro_id {"
] ⧺ map (\macro → replicate 4 ' ' ⊕ view _1 macro ⊕ ",") macros ⧺
[ "};"
, ""
]) [] (null macros) ⧺ bool (
[ "enum modifier_id {"
] ⧺ map (\m → replicate 4 ' ' ⊕ showMod m ⊕ ",") modifiersInfluencedList ⧺
[ "};"
, ""
]) [] (null modifiersInfluencedList)
⧺ zipWith (\i action → "#define AC_FN" ⊕ show i ⊕ " " ⊕ action) [0 ∷ Int ..] functionKeys ⧺
[ ""
, "#ifdef KEYMAP_SECTION_ENABLE"
, "const action_t actionmaps[][UNIMAP_ROWS][UNIMAP_COLS] __attribute__ ((section (\".keymap.keymaps\"))) = {"
, "#else"
, "const action_t actionmaps[][UNIMAP_ROWS][UNIMAP_COLS] PROGMEM = {"
, "#endif"
] ⧺ map (replicate 4 ' ' ⊕) printedLayers ⧺
[ "};"
, ""
] ⧺ bool (
[ "const macro_t *action_get_macro(keyrecord_t *record, uint8_t id, uint8_t opt) {"
, " switch (id) {"
] ⧺ concatMap (map (replicate 8 ' ' ⊕) ∘ printMacro) macros ⧺
[ " }"
, " return MACRO_NONE;"
, "}"
, ""
]) [] (null macros)
⧺ map (\m → "#define " ⊕ showMask m ⊕ " (" ⊕ intercalate "|" (map (\m' → "MOD_BIT(" ⊕ showKeycode m' ⊕ ")") (modifierToRealModifiers m)) ⊕ ")") realModsInShiftstates
⧺ bool [""] [] (null realModsInShiftstates)
⧺ bool (
[ "enum vmod_mask {"
] ⧺ zipWith (\i m → replicate 4 ' ' ⊕ showMask m ⊕ " = " ⊕ show (2^i ∷ Int) ⊕ ",") [0 ∷ Int ..] virtualModsInShiftstates ⧺
[ "};"
, ""
]) [] (null virtualModsInShiftstates) ⧺
[ "uint" ⊕ show indexSize ⊕ "_t vmods = 0;"
, ""
, "const uint" ⊕ show layerSize ⊕ "_t layer_states[] = {"
] ⧺ map (\(i, state) → replicate 4 ' ' ⊕ "0x" ⊕ showHex (layerStateAfterGrouping i) "," ⊕ " // " ⊕ toString state) (getLayers getMaxIndex layers') ⧺
[ "};"
, ""
, "void action_function(keyrecord_t *record, uint8_t id, uint8_t opt) {"
, " uint8_t pressed = record->event.pressed;"
, " switch (id) {"
, " case F_MODIFIER:"
, " // Set the new modifier"
, " switch (opt) {"
] ⧺
map (\m → " case " ⊕ showMod m ⊕ ": pressed ? add_key(" ⊕ showKeycode m ⊕ ") : del_key(" ⊕ showKeycode m ⊕ "); break;") realModsInfluenced ⧺
map (\m → " case " ⊕ showMod m ⊕ ": pressed ? (vmods |= " ⊕ showMask m ⊕ ") : (vmods &= ~" ⊕ showMask m ⊕ "); break;") virtualModsInfluenced ⧺
[ " }"
, ""
, " // Update the layer"
, " uint8_t mods = get_mods();"
, " uint" ⊕ show indexSize ⊕ "_t layer_index = 0;"
] ⧺ zipWith (\i m → " layer_index |= mods & " ⊕ showMask m ⊕ " ? " ⊕ show (2^i ∷ Int) ⊕ " : 0;") [0 ∷ Int ..] realModsInShiftstates ⧺
[ " layer_index |= vmods << " ⊕ show (length realModsInShiftstates) ⊕ ";"
, " layer_clear();"
, " layer_or(layer_states[layer_index]);"
, " break;"
, " }"
, "}"
]
where
(printedLayers, functionKeys) = flip runState [] $
concat <$> zipWithM (printTmkLayer modifiersInfluenced) [0..] layers
shiftstates = map __tmkShiftstate layers'
(layerStateAfterGrouping, layers) = groupLayers layers'
modifiersInShiftstates = S.unions ∘ map getSet $ shiftstates
modifiersInfluenced = S.fromList ∘ concatMap (concatMap getEqualModifiers ∘ toList) $ shiftstates
modifiersInfluencedList = toList modifiersInfluenced
showMod = ("MOD_" ⊕) ∘ map toUpper ∘ toString
showKeycode modifier =
let e = error (show' modifier ⊕ " is not a real modifier in TMK")
in "KC_" ⊕ fromMaybe e (lookup modifier modifierAndKeycode)
showMask modifier =
bool "V" "" (isRealModifier modifier) ⊕
showMod (toBaseModifier modifier) ⊕ "_MASK"
(realModsInShiftstates, virtualModsInShiftstates) = partition isRealModifier (toList modifiersInShiftstates)
(realModsInfluenced, virtualModsInfluenced) = partition isRealModifier modifiersInfluencedList
asPower2 x
| x < 1 = 8
| otherwise = max 8 (bit (ceiling (logBase 2 (fromIntegral x ∷ Double)) ∷ Int)) ∷ Int
indexSize = asPower2 (length modifiersInShiftstates)
layerSize = asPower2 (length layers')
macros = nub (mapMaybe toMacro (concatMap (M.elems ∘ fst) layers))
printMacro (mId, press, release) =
[ "case " ⊕ mId ⊕ ":"
, " return record->event.pressed ?"
, " " ⊕ printMacroPart press ⊕ " :"
, " " ⊕ printMacroPart release ⊕ ";"
]
printMacroPart [] = "MACRO_NONE"
printMacroPart parts = "MACRO(" ⊕ concatMap (⊕ ", ") parts ⊕ "END)"
getLayers ∷ (Shiftstate → Int) → [TmkLayer] → [(Int, Shiftstate)]
getLayers getMaxIndex layers = ($ shiftstates) $
S.toAscList ∘ S.unions ∘ map getSet >>> -- get an ascending list of modifiers
uncurry (⧺) ∘ partition isRealModifier >>> -- place the real modifiers at the front
map (WithPlus ∘ S.fromList) ∘ subsequences >>> -- generate the substates with the real modifiers at the front
map (sum ∘ map bit ∘ getActiveStates getMaxIndex shiftstates &&& id)
where
shiftstates = map __tmkShiftstate layers
getActiveStates ∷ (Shiftstate → Int) → [Shiftstate] → Shiftstate → [Int]
getActiveStates getMaxIndex states state =
findIndices (`isSubState` state) (take (getMaxIndex state) states)
toTmkKeymap ∷ Logger m ⇒ Layout → m TmkKeymap
toTmkKeymap =
prepareLayout >=>
toTmkKeymap' >$>
over _tmkLayers addTransLetters >>>
removeTransLayers
toTmkKeymap' ∷ Logger m ⇒ Layout → m TmkKeymap
toTmkKeymap' layout =
TmkKeymap getMaxIndex <$> zipWithM lettersToTmkLayer shiftstates letters
where
(keys, shiftstates) = unifyShiftstates (view _keys layout)
shiftlevels = map (WithBar ∘ (:| [])) shiftstates
posses = map (view _pos) keys
letters = map (M.fromList ∘ zip posses) ∘ transpose ∘ map (view _letters) $ keys
getMaxIndex = maybe (length shiftstates) (succ ∘ fst) ∘ getLevel keyForShiftstates
keyForShiftstates = Key undefined undefined shiftlevels undefined (Just False)
removeTransLayers ∷ TmkKeymap → TmkKeymap
removeTransLayers (TmkKeymap getMaxIndex layers) = TmkKeymap getMaxIndex' layers'
where
(layers', filteredIndices) = ($ layers) $
map (mfilter (not ∘ allTrans) ∘ Just) >>>
catMaybes &&& findIndices isJust
getMaxIndex' = (\i → length (takeWhile (< i) filteredIndices)) ∘ getMaxIndex
lettersToTmkLayer ∷ Logger m ⇒ Shiftstate → Map Pos Letter → m TmkLayer
lettersToTmkLayer state = traverse (letterToTmkLetter state) >$> TmkLayer state
letterToTmkLetter ∷ Logger m ⇒ Shiftstate → Letter → m TmkLetter
letterToTmkLetter state letter = letterToTmkLetter' letter state letter
letterToTmkLetter' ∷ Logger m ⇒ Letter → Shiftstate → Letter → m TmkLetter
letterToTmkLetter' _ _ LNothing = pure (TmkAction "NO")
letterToTmkLetter' _ _ (Ligature _ s)
| Just tmkLetter ← tmkLetterByMacro (map Char s) = pure tmkLetter
letterToTmkLetter' errorL state (Action a)
| Just action ← lookup a actionAndTmkAction = pure (TmkAction action)
| Just letter ← lookup a actionAndRedirect = letterToTmkLetter' errorL state letter
letterToTmkLetter' _ _ (Modifiers _ []) = pure (TmkAction "NO")
letterToTmkLetter' _ _ (Modifiers effect [modifier])
| effect ≡ defaultModifierEffect modifier = pure (TmkModifier modifier)
letterToTmkLetter' _ _ (Redirect [] pos)
| Just posAction ← lookup pos posAndTmkAction = pure (TmkAction posAction)
letterToTmkLetter' _ state (Redirect modifiers pos)
| Just posAction ← lookup pos posAndTmkAction = do
mods ← intercalate "|" ∘ catMaybes <$> traverse printMod (modifiers ∖ toList state)
case mods of
"" → pure (TmkAction posAction)
_ → pure $ TmkFn ("ACTION_MODS_KEY(" ⊕ mods ⊕ ", KC_" ⊕ posAction ⊕ ")")
where
printMod modifier =
case lookup modifier modifierAndKeycode of
Just keycode → pure (Just ("MOD_BIT(KC_" ⊕ keycode ⊕ ")"))
Nothing → Nothing <$ tell [show' modifier ⊕ " is not supported in TMK"]
letterToTmkLetter' _ state letter
| action:_ ← mapMaybe posToAction posses = pure (TmkAction action)
where
posses = getPosByLetterAndShiftstate letter state defaultFullLayout
posToAction = flip lookup posAndTmkAction
letterToTmkLetter' _ _ letter
| Just tmkLetter ← tmkLetterByMacro [letter] = pure tmkLetter
letterToTmkLetter' errorL state _ =
TmkAction "NO" <$ tell [show' errorL ⊕ " is not supported on " ⊕ show' state ⊕ " in TMK"]
tmkLetterByMacro ∷ [Letter] → Maybe TmkLetter
tmkLetterByMacro letters = TmkMacro mId <$> macro letters <*> pure []
where
mId = "LIG_" ⊕ concatMap letterToString letters
letterToString (Char c)
| isAscii c ∧ isAlphaNum c = [c]
| otherwise = "_" ⊕ fromMaybe (printf "U%04X" c) (lookup c charAndString) ⊕ "_"
letterToString letter = "_" ⊕ toString letter ⊕ "_"
macro =
traverse getPosAndShiftlevel >=>
groupWith' snd >>>
(traverse ∘ _1) (traverse (flip lookup modifierAndKeycode) ∘ toList ∘ NE.head ∘ getNonEmpty) >=>
(traverse ∘ _2 ∘ traverse) (flip lookup posAndTmkAction ∘ fst) >$>
concatMap (uncurry modsAndCodesToMacro) >>>
(["SM()", "CM()"] ⧺) ∘ (⧺ ["RM()"])
getPosAndShiftlevel letter =
view _keys defaultFullLayout &
concatMap (\key → map ((,) (view _pos key)) (getValidShiftlevels letter key)) &
listToMaybe
getValidShiftlevels letter key =
filterOnFst (≡ letter) (view _letters key `zip` view _shiftlevels key)
modsAndCodesToMacro modifiers keycodes =
map (\m → "D(" ⊕ m ⊕ ")") modifiers ⧺
map (\c → "T(" ⊕ c ⊕ ")") keycodes ⧺
map (\m → "U(" ⊕ m ⊕ ")") modifiers
groupLayers ∷ [TmkLayer] → (Int → Int, [(Map Pos TmkLetter, Shiftlevel)])
groupLayers layers = (flip layerStateAfterGrouping &&& layers') groupedLayers
where
groupedLayers = NE.groupWith __tmkLetters layers
layerStateAfterGrouping initState =
NE.tail ∘ NE.scanl (\(_, start) gr → (start, start + length gr)) (0, 0) >>>
map (any (testBit initState) ∘ range ∘ over _2 pred) >>>
sum ∘ (\xs → zipWith (bool 0 ∘ bit) [0..length xs] xs)
layers' = map (__tmkLetters ∘ NE.head &&& WithBar ∘ fmap __tmkShiftstate)
addTransLetters ∷ [TmkLayer] → [TmkLayer]
addTransLetters [] = []
addTransLetters (x:xs) = addTransLetters' [] x xs
addTransLetters' ∷ [TmkLayer] → TmkLayer → [TmkLayer] → [TmkLayer]
addTransLetters' low layer high = layer' : nextLayers
where
prevLetters = ($ low) $
filter (`isSubLayer` layer) >>>
M.unions ∘ map (M.filter (≢ TmkAction "TRNS") ∘ __tmkLetters)
layer' = over _tmkLetters replaceLetters layer
replaceLetters = M.unionWith replaceLetter prevLetters
replaceLetter otherLetter letter
| otherLetter ≡ letter = TmkAction "TRNS"
| otherwise = letter
nextLayers = fromMaybe [] $
uncurry (addTransLetters' (layer' : low)) <$> uncons high
allTrans ∷ TmkLayer → Bool
allTrans = all (∈ map TmkAction ["TRNS", "NO"]) ∘ __tmkLetters
isSubLayer ∷ TmkLayer → TmkLayer → Bool
isSubLayer = isSubState `on` __tmkShiftstate
isSubState ∷ Shiftstate → Shiftstate → Bool
isSubState = (S.⊆) `on` getSet
|
39aldo39/klfc
|
src/Tmk.hs
|
gpl-3.0
| 16,481
| 0
| 32
| 3,623
| 5,125
| 2,647
| 2,478
| 327
| 3
|
module PPA.Analysis.AvailableExpressions where
import Prelude hiding (init)
import qualified Data.Set as Set
import qualified Data.List as List
import qualified Data.Array.IArray as Array
import PPA.Lang.While
import PPA.Lang.While.Util
type AE = Set.Set AExp
type VecAE = Array.Array Integer AE
type VecF = Array.Array Integer (Solution -> AE)
data Solution = Solution { entryAE :: VecAE
, exitAE :: VecAE
} deriving (Show, Eq)
data Solver = Solver { entryF :: VecF
, exitF :: VecF
}
genIter :: Integer -> Solver -> Solution -> Solution
genIter l s rd = Solution { entryAE = entries, exitAE = exits }
where
entries = Array.array (1, l) [ (i, ((entryF s) Array.! i) rd) | i <- [1..l]]
exits = Array.array (1, l) [ (i, ((exitF s) Array.! i) rd) | i <- [1..l]]
-- compute fixpoint
fix :: (Eq a) => a -> (a -> a) -> a
fix start f =
if start == next then
start
else
fix next f
where
next = f start
kill :: Stmt -> Lab -> Set.Set AExp
kill s l =
case bf l of
(BAssign x a _) -> Set.filter (\ a -> x `Set.member` fvA a) $ aExp s
(BSkip _) -> Set.empty
(BBExp _ _) -> Set.empty
where
bf :: Lab -> Block
bf = blockMap $ blocks s
gen :: Stmt -> Lab -> Set.Set AExp
gen s l =
case bf l of
(BAssign x a _) -> Set.filter (\ a -> x `Set.notMember` fvA a) $ aExpA a
(BSkip _) -> Set.empty
(BBExp b _) -> aExpB b
where
bf :: Lab -> Block
bf = blockMap $ blocks s
ae :: Stmt -> Solution
ae s =
fix start $ genIter sz solver
where
start = Solution { entryAE = upper, exitAE = upper }
where
upper :: VecAE
upper = Array.array (1, sz) [(i, aExp s) | i <- [1..sz]]
solver = Solver { entryF = aeEntry, exitF = aeExit }
where
aeEntry :: VecF
aeEntry = Array.array (1, sz) [(i, (\ ae ->
if i == init s then
Set.empty
else
List.foldl Set.intersection (aExp s) [(exitAE ae) Array.! l' | (l', l) <- Set.toList $ flow s, l == i])) | i <- [1..sz]]
aeExit :: VecF
aeExit = Array.array (1, sz) [(i, (\ ae ->
Set.union (((entryAE ae) Array.! i) Set.\\ (kill s i)) (gen s i))) | i <- [1..sz]]
sz :: Integer
sz = toInteger $ Set.size $ labels s
|
Isweet/ppa
|
src/PPA/Analysis/AvailableExpressions.hs
|
gpl-3.0
| 2,526
| 0
| 20
| 921
| 1,027
| 563
| 464
| 58
| 3
|
import SimpleGraphics
sierp1 :: Int -> Graphic
sierp1 0 = rectangle 1 1
sierp1 n = overGraphics
. zipWith translate [(x*3^(n-1),y*3^(n-1))|x<-[0..2],y<-[0..2],x/=1 || y/=1]
. repeat . sierp1 $ n - 1
sierp2 :: Int -> Graphic
sierp2 0 = polygon [(0,0),(0,1),(1,0)]
sierp2 n = overGraphics
. zipWith translate [(x*2^(n-1),y*2^(n-1)) | (x,y) <- [(0,0),(0,1),(1,0)]]
. repeat . sierp2 $ n - 1
main :: IO ()
main = do
putStrLn "Writing sierp1.svg"
writeImage "sierp-ctverec.svg" (sierp1 5)
putStrLn "Writing sierp2.svg"
writeImage "sierp-trojuhelnik.svg" (sierp2 9)
|
xkollar/handy-haskell
|
svg-graphic-teach/examples/sierp.hs
|
gpl-3.0
| 596
| 0
| 15
| 118
| 355
| 189
| 166
| 17
| 1
|
{-
Author: <authors name>
Maintainer: <maintainer's name>
Email: <maintainer's email>
License: GPL 3.0
File: filename
Description: short description
-}
{-
General comments
-}
-- Function documentation/description (not comments)
someFunction :: a -> b -> ...
someFunction = definition
{-
Always explain functions just above them so Hackage can help us generate documentation
"TODO:" Will denote a task to do
"WARNING:" Some important information to put in the documentation
-}
|
j5b/ps-pc
|
template.hs
|
gpl-3.0
| 511
| 2
| 7
| 104
| 25
| 14
| 11
| -1
| -1
|
module Pythia8.Desc.Annotate where
|
wavewave/HPythia8-generate
|
lib/Pythia8/Desc/Annotate.hs
|
gpl-3.0
| 35
| 0
| 3
| 3
| 7
| 5
| 2
| 1
| 0
|
{-# LANGUAGE TypeFamilies #-}
module Lamdu.Sugar.Convert.Apply
( convert
) where
import qualified Control.Lens as Lens
import Control.Monad.Once (Typeable)
import Control.Monad.Trans.Except.Extended (runMatcherT, justToLeft)
import Control.Monad.Trans.Maybe (MaybeT(..))
import qualified Data.Map as Map
import Data.Maybe.Extended (maybeToMPlus)
import qualified Data.Property as Property
import qualified Data.Set as Set
import Hyper
import Hyper.Syntax (funcIn)
import Hyper.Syntax.Row (freExtends, freRest)
import Hyper.Syntax.Scheme (sTyp)
import Lamdu.Calc.Definition (Deps, depsGlobalTypes)
import qualified Lamdu.Calc.Term as V
import qualified Lamdu.Calc.Type as T
import qualified Lamdu.Expr.IRef as ExprIRef
import qualified Lamdu.Sugar.Config as Config
import Lamdu.Sugar.Convert.Expression.Actions (addActions, addActionsWith, subexprPayloads)
import Lamdu.Sugar.Convert.Fragment (convertAppliedHole)
import Lamdu.Sugar.Convert.GetField (convertGetFieldParam)
import Lamdu.Sugar.Convert.IfElse (convertIfElse)
import qualified Lamdu.Sugar.Convert.Input as Input
import Lamdu.Sugar.Convert.Monad (ConvertM)
import qualified Lamdu.Sugar.Convert.Monad as ConvertM
import Lamdu.Sugar.Internal
import qualified Lamdu.Sugar.Internal.EntityId as EntityId
import Lamdu.Sugar.Lens (childPayloads, getVarName, taggedListItems)
import qualified Lamdu.Sugar.PresentationModes as PresentationModes
import Lamdu.Sugar.Types
import Revision.Deltum.Transaction (Transaction)
import Lamdu.Prelude
convert ::
(Monad m, Typeable m, Monoid a) =>
V.App V.Term # Ann (Input.Payload m a) ->
Input.Payload m a # V.Term ->
ConvertM m (ExpressionU EvalPrep m a)
convert app@(V.App funcI argI) exprPl =
runMatcherT $
do
convertGetFieldParam app exprPl & MaybeT & justToLeft
(funcS, argS) <-
do
argS <- ConvertM.convertSubexpression argI & lift
convertAppliedHole app exprPl argS & justToLeft
funcS <- ConvertM.convertSubexpression funcI & lift
protectedSetToVal <- lift ConvertM.typeProtectedSetToVal
pure
( if Lens.has (hVal . _BodyLeaf . _LeafHole) argS
then
let dst = argI ^. hAnn . Input.stored . ExprIRef.iref
deleteAction =
EntityId.ofValI dst <$
protectedSetToVal (exprPl ^. Input.stored) dst
in funcS
& annotation . pActions . delete .~ SetToHole deleteAction
else funcS
, argS
)
convertEmptyInject app funcS argS exprPl & justToLeft
convertPostfix app funcS argS exprPl & justToLeft
convertLabeled app funcS argS exprPl & justToLeft
convertPrefix app funcS argS exprPl & lift
defParamsMatchArgs ::
V.Var ->
Composite v InternalName i o # Ann a ->
Deps ->
Bool
defParamsMatchArgs var record frozenDeps =
do
defArgs <-
frozenDeps ^?
depsGlobalTypes . Lens.at var . Lens._Just
. _Pure . sTyp . _Pure . T._TFun . funcIn
. _Pure . T._TRecord . T.flatRow
defArgs ^? freRest . _Pure . T._REmpty
let sFields =
record ^..
( cList . taggedListItems . tiTag . tagRefTag . tagVal
<> cPunnedItems . traverse . pvVar . hVal . Lens._Wrapped . getVarName . inTag
) & Set.fromList
guard (sFields == Map.keysSet (defArgs ^. freExtends))
& Lens.has Lens._Just
convertEmptyInject ::
(Monad m, Monoid a, Recursively HFoldable h) =>
h # Ann (Input.Payload m a) ->
ExpressionU v m a -> ExpressionU v m a -> Input.Payload m a # V.Term ->
MaybeT (ConvertM m) (ExpressionU v m a)
convertEmptyInject subexprs funcS argS applyPl =
do
inject <- annValue (^? _BodyLeaf . _LeafInject . Lens._Unwrapped) funcS & maybeToMPlus
r <- annValue (^? _BodyRecord) argS & maybeToMPlus
r ^. hVal . cList . tlItems & null & guard
r ^. hVal . cPunnedItems & null & guard
Lens.has (hVal . cTail . _ClosedComposite) r & guard
r & annValue %~ (^. cList . tlAddFirst . Lens._Unwrapped)
& NullaryInject inject & BodyNullaryInject
& addActions subexprs applyPl & lift
convertPostfix ::
(Monad m, Monoid a, Recursively HFoldable h) =>
h # Ann (Input.Payload m a) ->
ExpressionU v m a -> ExpressionU v m a -> Input.Payload m a # V.Term ->
MaybeT (ConvertM m) (ExpressionU v m a)
convertPostfix subexprs funcS argS applyPl =
do
postfixFunc <- annValue (^? _BodyPostfixFunc) funcS & maybeToMPlus
del <- makeDel applyPl & lift
let postfix =
PostfixApply
{ _pArg = argS & annotation . pActions . delete . Lens.filteredBy _CannotDelete .~ del funcS
, _pFunc = postfixFunc
}
setTo <- lift ConvertM.typeProtectedSetToVal ?? applyPl ^. Input.stored
ifSugar <- Lens.view (ConvertM.scConfig . Config.sugarsEnabled . Config.ifExpression)
guard ifSugar *> convertIfElse setTo postfix
& maybe (BodyPostfixApply postfix) BodyIfElse
& addActions subexprs applyPl & lift
convertLabeled ::
(Monad m, Monoid a, Recursively HFoldable h) =>
h # Ann (Input.Payload m a) ->
ExpressionU v m a -> ExpressionU v m a -> Input.Payload m a # V.Term ->
MaybeT (ConvertM m) (ExpressionU v m a)
convertLabeled subexprs funcS argS exprPl =
do
Lens.view (ConvertM.scConfig . Config.sugarsEnabled . Config.labeledApply) >>= guard
-- Make sure it's a not a param, get the var
-- Make sure it is not a "let" but a "def" (recursive or external)
funcVar <-
annValue
( ^? _BodyLeaf . _LeafGetVar . _GetBinder
. Lens.filteredBy (bvForm . _GetDefinition)
. Lens._Unwrapped
) funcS
& maybeToMPlus
-- Make sure the argument is a record
record <- argS ^? hVal . _BodyRecord & maybeToMPlus
-- that is closed
Lens.has (cTail . _ClosedComposite) record & guard
-- with at least 2 fields
length (record ^.. cList . taggedListItems) + length (record ^. cPunnedItems) >= 2 & guard
frozenDeps <- Lens.view ConvertM.scFrozenDeps <&> Property.value
let var = funcVar ^. hVal . Lens._Wrapped . bvVar
-- If it is an external (non-recursive) def (i.e: not in
-- scope), make sure the def (frozen) type is inferred to have
-- closed record of same parameters
recursiveRef <- Lens.view (ConvertM.scScopeInfo . ConvertM.siRecursiveRef)
Just var == (recursiveRef <&> (^. ConvertM.rrDefI) <&> ExprIRef.globalId)
|| defParamsMatchArgs var record frozenDeps & guard
let getArg field =
AnnotatedArg
{ _aaTag = field ^. tiTag . tagRefTag
, _aaExpr = field ^. tiValue
}
bod <-
PresentationModes.makeLabeledApply
funcVar
(record ^.. cList . taggedListItems <&> getArg)
(record ^. cPunnedItems) exprPl
<&> BodyLabeledApply & lift
let userPayload =
subexprPayloads subexprs (bod ^.. childPayloads)
& mconcat
addActionsWith userPayload exprPl bod & lift
convertPrefix ::
(Monad m, Monoid a) =>
V.App V.Term # Ann (Input.Payload m a) ->
ExpressionU v m a -> ExpressionU v m a -> Input.Payload m a # V.Term ->
ConvertM m (ExpressionU v m a)
convertPrefix subexprs funcS argS applyPl =
do
del <- makeDel applyPl
protectedSetToVal <- ConvertM.typeProtectedSetToVal
let injectToNullary x
| Lens.has (hVal . _BodyLeaf . _LeafInject) funcS =
do
ExprIRef.writeValI argIref (V.BLeaf V.LRecEmpty)
protectedSetToVal (applyPl ^. Input.stored) (applyPl ^. Input.stored . ExprIRef.iref)
<&> EntityId.ofValI
| otherwise = x
where
argIref = subexprs ^. V.appArg . hAnn . Input.stored . ExprIRef.iref
BodySimpleApply App
{ _appFunc = funcS & annotation . pActions . delete .~ del argS
, _appArg =
argS
& annotation . pActions . delete %~ (_Delete %~ injectToNullary) . (Lens.filteredBy _CannotDelete .~ del funcS)
} & addActions subexprs applyPl
makeDel ::
Monad m =>
Input.Payload m a # V.Term ->
ConvertM m ((Annotated (ConvertPayload m a2) # h) -> Delete (Transaction m))
makeDel applyPl =
ConvertM.typeProtectedSetToVal <&>
\protectedSetToVal remain ->
protectedSetToVal (applyPl ^. Input.stored)
(remain ^. annotation . pInput . Input.stored . ExprIRef.iref)
<&> EntityId.ofValI
& Delete
|
Peaker/lamdu
|
src/Lamdu/Sugar/Convert/Apply.hs
|
gpl-3.0
| 9,285
| 0
| 24
| 2,901
| 2,555
| 1,314
| 1,241
| -1
| -1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.