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 DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Data.IHO.S57.VRID where import Control.Lens import Data.Data (Data) import Data.IHO.S57.Types import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Data.Text (Text) import qualified Data.Text as T import Data.Tree import Data.Typeable (Typeable) data VRPC = VRPC { _vrpcUpdateInstruction :: ! UpdateInstruction , _vrpcObjectPointerIndex :: ! Int , _vrpcObjectPointers :: ! Int } deriving (Show, Eq, Data, Typeable) makeLenses ''VRPC readVRPC :: Tree S57Structure -> VRPC readVRPC r | (structureFieldName . rootLabel $ r) /= "VRPC" = error $ "not an VRPC record: " ++ show r | otherwise = VRPC { _vrpcUpdateInstruction = lookupField r "VPUI" , _vrpcObjectPointerIndex = lookupField r "VPIX" , _vrpcObjectPointers = lookupField r "NVPT" } data TopologyIndicator = BeginningNode | EndNode | LeftFace | RightFace | ContainingFace | NullTopo deriving (Show, Eq, Data, Typeable) data VRPT = VRPT { _vrptName :: ! RecordName , _vrptOrientation :: ! Orientation , _vrptUsageIndicator :: ! UsageIndicator , _vrptTopologyIndicator :: ! TopologyIndicator , _vrptMaskingIndicator :: ! MaskingIndicator } deriving (Show, Eq, Data, Typeable) mkVRPTs :: S57FileRecord -> [VRPT] mkVRPTs r | (structureFieldName . rootLabel $ r) /= "VRPT" = error $ "not an VRPT record: " ++ show r | otherwise = let rv = structureMultiField . rootLabel $ r lookupFieldM k _r = maybe (error $ "mkVRPT: unable to lookup key " ++ T.unpack k) id $ Map.lookup k _r _lookupField k _r = fromS57Value $ lookupFieldM k _r mkVRPT _r = VRPT { _vrptName = _lookupField "*NAME" _r , _vrptOrientation = _lookupField "ORNT" _r , _vrptUsageIndicator = _lookupField "USAG" _r , _vrptTopologyIndicator = _lookupField "TOPI" _r , _vrptMaskingIndicator = _lookupField "MASK" _r } in fmap mkVRPT rv data SGCC = SGCC { _sgccUpdateInstruction :: ! UpdateInstruction , _sgccCoordinateIndex :: ! Int , _sgccCoordinates :: ! Int } deriving (Show, Eq, Data, Typeable) makeLenses ''SGCC readSGCC :: Tree S57Structure -> SGCC readSGCC r | ((structureFieldName . rootLabel $ r) /= "SGCC") = error $ "not an SGCC record: " ++ show r | otherwise = SGCC { _sgccUpdateInstruction = lookupField r "CCUI" , _sgccCoordinateIndex = lookupField r "CCIX" , _sgccCoordinates = lookupField r "CCNC" } mkSG2Ds :: S57FileRecord -> [(Double, Double)] mkSG2Ds = let mkSG2D lf _r = (lf "*YCOO" _r, lf "XCOO" _r) in mkTuples "mkSG2D" mkSG2D mkSG3Ds :: S57FileRecord -> [(Double, Double, Double)] mkSG3Ds = let mkSG3D lf _r = (lf "*YCOO" _r, lf "XCOO" _r, lf "VE3D" _r) in mkTuples "mkSG3D" mkSG3D data VRID = VRID { _vridRecordName :: ! RecordName , _vridVersion :: ! Int , _vridUpdateInstruction :: UpdateInstruction , _vridATTFs :: ! (Map Int Text) , _vridVRPC :: ! (Maybe VRPC) , _vridVRPTs :: ! [VRPT] , _vridSGCC :: ! (Maybe SGCC) , _vridSG2Ds :: ! [(Double, Double)] , _vridSG3Ds :: ! [(Double, Double, Double)] } deriving (Show, Eq, Data, Typeable) makeLenses ''VRID vridTableEmpty :: RecordTable VRID vridTableEmpty = mempty vridUpsert :: RecordTable VRID -> VRID -> RecordTable VRID vridUpsert tbl v = let rv = v ^. vridVersion vui = v ^. vridUpdateInstruction in case vui of Insert -> if rv /= 1 then error $ "vridUpsert: INSERT record with version != 1: " ++ show v else insertRecord v tbl Delete -> deleteRecord v tbl Modify -> let rn = v ^. recordName r = fromMaybe (error $ "vridUpdate: MODIFY for non existing record: " ++ show rn) $ lookupRecord v tbl attfs = updateATTFs (r ^. vridATTFs) $ Map.toList $ v ^. vridATTFs vrpts = maybe (v ^. vridVRPTs) (updateVRPTs v r) $ pointerUpdateApplyable vridVRPC vridVRPTs r sg2ds = maybe (v ^. vridSG2Ds) (updateSG2Ds v r) $ pointerUpdateApplyable vridSGCC vridSG2Ds r sg3ds = maybe (v ^. vridSG3Ds) (updateSG3Ds v r) $ pointerUpdateApplyable vridSGCC vridSG2Ds r r' = r { _vridVersion = rv , _vridUpdateInstruction = vui , _vridATTFs = attfs , _vridVRPTs = vrpts , _vridSG2Ds = sg2ds , _vridSG3Ds = sg3ds } in if rv <= (r ^.vridVersion) then error $ "vridUpdate: MODIFY must have a version >= " ++ show rv else insertRecord r' tbl updateVRPTs :: VRID -> VRID -> VRPC -> [VRPT] updateVRPTs = updatePointerFields vrpcUpdateInstruction vrpcObjectPointerIndex vrpcObjectPointers vridVRPTs updateBySGCC :: Getting [b] VRID [b] -> VRID -> VRID -> SGCC -> [b] updateBySGCC = updatePointerFields sgccUpdateInstruction sgccCoordinateIndex sgccCoordinates updateSG2Ds :: VRID -> VRID -> SGCC -> [(Double, Double)] updateSG2Ds = updateBySGCC vridSG2Ds updateSG3Ds :: VRID -> VRID -> SGCC -> [(Double, Double, Double)] updateSG3Ds = updateBySGCC vridSG3Ds instance FromS57FileRecord VRID where fromS57FileDataRecord r | ((structureFieldName . rootLabel $ r) /= "VRID") = error $ "not an VRID record: " ++ show r | otherwise = VRID { _vridRecordName = RecordName { _rcnm = lookupField r "RCNM", _rcid = lookupField r "RCID" } , _vridVersion = lookupField r "RVER" , _vridUpdateInstruction = lookupField r "RUIN" , _vridATTFs = maybe mempty mkAttrs $ lookupChildFieldM "VRID" r "ATTF" , _vridVRPC = fmap readVRPC $ lookupChildFieldM "VRID" r "FFPC" , _vridVRPTs = maybe mempty mkVRPTs $ lookupChildFieldM "VRID" r "VRPT" , _vridSGCC = fmap readSGCC $ lookupChildFieldM "VRID" r "SGCC" , _vridSG2Ds = maybe mempty mkSG2Ds $ lookupChildFieldM "VRID" r "SG2D" , _vridSG3Ds = maybe mempty mkSG3Ds $ lookupChildFieldM "VRID" r "SG3D" } instance HasRecordName VRID where recordName = vridRecordName instance Enum TopologyIndicator where toEnum 1 = BeginningNode toEnum 2 = EndNode toEnum 3 = LeftFace toEnum 4 = RightFace toEnum 5 = ContainingFace toEnum 255 = NullTopo toEnum t = error $ "toEnum: " ++ show t ++ " is not a TopologyIndicator" fromEnum BeginningNode = 1 fromEnum EndNode = 2 fromEnum LeftFace = 3 fromEnum RightFace = 4 fromEnum ContainingFace = 5 fromEnum NullTopo = 255 instance FromS57Value TopologyIndicator where fromS57Value (S57CharData "B") = BeginningNode fromS57Value (S57CharData "E") = EndNode fromS57Value (S57CharData "S") = LeftFace fromS57Value (S57CharData "D") = RightFace fromS57Value (S57CharData "F") = ContainingFace fromS57Value (S57CharData "N") = NullTopo fromS57Value (S57Int i) = toEnum i fromS57Value v = error $ "fromS57Value TopologyIndicator undefined for " ++ show v
alios/iho-s57
library/Data/IHO/S57/VRID.hs
bsd-3-clause
7,969
38
19
2,600
2,053
1,087
966
222
5
module Data.ByteString.ShellEscape.EscapeVector where import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as ByteString import Data.Vector (Vector) import qualified Data.Vector as Vector import qualified Data.Vector.Mutable as Vector (new, write) import qualified Data.ByteString.ShellEscape.Put as Put type EscapeVector escapingMode = Vector (Char, escapingMode) escWith :: (Char -> escapingMode) -> ByteString -> EscapeVector escapingMode escWith cf b = Vector.create $ do v <- Vector.new (ByteString.length b) sequence_ . snd $ ByteString.foldl' (f v) (0, []) b return v where f v (i, ops) c = (i + 1, Vector.write v i (c, cf c) : ops) stripEsc :: Vector (Char, escapingMode) -> ByteString stripEsc v = ByteString.unfoldr f . fst $ Vector.unzip v where f v | Vector.null v = Nothing | otherwise = Just (Vector.unsafeHead v, Vector.unsafeTail v) interpretEsc v f finish init = (eval . (finish lastMode :)) instructions where eval = Put.runPut' . sequence_ . reverse (instructions, lastMode) = Vector.foldl' f' init v where f' (list, mode) (c, e) = (put:list, mode') where (put, mode') = f mode (c, e)
solidsnack/shell-escape
Data/ByteString/ShellEscape/EscapeVector.hs
bsd-3-clause
1,339
0
12
374
461
252
209
23
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} module Network.Craze.Internal where import Control.Exception (SomeException) import Control.Monad (forM, when) import Data.Map.Lazy (Map) import qualified Data.Map.Lazy as M import Data.Monoid ((<>)) import Control.Concurrent.Async.Lifted (Async, async, asyncThreadId, cancel, waitAnyCatch) import Control.Concurrent.Lifted (threadDelay) import Control.Lens (at, makeLenses, use, (&), (.~), (?=)) import Control.Monad.State (MonadState) import Control.Monad.Trans (MonadIO, liftIO) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as TIO import Network.Curl (CurlBuffer, CurlHeader, CurlResponse_, curlGetResponse_) import Network.Craze.Types type ClientMap ht bt a = Map (Async (CurlResponse_ ht bt)) (ClientState a) data ClientState a = ClientState { _csOptions :: ProviderOptions , _csStatus :: ClientStatus a } data RaceState ht bt a = RaceState { _rsClientMap :: ClientMap ht bt a , _rsChecker :: RacerChecker a , _rsHandler :: RacerHandler ht bt a , _rsDebug :: Bool , _rsReturnLast :: Bool } makeLenses ''ClientState makeLenses ''RaceState extractStatuses :: RaceState ht bt a -> [(Text, ClientStatus a)] extractStatuses RaceState{..} = M.elems $ makeTuple <$> _rsClientMap where makeTuple :: ClientState a -> (Text, ClientStatus a) makeTuple ClientState{..} = (poTag _csOptions, _csStatus) makeRaceState :: (CurlHeader ht, CurlBuffer bt, MonadIO m) => Text -> Racer ht bt a -> m (RaceState ht bt a) makeRaceState url Racer{..} = do providerMap <- makeClientMap url racerProviders pure $ RaceState providerMap racerChecker racerHandler racerDebug racerReturnLast makeClientMap :: (CurlHeader ht, CurlBuffer bt, MonadIO m) => Text -> [RacerProvider] -> m (ClientMap ht bt a) makeClientMap url providers = M.fromList <$> forM providers (makeClient url) makeClient :: (CurlHeader ht, CurlBuffer bt, MonadIO m) => Text -> RacerProvider -> m (Async (CurlResponse_ ht bt), ClientState a) makeClient url provider = liftIO $ do options <- provider future <- async $ performGet url options pure (future, ClientState options Pending) performGet :: (CurlHeader ht, CurlBuffer bt) => Text -> ProviderOptions -> IO (CurlResponse_ ht bt) performGet url ProviderOptions{..} = do case poDelay of Nothing -> pure () Just delay -> threadDelay delay curlGetResponse_ (T.unpack url) poOptions cancelAll :: MonadIO m => [Async a] -> m () cancelAll = liftIO . mapM_ (async . cancel) cancelRemaining :: (MonadIO m, MonadState (RaceState ht bt a) m) => m () cancelRemaining = do remaining <- onlyPending <$> use rsClientMap cancelAll $ M.keys remaining identifier :: Async (CurlResponse_ ht bt) -> ProviderOptions -> Text identifier a o = poTag o <> ":" <> (T.pack . show . asyncThreadId $ a) onlyPending :: ClientMap ht bt a -> ClientMap ht bt a onlyPending = M.filter (isPending . _csStatus) isPending :: ClientStatus a -> Bool isPending Pending = True isPending _ = False markAsSuccessful :: (MonadState (RaceState ht bt a) m) => Async (CurlResponse_ ht bt) -> a -> m () markAsSuccessful key result = do maybePrevious <- use $ rsClientMap . at key case maybePrevious of Just previous -> (rsClientMap . at key) ?= (previous & csStatus .~ Successful result) Nothing -> pure () markAsFailure :: (MonadState (RaceState ht bt a) m) => Async (CurlResponse_ ht bt) -> a -> m () markAsFailure key result = do maybePrevious <- use $ rsClientMap . at key case maybePrevious of Just previous -> (rsClientMap . at key) ?= (previous & csStatus .~ Failed result) Nothing -> pure () markAsErrored :: (MonadState (RaceState ht bt a) m) => Async (CurlResponse_ ht bt) -> SomeException -> m () markAsErrored key result = do maybePrevious <- use $ rsClientMap . at key case maybePrevious of Just previous -> (rsClientMap . at key) ?= (previous & csStatus .~ Errored result) Nothing -> pure () waitForOne :: (Eq a, MonadIO m, MonadState (RaceState ht bt a) m) => m (Maybe (Async (CurlResponse_ ht bt), a)) waitForOne = do debug <- use rsDebug providerMap <- use rsClientMap let asyncs = _csOptions <$> onlyPending providerMap if null asyncs then pure Nothing else do winner <- liftIO $ waitAnyCatch (M.keys asyncs) case winner of (as, Right a) -> do handler <- use rsHandler check <- use rsChecker returnLast <- use rsReturnLast result <- liftIO $ handler a if check result then do markAsSuccessful as result cancelRemaining when debug . liftIO $ do TIO.putStr "[racer] Winner: " print (asyncThreadId as) pure $ Just (as, result) else do markAsFailure as result remaining <- M.keys . onlyPending <$> use rsClientMap if returnLast && null remaining then do when debug . liftIO $ do TIO.putStr "[racer] Reached last. Returning: " print (asyncThreadId as) pure $ Just (as, result) else waitForOne (as, Left ex) -> markAsErrored as ex >> waitForOne
etcinit/craze
src/Network/Craze/Internal.hs
bsd-3-clause
5,920
0
26
1,744
1,879
956
923
160
5
module Sprite.Target where import Graphics.Rendering.OpenGL import Sprite.Class import Sprite.Colors data Target = Target (Vector3 Float) instance Sprite Target where pos (Target v) = v draw (Target v) = do preservingMatrix $ do translate v scale 0.1 0.1 (0.1::Float) renderPrimitive Quads $ do materialAmbientAndDiffuse Front $= black vertex (Vertex3 ( 0.5) ( 0.5) 0 :: Vertex3 Float) vertex (Vertex3 (-0.5) ( 0.5) 0 :: Vertex3 Float) vertex (Vertex3 (-0.5) (-0.5) 0 :: Vertex3 Float) vertex (Vertex3 ( 0.5) (-0.5) 0 :: Vertex3 Float) update (Target v) = Target $ Vector3 x' y' z where Vector3 x y z = v x' = x + (sin (20*y))/100 y' = (y - 0.005)
flazz/tooHS
src/Sprite/Target.hs
bsd-3-clause
745
0
18
207
320
161
159
21
0
module Tubes.Bot where import Control.Concurrent (threadDelay, forkIO) import Control.Concurrent.STM (TVar, atomically, readTVar, writeTVar, modifyTVar) import Control.Monad (forever, void) import Tubes.Model type Bot = PlayerId -> Universe -> Maybe CompleteAction newLineBot :: Bot newLineBot _botId u = case map stationLocation (tubeStations (universeTube u)) of (to:from:_) | null (findSegments from to (universeTube u)) -> Just (StartNewLine from (Present to)) _ -> Nothing extendLineBot :: Bot extendLineBot _botId u = case concatMap tubeLineStations (tubeLines (universeTube u)) of (from:_) -> case map stationLocation (tubeStations (universeTube u)) of (to:_) | null (findSegments from to (universeTube u)) -> Just (ContinueLine 0 Backward from (Present to)) _ -> Nothing _ -> Nothing -- | Add a bot to the 'Universe'. spawnBot :: PlayerId -> Bot -> TVar Universe -> IO () spawnBot botId bot w = do atomically $ modifyTVar w (addPlayer botId) void $ forkIO $ forever $ do threadDelay sec atomically $ do u <- readTVar w case bot botId u of Just action -> writeTVar w (applyPlayerCompleteAction botId action u) Nothing -> return () where sec = 10^6 -- one second in milliseconds
fizruk/tubes
src/Tubes/Bot.hs
bsd-3-clause
1,286
0
18
280
472
236
236
30
3
module Compat where import GhcPlugins import DriverPhases ( Phase(..) , phaseInputExt, eqPhase, isHaskellSrcFilename ) import PipelineMonad ( PipelineOutput(..) ) import SysTools ( newTempName ) import qualified Binary as B import System.FilePath ----------------------------------------------------------------------- -- COPYPASTA ----------------------------------------------------------------------- -- copypasted from ghc/Main.hs -- TODO: put this in a library haskellish :: (String, Maybe Phase) -> Bool haskellish (f,Nothing) = looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f haskellish (_,Just phase) = phase `notElem` [ As True, As False, Cc, Cobjc, Cobjcxx, CmmCpp, Cmm , StopLn] -- getOutputFilename copypasted from DriverPipeline -- ToDo: uncopypaste -- Notice that StopLn output is always .o! Very useful. getOutputFilename :: Phase -> PipelineOutput -> String -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath getOutputFilename stop_phase output basename dflags next_phase maybe_location | is_last_phase, Persistent <- output = persistent_fn | is_last_phase, SpecificFile <- output = case outputFile dflags of Just f -> return f Nothing -> panic "SpecificFile: No filename" | keep_this_output = persistent_fn | otherwise = newTempName dflags suffix where hcsuf = hcSuf dflags odir = objectDir dflags osuf = objectSuf dflags keep_hc = gopt Opt_KeepHcFiles dflags keep_s = gopt Opt_KeepSFiles dflags keep_bc = gopt Opt_KeepLlvmFiles dflags myPhaseInputExt HCc = hcsuf myPhaseInputExt MergeStub = osuf myPhaseInputExt StopLn = osuf myPhaseInputExt other = phaseInputExt other is_last_phase = next_phase `eqPhase` stop_phase -- sometimes, we keep output from intermediate stages keep_this_output = case next_phase of As _ | keep_s -> True LlvmOpt | keep_bc -> True HCc | keep_hc -> True _other -> False suffix = myPhaseInputExt next_phase -- persistent object files get put in odir persistent_fn | StopLn <- next_phase = return odir_persistent | otherwise = return persistent persistent = basename <.> suffix odir_persistent | Just loc <- maybe_location = ml_obj_file loc | Just d <- odir = d </> persistent | otherwise = persistent -- Copypaste from Finder -- | Constructs the filename of a .o file for a given source file. -- Does /not/ check whether the .o file exists mkObjPath :: DynFlags -> FilePath -- the filename of the source file, minus the extension -> String -- the module name with dots replaced by slashes -> FilePath mkObjPath dflags basename mod_basename = obj_basename <.> osuf where odir = objectDir dflags osuf = objectSuf dflags obj_basename | Just dir <- odir = dir </> mod_basename | otherwise = basename -- | Constructs the filename of a .hi file for a given source file. -- Does /not/ check whether the .hi file exists mkHiPath :: DynFlags -> FilePath -- the filename of the source file, minus the extension -> String -- the module name with dots replaced by slashes -> FilePath mkHiPath dflags basename mod_basename = hi_basename <.> hisuf where hidir = hiDir dflags hisuf = hiSuf dflags hi_basename | Just dir <- hidir = dir </> mod_basename | otherwise = basename -- Copypasted from GhcMake home_imps :: [(Maybe FastString, Located ModuleName)] -> [Located ModuleName] home_imps imps = [ lmodname | (mb_pkg, lmodname) <- imps, isLocal mb_pkg ] where isLocal Nothing = True isLocal (Just pkg) | pkg == fsLit "this" = True -- "this" is special isLocal _ = False ms_home_srcimps :: ModSummary -> [Located ModuleName] ms_home_srcimps = home_imps . ms_srcimps ms_home_imps :: ModSummary -> [Located ModuleName] ms_home_imps = home_imps . ms_imps -- from MkIface putNameLiterally :: B.BinHandle -> Name -> IO () putNameLiterally bh name = do B.put_ bh $! nameModule name B.put_ bh $! nameOccName name
ezyang/ghc-shake
Compat.hs
bsd-3-clause
4,769
0
12
1,559
954
491
463
86
8
{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-| RouteT monad transformer for frontend routing convenience. -} module Reflex.Dom.Contrib.MonadRouted ( routeApp , MonadRouted(..) , askUri , askInitialSegments , uriPathParts , uriToPath , redirectInternal , redirectLocal , withPathSegment , withPathSegment' , dynPath , RouteT(..) , PathSegment , LocationInfo(..) , RoutingInfo (..) , mkLocationInfo ) where ------------------------------------------------------------------------------ import Control.Monad.Exception import Control.Monad.Reader import Control.Monad.Ref import Control.Monad.State.Strict import Data.Coerce import qualified Data.List as L import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding import GHCJS.DOM.Types (MonadJSM) import Reflex.Dom.Contrib.Router import Reflex.Dom.Core import Reflex.Host.Class import URI.ByteString ------------------------------------------------------------------------------- import Debug.Trace ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Type alias for portions of a path after splitting on '/' type PathSegment = Text ------------------------------------------------------------------------------ -- | The environment inside the RouteT monad transformer. data LocationInfo = LocationInfo { _locationUri :: URIRef Absolute -- ^ A complete parsed representation of the contents of the location bar -- is available at all times. , _locationPathSegments :: [PathSegment] -- ^ The path split on '/'. , _locationPathQuery :: [(T.Text, T.Text)] -- ^ Query params , _localPathContext :: [PathSegment] -- ^ Path segments in the current routing context (including static ones) , _locationStatic :: T.Text -- ^ Purely static path parts } deriving (Eq,Ord,Show) --makeLenses ''LocationInfo ------------------------------------------------------------------------------ -- | Constructs an app's top-level LocationInfo from URL text. mkLocationInfo :: T.Text -- ^ The path initial segments not used for dynamic routing -> URIRef Absolute -- ^ Full Url of target to route to -> LocationInfo mkLocationInfo ctx r = LocationInfo r routeSegs (uriQueryText r) ctxSegs ctx where ctxSegs = contextPathParts ctx -- TODO: What should happen if the route fails to prefix-match the -- static path segment? Throw at error? Here we just return [] for -- dynamic segments routeSegs = fromMaybe [] . L.stripPrefix (contextPathParts ctx) $ uriPathParts r uriQueryText = fmap (\(a, b) -> (decodeUtf8 a, decodeUtf8 b)) . queryPairs . uriQuery ------------------------------------------------------------------------------- -- Enter a route by one segment; one routing segment is popped and moved -- to the dynamic context dropSegment :: LocationInfo -> LocationInfo dropSegment li@(LocationInfo _ [] _ _ _) = li dropSegment (LocationInfo uri (x:xs) qps ctx st) = LocationInfo uri xs qps (ctx ++ [x]) st ------------------------------------------------------------------------------ -- | Top-level routing function. routeApp :: forall t m a.MonadWidget t m => T.Text -- ^ Static part of the path not used in dynamic routing -- Leading and trailing '/' will be added automatically -> RouteT t m a -> m a routeApp staticPath app = do rec rUri :: Dynamic t (URIRef Absolute) <- route (decodeUtf8 . serializeURIRef' <$> (switch . current $ getLMost <$> rc)) let locInfo = mkLocationInfo staticPath <$> rUri (a,rc) <- runRouteT app $ RoutingInfo locInfo staticPath return a data RoutingInfo t = RoutingInfo { _routingInfoLocation :: Dynamic t LocationInfo , _routingInfoStaticPath :: Text } ------------------------------------------------------------------------------ -- | Canonical implementation of the MonadRouted routing interface. newtype RouteT t m a = RouteT { unRouteT :: ReaderT (RoutingInfo t) (DynamicWriterT t (LMost t (URIRef Absolute)) m) a } deriving (Functor, Applicative, Monad, MonadFix, MonadHold t, MonadSample t, MonadAsyncException, MonadException, #ifdef __GHCJS__ MonadIO #else MonadJSM, MonadIO #endif ) deriving instance (Monad m, HasDocument m) => HasDocument (RouteT t m) deriving instance (Prerender js t m, Monad m, MonadFix m) => Prerender js t (RouteT t m) runRouteT :: MonadWidget t m => RouteT t m a -> RoutingInfo t -> m (a, Dynamic t (LMost t (URIRef Absolute))) runRouteT (RouteT m) ri = runDynamicWriterT $ runReaderT m ri instance MonadTrans (RouteT t) where lift = RouteT . lift . lift instance MonadReader r m => MonadReader r (RouteT t m) where ask = lift ask local f (RouteT a) = RouteT $ mapReaderT (local f) a instance MonadState s m => MonadState s (RouteT t m) where get = lift get put s = lift $ put s -- instance MonadDynamicWriter t w m => MonadDynamicWriter t w (RouteT t m) where -- tellDyn = lift . tellDyn instance DynamicWriter t w m => DynamicWriter t w (RouteT t m) where tellDyn = lift . tellDyn instance EventWriter t w m => EventWriter t w (RouteT t m) where tellEvent = lift . tellEvent instance HasJSContext m => HasJSContext (RouteT t m) where type JSContextPhantom (RouteT t m) = JSContextPhantom m askJSContext = lift askJSContext instance (MonadHold t m, MonadFix m, Adjustable t m) => Adjustable t (RouteT t m) where runWithReplace a0 a' = RouteT $ runWithReplace (coerce a0) (coerceEvent a') traverseIntMapWithKeyWithAdjust f dm0 dm' = RouteT $ traverseIntMapWithKeyWithAdjust (\k v -> unRouteT (f k v)) (coerce dm0) (coerceEvent dm') traverseDMapWithKeyWithAdjust f dm0 dm' = RouteT $ traverseDMapWithKeyWithAdjust (\k v -> unRouteT (f k v)) (coerce dm0) (coerceEvent dm') traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = RouteT $ traverseDMapWithKeyWithAdjustWithMove (\k v -> unRouteT (f k v)) (coerce dm0) (coerceEvent dm') instance MonadRef m => MonadRef (RouteT t m) where type Ref (RouteT t m) = Ref m newRef = lift . newRef readRef = lift . readRef writeRef r = lift . writeRef r instance MonadAtomicRef m => MonadAtomicRef (RouteT t m) where atomicModifyRef r = lift . atomicModifyRef r instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (RouteT t m) where newEventWithTrigger = lift . newEventWithTrigger newFanEventWithTrigger f = lift $ newFanEventWithTrigger f instance PerformEvent t m => PerformEvent t (RouteT t m) where type Performable (RouteT t m) = Performable m performEvent_ = lift . performEvent_ performEvent = lift . performEvent deriving instance TriggerEvent t m => TriggerEvent t (RouteT t m) instance PostBuild t m => PostBuild t (RouteT t m) where getPostBuild = lift getPostBuild ------------------------------------------------------------------------------ -- | Minimal functionality necessary for the core routing interface that gives -- you access to the contents of the location bar, lets you set its value, and -- provides a mechanism for traversing the path in a hierarchical fashion. class MonadRouted t m | m -> t where askRI :: m (RoutingInfo t) localRI :: (RoutingInfo t -> RoutingInfo t) -> m a -> m a tellUri :: Dynamic t (LMost t (URIRef Absolute)) -> m () instance MonadWidget t m => MonadRouted t (RouteT t m) where askRI = RouteT ask localRI f (RouteT m) = RouteT $ local f m tellUri = RouteT . tellDyn instance (MonadRouted t m, Monad m) => MonadRouted t (EventWriterT t w m) where askRI = lift askRI localRI f (EventWriterT a) = EventWriterT $ mapStateT (localRI f) a tellUri = lift . tellUri instance NotReady t m => NotReady t (RouteT r m) where notReadyUntil = lift . notReadyUntil notReady = lift notReady -- | Returns the full parsed URI. askUri :: (Monad m, Reflex t, MonadRouted t m) => m (Dynamic t (URIRef Absolute)) askUri = do locInfo <- _routingInfoLocation <$> askRI return $ _locationUri <$> locInfo -- | Path segments of original url askInitialSegments :: (Monad m, MonadJSM m, HasJSContext m, MonadRouted t m) => m [PathSegment] askInitialSegments = do staticPath <- _routingInfoStaticPath <$> askRI uri0 <- getURI return $ _locationPathSegments $ mkLocationInfo staticPath uri0 -- | Changes the location bar to the value specified in the first parameter. withPathSegment :: (Monad m, Reflex t, MonadRouted t m, MonadFix m, MonadHold t m) => (Dynamic t ([PathSegment], [(T.Text, T.Text)]) -> m a) -> m a withPathSegment f = do locInfo <- _routingInfoLocation <$> askRI top <- holdUniqDyn $ (\x -> (_locationPathSegments $ x, _locationPathQuery x)) <$> locInfo localRI (\ri -> ri { _routingInfoLocation = dropSegment <$> _routingInfoLocation ri }) (f top) where headMay [] = Nothing headMay (x:_) = Just x withPathSegment' :: (Monad m, Reflex t, MonadRouted t m, MonadFix m, MonadHold t m) => (Dynamic t (Maybe PathSegment, [(T.Text, T.Text)]) -> m a) -> m a withPathSegment' f = do locInfo <- _routingInfoLocation <$> askRI top <- holdUniqDyn $ (\x -> (headMay . _locationPathSegments $ x, _locationPathQuery x)) <$> locInfo localRI (\ri -> ri { _routingInfoLocation = dropSegment <$> _routingInfoLocation ri }) (f top) where headMay [] = Nothing headMay (x:_) = Just x -- | The latest full path as a text value. dynPath :: (Monad m, Reflex t, MonadRouted t m, MonadFix m, MonadHold t m) => m (Dynamic t T.Text) dynPath = do duri <- askUri holdUniqDyn $ uriToPath <$> duri -- | Change the location bar by appending the specifid value to the dynamic path -- context redirectInternal :: (Monad m, Reflex t, MonadRouted t m) => Event t Text -> m () redirectInternal pathPart = do locInfo <- _routingInfoLocation <$> askRI let reqs = attachWith constructReq (current locInfo) pathPart tellUri $ constDyn $ LMost reqs -- | Passes the first path segment to the supplied widget and pops it off -- the locationPathSegments field of the 'LocationInfo' that the widget -- sees. redirectLocal :: (Monad m, Reflex t, MonadRouted t m) => Event t Text -> m () redirectLocal pathPart = do locInfo <- _routingInfoLocation <$> askRI let reqs = attachWith appendingReq (current locInfo) pathPart tellUri $ constDyn $ LMost reqs ------------------------------------------------------------------------------- -- Build a URI from an "absolute" link (those issued by redirectInternal) -- Prepend just the static path parts -- If the redirect path contains query or fragment parts, overwrite those -- from the original load-time URI. Otherwise, keep those load-time parts -- (New query params & fragments will not be saved between redirects, -- they must be specified on every redirect event occurrence) constructReq :: LocationInfo -> Text -> URIRef Absolute constructReq (LocationInfo u _ qps _ st) p = let fullPath = "/" <> cleanT (st <> "/" <> cleanT p) -- Stringify (the original uri - query/frag) + (redirect) -- and reparse, to search for new query/frag fullUriString = serializeURIRef' u { uriQuery = Query [], uriFragment = Nothing } <> encodeUtf8 fullPath -- Re-parse the URI to check for new query/frag -- Disregard on parse error - parse error should only happen -- in response to a malformed redirect request fullUri' = either (\_ -> trace ("URI Parse error for: " ++ show fullUriString) u) id (parseURI laxURIParserOptions fullUriString) -- query' = if uriQuery fullUri' == Query [] -- then uriQuery u -- else uriQuery fullUri' query' = uriQuery fullUri' frag' = if uriFragment fullUri' `elem` [Nothing, Just ""] then uriFragment u else uriFragment fullUri' in u { uriPath = encodeUtf8 (T.takeWhile (/= '?') fullPath) , uriQuery = query' , uriFragment = frag' } ------------------------------------------------------------------------------- -- Build a URI from a link relative to the context -- Prepend the static and context path parts appendingReq :: LocationInfo -> Text -> URIRef Absolute appendingReq (LocationInfo u _ _ ctx _) p = let fullPath = "/" <> cleanT (partsToPath ctx <> "/" <> cleanT p) in u { uriPath = encodeUtf8 fullPath } instance (MonadHold t m, MonadFix m, DomBuilder t m, NotReady t (RouteT t m)) => DomBuilder t (RouteT t m) where type DomBuilderSpace (RouteT t m) = DomBuilderSpace m element t cfg (RouteT child) = RouteT $ ReaderT $ \r -> DynamicWriterT $ do s <- get (e, (a, newS)) <- lift $ element t cfg $ runStateT (unDynamicWriterT (runReaderT child r)) s put newS return (e, a) inputElement = lift . inputElement textAreaElement = lift . textAreaElement selectElement cfg (RouteT child) = RouteT $ ReaderT $ \r -> DynamicWriterT $ do s <- get (e, (a, newS)) <- lift $ selectElement cfg $ runStateT (unDynamicWriterT (runReaderT child r)) s put newS return (e, a) ------------------------------------------------------------------------------- -- Utility wrapper to collect route events with 'leftmost' newtype LMost t a = LMost { getLMost :: Event t a} instance Reflex t => Monoid (LMost t a) where mempty = LMost never instance Reflex t => Semigroup (LMost t a) where LMost a <> LMost b = LMost (leftmost [a,b]) ------------------------------------------------------------------------------- -- Utility functions partsToPath :: [PathSegment] -> T.Text partsToPath = T.intercalate "/" uriPathParts :: URIRef Absolute -> [PathSegment] uriPathParts = pathParts . decodeUtf8 . uriPath uriToPath :: URIRef Absolute -> T.Text uriToPath = partsToPath . uriPathParts pathParts :: T.Text -> [PathSegment] pathParts = T.splitOn "/" . cleanT contextPathParts :: T.Text -> [PathSegment] contextPathParts = splitOn' "/" . cleanT splitOn' :: Text -> Text -> [Text] splitOn' _ "" = [] -- instead of [""] as returned by T.splitOn splitOn' s x = T.splitOn s x cleanT :: T.Text -> T.Text cleanT = T.dropWhile (== '/')
byteally/webapi
webapi-reflex-dom/src/Reflex/Dom/Contrib/MonadRouted.hs
bsd-3-clause
15,233
0
17
3,431
3,890
2,043
1,847
264
2
module GhcNameVersion ( GhcNameVersion (..) ) where import GhcPrelude -- | Settings for what GHC this is. data GhcNameVersion = GhcNameVersion { ghcNameVersion_programName :: String , ghcNameVersion_projectVersion :: String }
sdiehl/ghc
compiler/main/GhcNameVersion.hs
bsd-3-clause
241
0
8
45
38
25
13
6
0
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ConstraintKinds #-} module RPG.Core ( Tag (..) , hasCollision , isFloor , propKey , box , interaction , Has , Eff , Prop , ask , def , lift , liftIO , module Control.Lens , module Control.Monad , module Data.Some , module Game.Sequoia , Key (..) , PropId (..) ) where import Control.Eff import Control.Eff.Lift import Control.Eff.Reader.Lazy import Control.Monad import Control.Monad.IO.Class (liftIO) import Control.Lens import Data.Default import Data.IORef (IORef (..), readIORef, writeIORef) import Data.Some hiding (Event (..), never) import Game.Sequoia import Game.Sequoia.Keyboard type Prop = Prop' Tag type Has t r = Member (Reader t) r newtype PropId = PropId Int deriving (Eq, Show, Ord) data Tag = Tag { _hasCollision :: Bool , _isFloor :: Bool , _propKey :: Maybe PropId , _box :: Maybe ((Prop -> Prop) -> IO ()) , _interaction :: Maybe (Now ()) } $(makeLenses ''Tag) instance Show Tag where show Tag{..} = concat [ "Tag " , show _hasCollision , show _isFloor , show _propKey ] instance Default Tag where def = Tag False False Nothing Nothing Nothing
isovector/rpg-gen
src/RPG/Core.hs
bsd-3-clause
1,419
0
13
430
395
236
159
52
0
module Main where import System.Environment (getArgs) main :: IO () main = do args <- getArgs let width = if (length args == 0) then 80 else (read $ args !! 0) let dataSource = if (length args <= 1) then getContents else readFile (args !! 1) map (take width) . lines <$> dataSource >>= mapM_ putStrLn
ahgilbert/trunc
src/Main.hs
bsd-3-clause
312
2
9
68
131
71
60
8
3
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.EXT.TextureInteger -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/EXT/texture_integer.txt EXT_texture_integer> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.EXT.TextureInteger ( -- * Enums gl_ALPHA16I_EXT, gl_ALPHA16UI_EXT, gl_ALPHA32I_EXT, gl_ALPHA32UI_EXT, gl_ALPHA8I_EXT, gl_ALPHA8UI_EXT, gl_ALPHA_INTEGER_EXT, gl_BGRA_INTEGER_EXT, gl_BGR_INTEGER_EXT, gl_BLUE_INTEGER_EXT, gl_GREEN_INTEGER_EXT, gl_INTENSITY16I_EXT, gl_INTENSITY16UI_EXT, gl_INTENSITY32I_EXT, gl_INTENSITY32UI_EXT, gl_INTENSITY8I_EXT, gl_INTENSITY8UI_EXT, gl_LUMINANCE16I_EXT, gl_LUMINANCE16UI_EXT, gl_LUMINANCE32I_EXT, gl_LUMINANCE32UI_EXT, gl_LUMINANCE8I_EXT, gl_LUMINANCE8UI_EXT, gl_LUMINANCE_ALPHA16I_EXT, gl_LUMINANCE_ALPHA16UI_EXT, gl_LUMINANCE_ALPHA32I_EXT, gl_LUMINANCE_ALPHA32UI_EXT, gl_LUMINANCE_ALPHA8I_EXT, gl_LUMINANCE_ALPHA8UI_EXT, gl_LUMINANCE_ALPHA_INTEGER_EXT, gl_LUMINANCE_INTEGER_EXT, gl_RED_INTEGER_EXT, gl_RGB16I_EXT, gl_RGB16UI_EXT, gl_RGB32I_EXT, gl_RGB32UI_EXT, gl_RGB8I_EXT, gl_RGB8UI_EXT, gl_RGBA16I_EXT, gl_RGBA16UI_EXT, gl_RGBA32I_EXT, gl_RGBA32UI_EXT, gl_RGBA8I_EXT, gl_RGBA8UI_EXT, gl_RGBA_INTEGER_EXT, gl_RGBA_INTEGER_MODE_EXT, gl_RGB_INTEGER_EXT, -- * Functions glClearColorIiEXT, glClearColorIuiEXT, glGetTexParameterIivEXT, glGetTexParameterIuivEXT, glTexParameterIivEXT, glTexParameterIuivEXT ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/EXT/TextureInteger.hs
bsd-3-clause
1,897
0
4
241
202
142
60
56
0
module Utils.CmdArgParser (Arguments (..), Arg (..), getArguments) where -- this module defines a command line -- argument parser import Control.Applicative hiding (many) import Control.Monad.Identity import Data.List import System.Environment (getArgs) import System.Posix.Files (fileExist) import Text.Parsec import qualified Text.Parsec.Token as P import Text.Parsec.Language (emptyDef) -- simple data type for representing arguments data Arguments = Arguments [Arg] FilePath deriving (Eq, Ord) -- Arguments for controling the behavior of the -- algorithm data Arg = KindInfo -- represented by --k | ClassInfo -- represented by --c | InstInfo -- represented by --i | AssumpInfo -- represented by --a | Recomp -- represented by --r | Make -- enable multi module compilation | Help -- shows help message deriving (Eq, Ord, Enum) -- sample show instance for arguments instance Show Arg where show KindInfo = "--k" show ClassInfo = "--c" show InstInfo = "--i" show AssumpInfo = "--a" show Recomp = "--r" show Make = "--make" show Help = "--h" type Parser a = ParsecT String () Identity a -- getting parameters getArguments :: IO (Either String Arguments) getArguments = do args <- getArgs let r = splitArgs args analysis r analysis :: (Maybe [String], Maybe String) -> IO (Either String Arguments) analysis (Nothing, Nothing) = return (Left "No input arguments.\nUsage: for information try --h option.") analysis (Just x, Nothing) = if "--h" `elem` x then return (Left helpMessage) else return (Left "Incorrect usage. For more information try --h option.") analysis (Nothing, Just f) = do b <- fileExist f if b then return (Right (Arguments [] f)) else return (Left (concat ["The file:\n", f, "\ndoesn't exist."])) analysis (Just as, Just f) = finish as f finish :: [String] -> String -> IO (Either String Arguments) finish ss s = do let ps = concat ss args = parser ps either (return . Left) (complete s) args complete :: String -> [Arg] -> IO (Either String Arguments) complete s args = do b <- fileExist s if b then return (Right (Arguments args s)) else return (Left (concat ["The file:\n", s, "\ndoesn't exist."])) parser :: String -> Either String [Arg] parser s = case parse pargs "" s of Left _ -> Left "Incorrect usage. For more information try --h option." Right as -> Right as -- parses very simple arguments pargs :: Parser [Arg] pargs = many (arg ps) where ps = map (\i -> (show i, i)) [KindInfo ..] arg = choice . map f f (s,k) = const k <$> try (symbol s) -- lexer definition lexer = P.makeTokenParser emptyDef symbol = P.symbol lexer -- some auxiliar functions splitArgs :: [String] -> (Maybe [String], Maybe String) splitArgs ss = case partition (\s -> (take 2 s) == "--") ss of ([],[x]) -> (Nothing, Just x) (ps,[x]) -> (Just ps, Just x) (ps,[]) -> (Just ps, Nothing) _ -> (Nothing, Nothing) helpMessage :: String helpMessage = "Usage:\nmain [options] file\n\n" ++ "Options:\n--k: Show infered kinds\n"++ "--c: Show infered class constraints\n" ++ "--i: Show infered instance constraints\n" ++ "--a: Show infered types (include data constructors)\n" ++ "--r: Turn off recompilation checker\n" ++ "--make : Enable multi-module processing\n" ++ "--h: Show this message\n"
rodrigogribeiro/mptc
src/Utils/CmdArgParser.hs
bsd-3-clause
3,993
0
13
1,323
1,065
572
493
90
4
-- | Bit-shift style argument re-arrangement module Data.Function.Slip where slipr :: (a -> b -> c -> d) -> b -> c -> a -> d slipr f b c a = f a b c (<~>>) = slipr infixl 8 <~>> slipl :: (a -> b -> c -> d) -> c -> a -> b -> d slipl f c a b = f a b c (<<~>) = slipl infixl 8 <<~> slipr4 :: (a -> b -> c -> d -> e) -> b -> c -> d -> a -> e slipr4 f b c d a = f a b c d (<~~>>) = slipr4 infixl 8 <~~>> slipl4 :: (a -> b -> c -> d -> e) -> d -> a -> b -> c -> e slipl4 f d a b c = f a b c d (<<~~>) = slipl4 infixl 8 <<~~> slipr5 :: (a -> b -> c -> d -> e -> f) -> b -> c -> d -> e -> a -> f slipr5 f b c d e a = f a b c d e (<~~~>>) = slipr5 infixl 8 <~~~>> slipl5 :: (a -> b -> c -> d -> e -> f) -> e -> a -> b -> c -> d -> f slipl5 f e a b c d = f a b c d e (<<~~~>) = slipl5 infixl 8 <<~~~>
athanclark/composition-extra
src/Data/Function/Slip.hs
bsd-3-clause
818
0
11
270
494
264
230
25
1
-- TODO repl test file path methods. {-# LANGUAGE OverloadedStrings #-} module Pipe.FileSystem where import Control.Monad import Control.Monad.M import qualified Data.List as L import Data.String.Util import qualified Data.Text as T import Database.SQLite.Simple import System.FilePath import PackageConf import Pipes import System.Directory ( doesDirectoryExist, getDirectoryContents ) import qualified System.Directory as D import Text.HTML.TagSoup import Text.HTML.TagSoup.Match import Haddock.Artifact import Haddock.Sqlite import qualified Module as Ghc -- TODO the utility of some of these fields is still unclear to me, -- at the moment they are filled simply to satisfy the docset spec. plist :: String -> String plist str = unlines $ [ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" , "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">" , "<plist version=\"1.0\">" , "<dict>" , "<key>CFBundleIdentifier</key>" , "<string>" ++ str ++ "</string>" , "<key>CFBundleName</key>" , "<string>docset for Haskell package " ++ str ++ "</string>" , "<key>DocSetPlatformFamily</key>" , "<string>haskell</string>" , "<key>isDashDocset</key>" , "<true/>" , "<key>dashIndexFilePath</key>" , "<string>index.html</string>" , "</dict>" , "</plist>" ] docsetDir :: Ghc.PackageKey -> FilePath docsetDir k = Ghc.packageKeyString k ++ ".docset" leafs :: (FilePath -> Bool) -> FilePath -> ProducerM FilePath () leafs incPred p = do names <- liftIO $ getDirectoryContents p forM_ (filter (`notElem` [".", ".."]) names) $ \name' -> do let path = p </> name' dir <- liftIO . doesDirectoryExist $ path (if dir then leafs incPred else if not . incPred $ path then const (return ()) else yield) path type Tag' = Tag T.Text remoteUrl :: T.Text -> Bool remoteUrl url = any (T.isPrefixOf url) ["http://", "https://"] -- toStripped :: FilePath -> FilePath -> Either String FilePath -- toStripped pfx original = common :: FilePath -> FilePath -> FilePath common l r = fst . unzip . takeWhile (uncurry (==)) $ zip (normalise l) (normalise r) parent :: FilePath -> FilePath parent = takeDirectory stripPrefix :: FilePath -> FilePath -> Either String FilePath stripPrefix prefix path = if L.isPrefixOf prefix path then Right $ L.drop (L.length prefix + 1) path else Left $ "prefix: " ++ prefix ++ " doesn't agree with:\n " ++ path toRelativePath :: FilePath -> FilePath -> Either String FilePath toRelativePath base path = do let sharedPfx = common base path relative <- relativePath sharedPfx (</>) relative <$> stripPrefix sharedPfx path where relativePath :: FilePath -> Either String FilePath relativePath pfx = joinPath . flip replicate ".." . length . splitPath <$> stripPrefix pfx base relativize :: Ghc.PackageKey -> FilePath -> Either String T.Text relativize package p = let filename' = takeFileName p packageSubpath = Ghc.packageKeyString package matches = filter (packageSubpath ==) . reverse $ splitPath (parent p) in T.pack <$> if L.null matches then return p -- preserve the path so that it still can be used else -- assume as a package doc file and make relative toRelativePath packageSubpath $ L.head matches </> filename' convertUrl :: Ghc.PackageKey -> T.Text -> Either String T.Text convertUrl p urlExp | T.null urlExp = Right T.empty | otherwise = if T.isPrefixOf "file:///" urlExp then relativize p (T.unpack . T.drop 7 $ urlExp) else if T.isPrefixOf "/" urlExp then relativize p $ T.unpack urlExp else Right urlExp attributes :: FilePath -> Tag T.Text -> Either String [Attribute T.Text] attributes _ (TagOpen _ list) = Right list attributes src other = Left $ "failed to retrieve expected attributes from tag:\n " ++ show other ++ "\n in: \n" ++ src -- | Convert local package-compiled haddock links to local relative. convertLink :: Ghc.PackageKey -> FilePath -> Tag' -> Either String Tag' convertLink package src tag = -- We're only interested in processing links if not $ tagOpenLit "a" (anyAttrNameLit "href") tag then Right tag else do preserved <- filter (\(n,_) -> n /= "href") <$> attributes src tag let url = fromAttrib "href" tag if remoteUrl url then Right tag -- ignore remote links else do url' <- convertUrl package url Right . TagOpen "a" $ ("href", url') : preserved pipe_htmlConvert :: Ghc.PackageKey -> PipeM FilePath (FilePath, Maybe String) () pipe_htmlConvert p = forever $ do src <- await if Just (takeExtension src) /= Just "html" then yield (src, Nothing) else do buf <- liftIO . readFile $ src -- Link conversion errors are non-fatal. case mapM (convertLink p src) . parseTags $ T.pack buf of Left e -> do lift . warning $ preposition "failed to convert links" "for" "file" src [e] yield (src, Nothing) Right tags -> yield (src, Just . T.unpack . renderTags $ tags) -- | This consumes a doc file and copies it to a path in 'dstRoot'. -- By pre-condition: -- path has src_root as an ancestor -- By post-condition: -- written dst is the difference of path and src_root, -- with by the concatenation of dst_root as it's parent. cons_writeFile :: FilePath -> FilePath -> ConsumerM (FilePath, Maybe String) () cons_writeFile src_root dst_root = forever $ do (path, buf) <- await dst_relative_path <- lift . fromE $ stripPrefix src_root path -- liftIO . putStrLn $ "src_root: " ++ show src_root -- liftIO . putStrLn $ "relative path: " ++ show dst_relative_path -- liftIO . putStrLn $ "path: " ++ show path liftIO $ do let dst_path = dst_root </> dst_relative_path --liftIO . putStrLn $ "dst path: " ++ dst_path -- create requisite parent directories for the file at the destination D.createDirectoryIfMissing True $ parent dst_path case buf of Nothing -> D.copyFile path dst_path Just buf' -> writeFile dst_path buf' cons_writeFiles :: FilePath -> ConsumerM PackageConf () cons_writeFiles docsets_root = forever $ do conf <- await lift . msg $ "processing: " ++ (Ghc.packageKeyString . pkg $ conf) let docset_folder = docsetDir (pkg conf) dst_root = docsets_root </> docset_folder dst_doc_root = dst_root </> "Contents/Resources/Documents/" liftIO . D.createDirectoryIfMissing True $ dst_doc_root -- Copy all files and convert if necessary lift . indentM 2 $ msg "writing files.." lift . runEffect $ cons_writeFile (htmlDir conf) dst_doc_root <-< pipe_htmlConvert (pkg conf) <-< leafs (\p -> Just (takeExtension p) /= Just "haddock") (htmlDir conf) -- TODO Since the haddock index is already produced in source docs -- with latest packaging systems, this is likely unnecessary -- liftIO $ do -- putStrLn "running haddock indexes" -- runHaddockIndex (interfaceFile conf) dst_doc_root lift . indentM 2 $ msg "writing plist.." liftIO . writeFile (dst_root </> "Contents/Info.plist") . plist . Ghc.packageKeyString . pkg $ conf let db_path = dst_root </> "Contents/Resources/docSet.dsidx" liftIO $ do db_exists <- D.doesFileExist db_path when db_exists $ D.removeFile db_path -- Initialize the SQlite Db c' <- liftIO $ do c <- open db_path createTable c return c lift . indentM 2 $ msg "populating database.." -- Populate the SQlite Db liftIO $ execute_ c' "BEGIN;" artifacts <- lift $ toArtifacts (pkg conf) (interfaceFile conf) lift $ mapM_ (fromArtifact (pkg conf) c') artifacts liftIO $ execute_ c' "COMMIT;" liftIO . close $ c' lift . indentM 2 $ msg "finished populating sqlite database.." lift $ msg "\n"
jfeltz/dash-haskell
src/Pipe/FileSystem.hs
lgpl-3.0
8,182
3
22
2,032
2,067
1,036
1,031
167
3
module Lang.LamIf.Syntax where import FP newtype RawName = RawName { getRawName :: String } deriving (Eq, Ord) type SRawName = Stamped BdrNum RawName data GenName = GenName { genNameMark :: Maybe Int , genNameRawName :: RawName } deriving (Eq, Ord) newtype LocNum = LocNum Int deriving (Eq, Ord, PartialOrder, Peano) newtype BdrNum = BdrNum Int deriving (Eq, Ord, PartialOrder, Peano) type Name = Stamped BdrNum GenName srawNameToName :: SRawName -> Name srawNameToName (Stamped i x) = Stamped i $ GenName Nothing x data Lit = I Int | B Bool deriving (Eq, Ord) instance PartialOrder Lit where pcompare = discreteOrder makePrisms ''Lit data BinOp = Add | Sub | GTE deriving (Eq, Ord) instance PartialOrder BinOp where pcompare = discreteOrder data LBinOp = LBinOp { lbinOpOp :: BinOp , lbinOpLevel :: Int } deriving (Eq, Ord) data PreExp n e = Lit Lit | Var n | Lam n e | Prim LBinOp e e | Let n e e | App e e | If e e e | Tup e e | Pi1 e | Pi2 e deriving (Eq, Ord) type RawExp = Fix (PreExp RawName) type Exp = StampedFix LocNum (PreExp SRawName)
FranklinChen/maam
src/Lang/LamIf/Syntax.hs
bsd-3-clause
1,098
0
9
246
414
232
182
-1
-1
{-# OPTIONS_GHC -cpp #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Configure -- Copyright : Isaac Jones 2003-2005 -- -- Maintainer : Isaac Jones <ijones@syntaxpolice.org> -- Stability : alpha -- Portability : portable -- -- Explanation: Perform the \"@.\/setup configure@\" action. -- Outputs the @.setup-config@ file. {- All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Isaac Jones nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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 Distribution.Simple.Configure (writePersistBuildConfig, getPersistBuildConfig, maybeGetPersistBuildConfig, configure, localBuildInfoFile, findProgram, getInstalledPackages, configDependency, configCompiler, configCompilerAux, #ifdef DEBUG hunitTests #endif ) where #if __GLASGOW_HASKELL__ && __GLASGOW_HASKELL__ < 604 #if __GLASGOW_HASKELL__ < 603 #include "config.h" #else #include "ghcconfig.h" #endif #endif import Distribution.Simple.LocalBuildInfo import Distribution.Simple.Register (removeInstalledConfig) import Distribution.Setup(ConfigFlags(..), CopyDest(..)) import Distribution.Compiler(CompilerFlavor(..), Compiler(..), compilerBinaryName, extensionsToFlags) import Distribution.Package (PackageIdentifier(..), showPackageId, parsePackageId) import Distribution.PackageDescription( PackageDescription(..), Library(..), BuildInfo(..), Executable(..), setupMessage ) import Distribution.Simple.Utils (die, warn, withTempFile,maybeExit) import Distribution.Version (Version(..), Dependency(..), VersionRange(ThisVersion), parseVersion, showVersion, withinRange, showVersionRange) import Data.List (intersperse, nub, maximumBy, isPrefixOf) import Data.Char (isSpace) import Data.Maybe(fromMaybe) import System.Directory import Distribution.Compat.FilePath (splitFileName, joinFileName, joinFileExt, exeExtension) import Distribution.Program(Program(..), ProgramLocation(..), lookupPrograms, updateProgram) import System.Cmd ( system ) import System.Exit ( ExitCode(..) ) import Control.Monad ( when, unless ) import Distribution.Compat.ReadP import Distribution.Compat.Directory (findExecutable) import Data.Char (isDigit) import Prelude hiding (catch) #ifdef mingw32_HOST_OS import Distribution.PackageDescription (hasLibs) #endif #ifdef DEBUG import HUnit #endif tryGetPersistBuildConfig :: IO (Either String LocalBuildInfo) tryGetPersistBuildConfig = do e <- doesFileExist localBuildInfoFile let dieMsg = "error reading " ++ localBuildInfoFile ++ "; run \"setup configure\" command?\n" if (not e) then return $ Left dieMsg else do str <- readFile localBuildInfoFile case reads str of [(bi,_)] -> return $ Right bi _ -> return $ Left dieMsg getPersistBuildConfig :: IO LocalBuildInfo getPersistBuildConfig = do lbi <- tryGetPersistBuildConfig either die return lbi maybeGetPersistBuildConfig :: IO (Maybe LocalBuildInfo) maybeGetPersistBuildConfig = do lbi <- tryGetPersistBuildConfig return $ either (const Nothing) Just lbi writePersistBuildConfig :: LocalBuildInfo -> IO () writePersistBuildConfig lbi = do writeFile localBuildInfoFile (show lbi) localBuildInfoFile :: FilePath localBuildInfoFile = "./.setup-config" -- ----------------------------------------------------------------------------- -- * Configuration -- ----------------------------------------------------------------------------- configure :: PackageDescription -> ConfigFlags -> IO LocalBuildInfo configure pkg_descr cfg = do setupMessage "Configuring" pkg_descr removeInstalledConfig let lib = library pkg_descr -- detect compiler comp@(Compiler f' ver p' pkg) <- configCompilerAux cfg -- installation directories defPrefix <- default_prefix defDataDir <- default_datadir pkg_descr let pref = fromMaybe defPrefix (configPrefix cfg) my_bindir = fromMaybe default_bindir (configBinDir cfg) my_libdir = fromMaybe (default_libdir comp) (configLibDir cfg) my_libsubdir = fromMaybe (default_libsubdir comp) (configLibSubDir cfg) my_libexecdir = fromMaybe default_libexecdir (configLibExecDir cfg) my_datadir = fromMaybe defDataDir (configDataDir cfg) my_datasubdir = fromMaybe default_datasubdir (configDataSubDir cfg) -- check extensions let extlist = nub $ maybe [] (extensions . libBuildInfo) lib ++ concat [ extensions exeBi | Executable _ _ exeBi <- executables pkg_descr ] let exts = fst $ extensionsToFlags f' extlist unless (null exts) $ warn $ -- Just warn, FIXME: Should this be an error? show f' ++ " does not support the following extensions:\n " ++ concat (intersperse ", " (map show exts)) foundPrograms <- lookupPrograms (configPrograms cfg) happy <- findProgram "happy" (configHappy cfg) alex <- findProgram "alex" (configAlex cfg) hsc2hs <- findProgram "hsc2hs" (configHsc2hs cfg) c2hs <- findProgram "c2hs" (configC2hs cfg) cpphs <- findProgram "cpphs" (configCpphs cfg) greencard <- findProgram "greencard" (configGreencard cfg) let newConfig = foldr (\(_, p) c -> updateProgram p c) (configPrograms cfg) foundPrograms -- FIXME: currently only GHC has hc-pkg dep_pkgs <- case f' of GHC | ver >= Version [6,3] [] -> do ipkgs <- getInstalledPackagesAux comp cfg mapM (configDependency ipkgs) (buildDepends pkg_descr) JHC -> do ipkgs <- getInstalledPackagesJHC comp cfg mapM (configDependency ipkgs) (buildDepends pkg_descr) _ -> do return $ map setDepByVersion (buildDepends pkg_descr) split_objs <- if not (configSplitObjs cfg) then return False else case f' of GHC | ver >= Version [6,5] [] -> return True _ -> do warn ("this compiler does not support " ++ "--enable-split-objs; ignoring") return False let lbi = LocalBuildInfo{prefix=pref, compiler=comp, buildDir="dist" `joinFileName` "build", bindir=my_bindir, libdir=my_libdir, libsubdir=my_libsubdir, libexecdir=my_libexecdir, datadir=my_datadir, datasubdir=my_datasubdir, packageDeps=dep_pkgs, withPrograms=newConfig, withHappy=happy, withAlex=alex, withHsc2hs=hsc2hs, withC2hs=c2hs, withCpphs=cpphs, withGreencard=greencard, withVanillaLib=configVanillaLib cfg, withProfLib=configProfLib cfg, withProfExe=configProfExe cfg, withGHCiLib=configGHCiLib cfg, splitObjs=split_objs, userConf=configUser cfg } -- FIXME: maybe this should only be printed when verbose? message $ "Using install prefix: " ++ pref messageDir pkg_descr lbi "Binaries" mkBinDir mkBinDirRel messageDir pkg_descr lbi "Libraries" mkLibDir mkLibDirRel messageDir pkg_descr lbi "Private binaries" mkLibexecDir mkLibexecDirRel messageDir pkg_descr lbi "Data files" mkDataDir mkDataDirRel message $ "Using compiler: " ++ p' message $ "Compiler flavor: " ++ (show f') message $ "Compiler version: " ++ showVersion ver message $ "Using package tool: " ++ pkg mapM (\(s,p) -> reportProgram' s p) foundPrograms reportProgram "happy" happy reportProgram "alex" alex reportProgram "hsc2hs" hsc2hs reportProgram "c2hs" c2hs reportProgram "cpphs" cpphs reportProgram "greencard" greencard return lbi messageDir :: PackageDescription -> LocalBuildInfo -> String -> (PackageDescription -> LocalBuildInfo -> CopyDest -> FilePath) -> (PackageDescription -> LocalBuildInfo -> CopyDest -> Maybe FilePath) -> IO () messageDir pkg_descr lbi name mkDir mkDirRel = message (name ++ " installed in: " ++ mkDir pkg_descr lbi NoCopyDest ++ rel_note) where #if mingw32_HOST_OS rel_note | not (hasLibs pkg_descr) && mkDirRel pkg_descr lbi NoCopyDest == Nothing = " (fixed location)" | otherwise = "" #else rel_note = "" #endif -- |Converts build dependencies to a versioned dependency. only sets -- version information for exact versioned dependencies. setDepByVersion :: Dependency -> PackageIdentifier -- if they specify the exact version, use that: setDepByVersion (Dependency s (ThisVersion v)) = PackageIdentifier s v -- otherwise, just set it to empty setDepByVersion (Dependency s _) = PackageIdentifier s (Version [] []) -- |Return the explicit path if given, otherwise look for the program -- name in the path. findProgram :: String -- ^ program name -> Maybe FilePath -- ^ optional explicit path -> IO (Maybe FilePath) findProgram name Nothing = findExecutable name findProgram _ p = return p reportProgram :: String -> Maybe FilePath -> IO () reportProgram name Nothing = message ("No " ++ name ++ " found") reportProgram name (Just p) = message ("Using " ++ name ++ ": " ++ p) reportProgram' :: String -> Maybe Program -> IO () reportProgram' _ (Just Program{ programName=name , programLocation=EmptyLocation}) = message ("No " ++ name ++ " found") reportProgram' _ (Just Program{ programName=name , programLocation=FoundOnSystem p}) = message ("Using " ++ name ++ " found on system at: " ++ p) reportProgram' _ (Just Program{ programName=name , programLocation=UserSpecified p}) = message ("Using " ++ name ++ " given by user at: " ++ p) reportProgram' name Nothing = message ("No " ++ name ++ " found") -- | Test for a package dependency and record the version we have installed. configDependency :: [PackageIdentifier] -> Dependency -> IO PackageIdentifier configDependency ps (Dependency pkgname vrange) = do let ok p = pkgName p == pkgname && pkgVersion p `withinRange` vrange -- case filter ok ps of [] -> die ("cannot satisfy dependency " ++ pkgname ++ showVersionRange vrange) qs -> let pkg = maximumBy versions qs versions a b = pkgVersion a `compare` pkgVersion b in do message ("Dependency " ++ pkgname ++ showVersionRange vrange ++ ": using " ++ showPackageId pkg) return pkg getInstalledPackagesJHC :: Compiler -> ConfigFlags -> IO [PackageIdentifier] getInstalledPackagesJHC comp cfg = do let verbose = configVerbose cfg when (verbose > 0) $ message "Reading installed packages..." let cmd_line = "\"" ++ compilerPkgTool comp ++ "\" --list-libraries" str <- systemCaptureStdout verbose cmd_line case pCheck (readP_to_S (many (skipSpaces >> parsePackageId)) str) of [ps] -> return ps _ -> die "cannot parse package list" getInstalledPackagesAux :: Compiler -> ConfigFlags -> IO [PackageIdentifier] getInstalledPackagesAux comp cfg = getInstalledPackages comp (configUser cfg) (configVerbose cfg) getInstalledPackages :: Compiler -> Bool -> Int -> IO [PackageIdentifier] getInstalledPackages comp user verbose = do when (verbose > 0) $ message "Reading installed packages..." let user_flag = if user then "--user" else "--global" cmd_line = "\"" ++ compilerPkgTool comp ++ "\" " ++ user_flag ++ " list" str <- systemCaptureStdout verbose cmd_line let keep_line s = ':' `notElem` s && not ("Creating" `isPrefixOf` s) str1 = unlines (filter keep_line (lines str)) str2 = filter (`notElem` ",()") str1 -- case pCheck (readP_to_S (many (skipSpaces >> parsePackageId)) str2) of [ps] -> return ps _ -> die "cannot parse package list" systemCaptureStdout :: Int -> String -> IO String systemCaptureStdout verbose cmd = do withTempFile "." "" $ \tmp -> do let cmd_line = cmd ++ " >" ++ tmp when (verbose > 0) $ putStrLn cmd_line res <- system cmd_line case res of ExitFailure _ -> die ("executing external program failed: "++cmd_line) ExitSuccess -> do str <- readFile tmp let ev [] = ' '; ev xs = last xs ev str `seq` return str -- ----------------------------------------------------------------------------- -- Determining the compiler details configCompilerAux :: ConfigFlags -> IO Compiler configCompilerAux cfg = configCompiler (configHcFlavor cfg) (configHcPath cfg) (configHcPkg cfg) (configVerbose cfg) configCompiler :: Maybe CompilerFlavor -> Maybe FilePath -> Maybe FilePath -> Int -> IO Compiler configCompiler hcFlavor hcPath hcPkg verbose = do let flavor = case hcFlavor of Just f -> f Nothing -> error "Unknown compiler" comp <- case hcPath of Just path -> return path Nothing -> findCompiler verbose flavor ver <- configCompilerVersion flavor comp verbose pkgtool <- case hcPkg of Just path -> return path Nothing -> guessPkgToolFromHCPath verbose flavor comp return (Compiler{compilerFlavor=flavor, compilerVersion=ver, compilerPath=comp, compilerPkgTool=pkgtool}) findCompiler :: Int -> CompilerFlavor -> IO FilePath findCompiler verbose flavor = do let prog = compilerBinaryName flavor when (verbose > 0) $ message $ "searching for " ++ prog ++ " in path." res <- findExecutable prog case res of Nothing -> die ("Cannot find compiler for " ++ prog) Just path -> do when (verbose > 0) $ message ("found " ++ prog ++ " at "++ path) return path -- ToDo: check that compiler works? compilerPkgToolName :: CompilerFlavor -> String compilerPkgToolName GHC = "ghc-pkg" compilerPkgToolName NHC = "hmake" -- FIX: nhc98-pkg Does not yet exist compilerPkgToolName Hugs = "hugs" compilerPkgToolName JHC = "jhc" compilerPkgToolName cmp = error $ "Unsupported compiler: " ++ (show cmp) configCompilerVersion :: CompilerFlavor -> FilePath -> Int -> IO Version configCompilerVersion GHC compilerP verbose = do str <- systemGetStdout verbose ("\"" ++ compilerP ++ "\" --version") case pCheck (readP_to_S parseVersion (dropWhile (not.isDigit) str)) of [v] -> return v _ -> die ("cannot determine version of " ++ compilerP ++ ":\n "++ str) configCompilerVersion JHC compilerP verbose = do str <- systemGetStdout verbose ("\"" ++ compilerP ++ "\" --version") case words str of (_:ver:_) -> case pCheck $ readP_to_S parseVersion ver of [v] -> return v _ -> fail ("parsing version: "++ver++" failed.") _ -> fail ("reading version string: "++show str++" failed.") configCompilerVersion _ _ _ = return Version{ versionBranch=[],versionTags=[] } systemGetStdout :: Int -> String -> IO String systemGetStdout verbose cmd = do withTempFile "." "" $ \tmp -> do let cmd_line = cmd ++ " >" ++ tmp when (verbose > 0) $ putStrLn cmd_line maybeExit $ system cmd_line str <- readFile tmp let eval [] = ' '; eval xs = last xs eval str `seq` return str pCheck :: [(a, [Char])] -> [a] pCheck rs = [ r | (r,s) <- rs, all isSpace s ] guessPkgToolFromHCPath :: Int -> CompilerFlavor -> FilePath -> IO FilePath guessPkgToolFromHCPath verbose flavor path = do let pkgToolName = compilerPkgToolName flavor (dir,_) = splitFileName path pkgtool = dir `joinFileName` pkgToolName `joinFileExt` exeExtension when (verbose > 0) $ message $ "looking for package tool: " ++ pkgToolName ++ " near compiler in " ++ path exists <- doesFileExist pkgtool when (not exists) $ die ("Cannot find package tool: " ++ pkgtool) when (verbose > 0) $ message $ "found package tool in " ++ pkgtool return pkgtool message :: String -> IO () message s = putStrLn $ "configure: " ++ s -- ----------------------------------------------------------------------------- -- Tests #ifdef DEBUG hunitTests :: [Test] hunitTests = [] {- Too specific: packageID = PackageIdentifier "Foo" (Version [1] []) = [TestCase $ do let simonMarGHCLoc = "/usr/bin/ghc" simonMarGHC <- configure emptyPackageDescription {package=packageID} (Just GHC, Just simonMarGHCLoc, Nothing, Nothing) assertEqual "finding ghc, etc on simonMar's machine failed" (LocalBuildInfo "/usr" (Compiler GHC (Version [6,2,2] []) simonMarGHCLoc (simonMarGHCLoc ++ "-pkg")) [] []) simonMarGHC ] -} #endif
FranklinChen/hugs98-plus-Sep2006
packages/Cabal/Distribution/Simple/Configure.hs
bsd-3-clause
18,936
133
27
4,962
4,300
2,236
2,064
305
5
{-# LANGUAGE CPP, RankNTypes, MagicHash, BangPatterns #-} #if __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Trustworthy #-} #endif #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) #include "MachDeps.h" #endif ----------------------------------------------------------------------------- -- | -- Module : Data.Binary.Get -- Copyright : Lennart Kolmodin -- License : BSD3-style (see LICENSE) -- -- Maintainer : Lennart Kolmodin <kolmodin@gmail.com> -- Stability : experimental -- Portability : portable to Hugs and GHC. -- -- The 'Get' monad. A monad for efficiently building structures from -- encoded lazy ByteStrings. -- -- Primitives are available to decode words of various sizes, both big and -- little endian. -- -- Let's decode binary data representing illustrated here. -- In this example the values are in little endian. -- -- > +------------------+--------------+-----------------+ -- > | 32 bit timestamp | 32 bit price | 16 bit quantity | -- > +------------------+--------------+-----------------+ -- -- A corresponding Haskell value looks like this: -- -- @ --data Trade = Trade -- { timestamp :: !'Word32' -- , price :: !'Word32' -- , qty :: !'Word16' -- } deriving ('Show') -- @ -- -- The fields in @Trade@ are marked as strict (using @!@) since we don't need -- laziness here. In practise, you would probably consider using the UNPACK -- pragma as well. -- <http://www.haskell.org/ghc/docs/latest/html/users_guide/pragmas.html#unpack-pragma> -- -- Now, let's have a look at a decoder for this format. -- -- @ --getTrade :: 'Get' Trade --getTrade = do -- timestamp <- 'getWord32le' -- price <- 'getWord32le' -- quantity <- 'getWord16le' -- return '$!' Trade timestamp price quantity -- @ -- -- Or even simpler using applicative style: -- -- @ --getTrade' :: 'Get' Trade --getTrade' = Trade '<$>' 'getWord32le' '<*>' 'getWord32le' '<*>' 'getWord16le' -- @ -- -- The applicative style can sometimes result in faster code, as @binary@ -- will try to optimize the code by grouping the reads together. -- -- There are two kinds of ways to execute this decoder, the lazy input -- method and the incremental input method. Here we will use the lazy -- input method. -- -- Let's first define a function that decodes many @Trade@s. -- -- @ --getTrades :: Get [Trade] --getTrades = do -- empty <- 'isEmpty' -- if empty -- then return [] -- else do trade <- getTrade -- trades <- getTrades -- return (trade:trades) -- @ -- -- Finally, we run the decoder: -- -- @ --lazyIOExample :: IO [Trade] --lazyIOExample = do -- input <- BL.readFile \"trades.bin\" -- return ('runGet' getTrades input) -- @ -- -- This decoder has the downside that it will need to read all the input before -- it can return. On the other hand, it will not return anything until -- it knows it could decode without any decoder errors. -- -- You could also refactor to a left-fold, to decode in a more streaming fashion, -- and get the following decoder. It will start to return data without knowing -- that it can decode all input. -- -- @ --incrementalExample :: BL.ByteString -> [Trade] --incrementalExample input0 = go decoder input0 -- where -- decoder = 'runGetIncremental' getTrade -- go :: 'Decoder' Trade -> BL.ByteString -> [Trade] -- go ('Done' leftover _consumed trade) input = -- trade : go decoder (BL.chunk leftover input) -- go ('Partial' k) input = -- go (k . takeHeadChunk $ input) (dropHeadChunk input) -- go ('Fail' _leftover _consumed msg) _input = -- error msg -- --takeHeadChunk :: BL.ByteString -> Maybe BS.ByteString --takeHeadChunk lbs = -- case lbs of -- (BL.Chunk bs _) -> Just bs -- _ -> Nothing -- --dropHeadChunk :: BL.ByteString -> BL.ByteString --dropHeadChunk lbs = -- case lbs of -- (BL.Chunk _ lbs') -> lbs' -- _ -> BL.Empty -- @ -- -- The @lazyIOExample@ uses lazy I/O to read the file from the disk, which is -- not suitable in all applications, and certainly not if you need to read -- from a socket which has higher likelihood to fail. To address these needs, -- use the incremental input method like in @incrementalExample@. -- For an example of how to read incrementally from a Handle, -- see the implementation of 'decodeFileOrFail' in "Data.Binary". ----------------------------------------------------------------------------- module Data.Binary.Get ( -- * The Get monad Get -- * The lazy input interface -- $lazyinterface , runGet , runGetOrFail , ByteOffset -- * The incremental input interface -- $incrementalinterface , Decoder(..) , runGetIncremental -- ** Providing input , pushChunk , pushChunks , pushEndOfInput -- * Decoding , skip , isEmpty , bytesRead , isolate , lookAhead , lookAheadM , lookAheadE , label -- ** ByteStrings , getByteString , getLazyByteString , getLazyByteStringNul , getRemainingLazyByteString -- ** Decoding words , getWord8 -- *** Big-endian decoding , getWord16be , getWord32be , getWord64be -- *** Little-endian decoding , getWord16le , getWord32le , getWord64le -- *** Host-endian, unaligned decoding , getWordhost , getWord16host , getWord32host , getWord64host -- * Deprecated functions , runGetState -- DEPRECATED , remaining -- DEPRECATED , getBytes -- DEPRECATED ) where import Foreign import qualified Data.ByteString as B import qualified Data.ByteString.Unsafe as B import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Internal as L import Data.Binary.Get.Internal hiding ( Decoder(..), runGetIncremental ) import qualified Data.Binary.Get.Internal as I #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) -- needed for (# unboxing #) with magic hash import GHC.Base import GHC.Word #endif -- $lazyinterface -- The lazy interface consumes a single lazy 'L.ByteString'. It's the easiest -- interface to get started with, but it doesn't support interleaving I\/O and -- parsing, unless lazy I/O is used. -- -- There is no way to provide more input other than the initial data. To be -- able to incrementally give more data, see the incremental input interface. -- $incrementalinterface -- The incremental interface gives you more control over how input is -- provided during parsing. This lets you e.g. interleave parsing and -- I\/O. -- -- The incremental interface consumes a strict 'B.ByteString' at a time, each -- being part of the total amount of input. If your decoder needs more input to -- finish it will return a 'Partial' with a continuation. -- If there is no more input, provide it 'Nothing'. -- -- 'Fail' will be returned if it runs into an error, together with a message, -- the position and the remaining input. -- If it succeeds it will return 'Done' with the resulting value, -- the position and the remaining input. -- | A decoder procuced by running a 'Get' monad. data Decoder a = Fail !B.ByteString {-# UNPACK #-} !ByteOffset String -- ^ The decoder ran into an error. The decoder either used -- 'fail' or was not provided enough input. Contains any -- unconsumed input and the number of bytes consumed. | Partial (Maybe B.ByteString -> Decoder a) -- ^ The decoder has consumed the available input and needs -- more to continue. Provide 'Just' if more input is available -- and 'Nothing' otherwise, and you will get a new 'Decoder'. | Done !B.ByteString {-# UNPACK #-} !ByteOffset a -- ^ The decoder has successfully finished. Except for the -- output value you also get any unused input as well as the -- number of bytes consumed. -- | Run a 'Get' monad. See 'Decoder' for what to do next, like providing -- input, handling decoder errors and to get the output value. -- Hint: Use the helper functions 'pushChunk', 'pushChunks' and -- 'pushEndOfInput'. runGetIncremental :: Get a -> Decoder a runGetIncremental = calculateOffset . I.runGetIncremental calculateOffset :: I.Decoder a -> Decoder a calculateOffset r0 = go r0 0 where go r !acc = case r of I.Done inp a -> Done inp (acc - fromIntegral (B.length inp)) a I.Fail inp s -> Fail inp (acc - fromIntegral (B.length inp)) s I.Partial k -> Partial $ \ms -> case ms of Nothing -> go (k Nothing) acc Just i -> go (k ms) (acc + fromIntegral (B.length i)) I.BytesRead unused k -> go (k $! (acc - unused)) acc -- | DEPRECATED. Provides compatibility with previous versions of this library. -- Run a 'Get' monad and return a tuple with three values. -- The first value is the result of the decoder. The second and third are the -- unused input, and the number of consumed bytes. {-# DEPRECATED runGetState "Use runGetIncremental instead. This function will be removed." #-} runGetState :: Get a -> L.ByteString -> ByteOffset -> (a, L.ByteString, ByteOffset) runGetState g lbs0 pos' = go (runGetIncremental g) lbs0 where go (Done s pos a) lbs = (a, L.chunk s lbs, pos+pos') go (Partial k) lbs = go (k (takeHeadChunk lbs)) (dropHeadChunk lbs) go (Fail _ pos msg) _ = error ("Data.Binary.Get.runGetState at position " ++ show pos ++ ": " ++ msg) takeHeadChunk :: L.ByteString -> Maybe B.ByteString takeHeadChunk lbs = case lbs of (L.Chunk bs _) -> Just bs _ -> Nothing dropHeadChunk :: L.ByteString -> L.ByteString dropHeadChunk lbs = case lbs of (L.Chunk _ lbs') -> lbs' _ -> L.Empty -- | Run a 'Get' monad and return 'Left' on failure and 'Right' on -- success. In both cases any unconsumed input and the number of bytes -- consumed is returned. In the case of failure, a human-readable -- error message is included as well. runGetOrFail :: Get a -> L.ByteString -> Either (L.ByteString, ByteOffset, String) (L.ByteString, ByteOffset, a) runGetOrFail g lbs0 = feedAll (runGetIncremental g) lbs0 where feedAll (Done bs pos x) lbs = Right (L.chunk bs lbs, pos, x) feedAll (Partial k) lbs = feedAll (k (takeHeadChunk lbs)) (dropHeadChunk lbs) feedAll (Fail x pos msg) xs = Left (L.chunk x xs, pos, msg) -- | An offset, counted in bytes. type ByteOffset = Int64 -- | The simplest interface to run a 'Get' decoder. If the decoder runs into -- an error, calls 'fail', or runs out of input, it will call 'error'. runGet :: Get a -> L.ByteString -> a runGet g lbs0 = feedAll (runGetIncremental g) lbs0 where feedAll (Done _ _ x) _ = x feedAll (Partial k) lbs = feedAll (k (takeHeadChunk lbs)) (dropHeadChunk lbs) feedAll (Fail _ pos msg) _ = error ("Data.Binary.Get.runGet at position " ++ show pos ++ ": " ++ msg) -- | Feed a 'Decoder' with more input. If the 'Decoder' is 'Done' or 'Fail' it -- will add the input to 'B.ByteString' of unconsumed input. -- -- @ -- 'runGetIncremental' myParser \`pushChunk\` myInput1 \`pushChunk\` myInput2 -- @ pushChunk :: Decoder a -> B.ByteString -> Decoder a pushChunk r inp = case r of Done inp0 p a -> Done (inp0 `B.append` inp) p a Partial k -> k (Just inp) Fail inp0 p s -> Fail (inp0 `B.append` inp) p s -- | Feed a 'Decoder' with more input. If the 'Decoder' is 'Done' or 'Fail' it -- will add the input to 'ByteString' of unconsumed input. -- -- @ -- 'runGetIncremental' myParser \`pushChunks\` myLazyByteString -- @ pushChunks :: Decoder a -> L.ByteString -> Decoder a pushChunks r0 = go r0 . L.toChunks where go r [] = r go (Done inp pos a) xs = Done (B.concat (inp:xs)) pos a go (Fail inp pos s) xs = Fail (B.concat (inp:xs)) pos s go (Partial k) (x:xs) = go (k (Just x)) xs -- | Tell a 'Decoder' that there is no more input. This passes 'Nothing' to a -- 'Partial' decoder, otherwise returns the decoder unchanged. pushEndOfInput :: Decoder a -> Decoder a pushEndOfInput r = case r of Done _ _ _ -> r Partial k -> k Nothing Fail _ _ _ -> r -- | Skip ahead @n@ bytes. Fails if fewer than @n@ bytes are available. skip :: Int -> Get () skip n = withInputChunks (fromIntegral n) consumeBytes (const ()) failOnEOF -- | An efficient get method for lazy ByteStrings. Fails if fewer than @n@ -- bytes are left in the input. getLazyByteString :: Int64 -> Get L.ByteString getLazyByteString n0 = withInputChunks n0 consumeBytes L.fromChunks failOnEOF consumeBytes :: Consume Int64 consumeBytes n str | fromIntegral (B.length str) >= n = Right (B.splitAt (fromIntegral n) str) | otherwise = Left (n - fromIntegral (B.length str)) consumeUntilNul :: Consume () consumeUntilNul _ str = case B.break (==0) str of (want, rest) | B.null rest -> Left () | otherwise -> Right (want, B.drop 1 rest) consumeAll :: Consume () consumeAll _ _ = Left () resumeOnEOF :: [B.ByteString] -> Get L.ByteString resumeOnEOF = return . L.fromChunks -- | Get a lazy ByteString that is terminated with a NUL byte. -- The returned string does not contain the NUL byte. Fails -- if it reaches the end of input without finding a NUL. getLazyByteStringNul :: Get L.ByteString getLazyByteStringNul = withInputChunks () consumeUntilNul L.fromChunks failOnEOF -- | Get the remaining bytes as a lazy ByteString. -- Note that this can be an expensive function to use as it forces reading -- all input and keeping the string in-memory. getRemainingLazyByteString :: Get L.ByteString getRemainingLazyByteString = withInputChunks () consumeAll L.fromChunks resumeOnEOF ------------------------------------------------------------------------ -- Primtives -- helper, get a raw Ptr onto a strict ByteString copied out of the -- underlying lazy byteString. getPtr :: Storable a => Int -> Get a getPtr n = readNWith n peek {-# INLINE getPtr #-} -- | Read a Word8 from the monad state getWord8 :: Get Word8 getWord8 = readN 1 B.unsafeHead {-# INLINE[2] getWord8 #-} -- force GHC to inline getWordXX {-# RULES "getWord8/readN" getWord8 = readN 1 B.unsafeHead "getWord16be/readN" getWord16be = readN 2 word16be "getWord16le/readN" getWord16le = readN 2 word16le "getWord32be/readN" getWord32be = readN 4 word32be "getWord32le/readN" getWord32le = readN 4 word32le "getWord64be/readN" getWord64be = readN 8 word64be "getWord64le/readN" getWord64le = readN 8 word64le #-} -- | Read a Word16 in big endian format getWord16be :: Get Word16 getWord16be = readN 2 word16be word16be :: B.ByteString -> Word16 word16be = \s -> (fromIntegral (s `B.unsafeIndex` 0) `shiftl_w16` 8) .|. (fromIntegral (s `B.unsafeIndex` 1)) {-# INLINE[2] getWord16be #-} {-# INLINE word16be #-} -- | Read a Word16 in little endian format getWord16le :: Get Word16 getWord16le = readN 2 word16le word16le :: B.ByteString -> Word16 word16le = \s -> (fromIntegral (s `B.unsafeIndex` 1) `shiftl_w16` 8) .|. (fromIntegral (s `B.unsafeIndex` 0) ) {-# INLINE[2] getWord16le #-} {-# INLINE word16le #-} -- | Read a Word32 in big endian format getWord32be :: Get Word32 getWord32be = readN 4 word32be word32be :: B.ByteString -> Word32 word32be = \s -> (fromIntegral (s `B.unsafeIndex` 0) `shiftl_w32` 24) .|. (fromIntegral (s `B.unsafeIndex` 1) `shiftl_w32` 16) .|. (fromIntegral (s `B.unsafeIndex` 2) `shiftl_w32` 8) .|. (fromIntegral (s `B.unsafeIndex` 3) ) {-# INLINE[2] getWord32be #-} {-# INLINE word32be #-} -- | Read a Word32 in little endian format getWord32le :: Get Word32 getWord32le = readN 4 word32le word32le :: B.ByteString -> Word32 word32le = \s -> (fromIntegral (s `B.unsafeIndex` 3) `shiftl_w32` 24) .|. (fromIntegral (s `B.unsafeIndex` 2) `shiftl_w32` 16) .|. (fromIntegral (s `B.unsafeIndex` 1) `shiftl_w32` 8) .|. (fromIntegral (s `B.unsafeIndex` 0) ) {-# INLINE[2] getWord32le #-} {-# INLINE word32le #-} -- | Read a Word64 in big endian format getWord64be :: Get Word64 getWord64be = readN 8 word64be word64be :: B.ByteString -> Word64 word64be = \s -> (fromIntegral (s `B.unsafeIndex` 0) `shiftl_w64` 56) .|. (fromIntegral (s `B.unsafeIndex` 1) `shiftl_w64` 48) .|. (fromIntegral (s `B.unsafeIndex` 2) `shiftl_w64` 40) .|. (fromIntegral (s `B.unsafeIndex` 3) `shiftl_w64` 32) .|. (fromIntegral (s `B.unsafeIndex` 4) `shiftl_w64` 24) .|. (fromIntegral (s `B.unsafeIndex` 5) `shiftl_w64` 16) .|. (fromIntegral (s `B.unsafeIndex` 6) `shiftl_w64` 8) .|. (fromIntegral (s `B.unsafeIndex` 7) ) {-# INLINE[2] getWord64be #-} {-# INLINE word64be #-} -- | Read a Word64 in little endian format getWord64le :: Get Word64 getWord64le = readN 8 word64le word64le :: B.ByteString -> Word64 word64le = \s -> (fromIntegral (s `B.unsafeIndex` 7) `shiftl_w64` 56) .|. (fromIntegral (s `B.unsafeIndex` 6) `shiftl_w64` 48) .|. (fromIntegral (s `B.unsafeIndex` 5) `shiftl_w64` 40) .|. (fromIntegral (s `B.unsafeIndex` 4) `shiftl_w64` 32) .|. (fromIntegral (s `B.unsafeIndex` 3) `shiftl_w64` 24) .|. (fromIntegral (s `B.unsafeIndex` 2) `shiftl_w64` 16) .|. (fromIntegral (s `B.unsafeIndex` 1) `shiftl_w64` 8) .|. (fromIntegral (s `B.unsafeIndex` 0) ) {-# INLINE[2] getWord64le #-} {-# INLINE word64le #-} ------------------------------------------------------------------------ -- Host-endian reads -- | /O(1)./ Read a single native machine word. The word is read in -- host order, host endian form, for the machine you're on. On a 64 bit -- machine the Word is an 8 byte value, on a 32 bit machine, 4 bytes. getWordhost :: Get Word getWordhost = getPtr (sizeOf (undefined :: Word)) {-# INLINE getWordhost #-} -- | /O(1)./ Read a 2 byte Word16 in native host order and host endianness. getWord16host :: Get Word16 getWord16host = getPtr (sizeOf (undefined :: Word16)) {-# INLINE getWord16host #-} -- | /O(1)./ Read a Word32 in native host order and host endianness. getWord32host :: Get Word32 getWord32host = getPtr (sizeOf (undefined :: Word32)) {-# INLINE getWord32host #-} -- | /O(1)./ Read a Word64 in native host order and host endianess. getWord64host :: Get Word64 getWord64host = getPtr (sizeOf (undefined :: Word64)) {-# INLINE getWord64host #-} ------------------------------------------------------------------------ -- Unchecked shifts shiftl_w16 :: Word16 -> Int -> Word16 shiftl_w32 :: Word32 -> Int -> Word32 shiftl_w64 :: Word64 -> Int -> Word64 #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) shiftl_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftL#` i) shiftl_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftL#` i) #if WORD_SIZE_IN_BITS < 64 shiftl_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftL64#` i) #if __GLASGOW_HASKELL__ <= 606 -- Exported by GHC.Word in GHC 6.8 and higher foreign import ccall unsafe "stg_uncheckedShiftL64" uncheckedShiftL64# :: Word64# -> Int# -> Word64# #endif #else shiftl_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftL#` i) #endif #else shiftl_w16 = shiftL shiftl_w32 = shiftL shiftl_w64 = shiftL #endif
basvandijk/binary
src/Data/Binary/Get.hs
bsd-3-clause
19,348
0
21
4,173
3,372
1,932
1,440
230
5
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE RankNTypes #-} -- | LibClang is a Haskell binding to the libclang library, a compiler -- front-end for C-family languages. It allows you to produce and walk -- an AST, get a list of diagnostic warnings and errors, perform code -- completion, and more. -- -- Your starting point for using LibClang should be this module, which -- exports the 'ClangT' monad and the functions you'll need to start -- analyzing source code. The other modules in this library, such as -- "Clang.Cursor" and "Clang.Type", are meant to be imported -- qualified, and provide the functions you'll need to get more -- detailed information about the AST. module Clang ( -- * Parsing parseSourceFile -- * Traversing the AST , FFI.CursorList , getChildren , getDescendants , getDeclarations , getReferences , getDeclarationsAndReferences , FFI.ParentedCursorList , getParentedDescendants , getParentedDeclarations , getParentedReferences , getParentedDeclarationsAndReferences -- * Traversing inclusions , FFI.Inclusion(..) , FFI.InclusionList , getInclusions -- * The ClangT monad , ClangT , Clang , ClangBase , ClangValue(..) , ClangValueList(..) , clangScope -- * Clang AST types , FFI.AvailabilityKind(..) , FFI.CursorKind(..) , FFI.LinkageKind(..) , FFI.LanguageKind(..) , FFI.Cursor , FFI.CursorSet , FFI.ParentedCursor(..) , FFI.ObjCPropertyAttrKind(..) , FFI.ObjCDeclQualifierKind(..) , FFI.NameRefFlags(..) , FFI.Version(..) , FFI.PlatformAvailability(..) , FFI.PlatformAvailabilityInfo(..) , FFI.Diagnostic , FFI.DiagnosticSet , FFI.File , FFI.Remapping , FFI.SourceLocation , FFI.SourceRange , FFI.ClangString , FFI.Token , FFI.TokenKind(..) , FFI.Index , FFI.TranslationUnit , FFI.UnsavedFile , FFI.Module (..) , FFI.Type , FFI.TypeKind(..) , FFI.CallingConv(..) , FFI.CXXAccessSpecifier(..) , FFI.TypeLayoutError(..) , FFI.RefQualifierKind(..) ) where import qualified Data.Vector as DV import qualified Clang.Internal.FFI as FFI import qualified Clang.Index as Index import Clang.Internal.Monad import qualified Clang.TranslationUnit as TU -- | Parses a source file using libclang and allows you to analyze the -- resulting AST using a callback. -- -- More flexible alternatives to 'parseSourceFile' are available in -- "Clang.Index" and "Clang.TranslationUnit". parseSourceFile :: ClangBase m => FilePath -- ^ Source filename -> [String] -- ^ Clang-compatible compilation arguments -> (forall s. FFI.TranslationUnit s -> ClangT s m a) -- ^ Callback -> m (Maybe a) parseSourceFile path args f = Index.withNew False False $ \index -> TU.withParsed index (Just path) args DV.empty [] f -- | Gets an 'FFI.CursorList' of the children of this 'FFI.Cursor'. getChildren :: ClangBase m => FFI.Cursor s' -> ClangT s m (FFI.CursorList s) getChildren = FFI.getChildren -- | Gets an 'FFI.CursorList' of all descendants of this -- 'FFI.Cursor'. If you are planning on visiting all the descendants -- anyway, this is often more efficient than calling 'getChildren' -- repeatedly. The descendants are listed according to a preorder -- traversal of the AST. getDescendants :: ClangBase m => FFI.Cursor s' -> ClangT s m (FFI.CursorList s) getDescendants = FFI.getDescendants -- | Like 'getDescendants', but each descendant is annotated with its -- parent AST node. This provides enough information to replicate the -- preorder traversal of the AST, but maintains the performance -- benefits relative to 'getChildren'. getParentedDescendants :: ClangBase m => FFI.Cursor s' -> ClangT s m (FFI.ParentedCursorList s) getParentedDescendants = FFI.getParentedDescendants -- | Gets an 'FFI.CursorList' of all declarations in this 'FFI.TranslationUnit'. getDeclarations :: ClangBase m => FFI.TranslationUnit s' -> ClangT s m (FFI.CursorList s) getDeclarations = FFI.getDeclarations -- | Like 'getDeclarations', but each declaration is annotated with -- its parent AST node. getParentedDeclarations :: ClangBase m => FFI.TranslationUnit s' -> ClangT s m (FFI.ParentedCursorList s) getParentedDeclarations = FFI.getParentedDeclarations -- | Gets an 'FFI.CursorList' of all references in this 'FFI.TranslationUnit'. getReferences :: ClangBase m => FFI.TranslationUnit s' -> ClangT s m (FFI.CursorList s) getReferences = FFI.getReferences -- | Like 'getReferences', but each reference is annotated with -- its parent AST node. getParentedReferences :: ClangBase m => FFI.TranslationUnit s' -> ClangT s m (FFI.ParentedCursorList s) getParentedReferences = FFI.getParentedReferences -- | Gets two 'FFI.CursorList's, one containing all declarations in -- this 'FFI.TranslationUnit', and another containing all -- references. If you need both lists, this is more efficient than -- calling 'getDeclarations' and 'getReferences' individually, as it -- only traverses the AST once. getDeclarationsAndReferences :: ClangBase m => FFI.TranslationUnit s' -> ClangT s m (FFI.CursorList s, FFI.CursorList s) getDeclarationsAndReferences = FFI.getDeclarationsAndReferences -- | Like 'getDeclarationsAndReferences', but each reference is annotated with -- its parent AST node. getParentedDeclarationsAndReferences :: ClangBase m => FFI.TranslationUnit s' -> ClangT s m (FFI.ParentedCursorList s, FFI.ParentedCursorList s) getParentedDeclarationsAndReferences = FFI.getParentedDeclarationsAndReferences -- | Gets all inclusions in this 'FFI.TranslationUnit'. getInclusions :: ClangBase m => FFI.TranslationUnit s' -> ClangT s m (FFI.InclusionList s) getInclusions = FFI.getInclusions -- | 'Clang' is a specialization of the 'ClangT' monad to 'IO', -- provided as a convenience. If you have a more complicated monad -- stack, you may find it useful to define your own 'Clang'-like -- type synonym. type Clang s a = ClangT s IO a
chetant/LibClang
src/Clang.hs
bsd-3-clause
6,046
0
13
1,046
990
577
413
97
1
{-# LANGUAGE CPP #-} module UtilsSpec (main, spec) where import Test.Hspec import TestUtils import qualified GHC as GHC import qualified HscTypes as GHC import Control.Exception import Control.Monad.State import Data.List import qualified GhcMod.Types as GM (mpModule) import Language.Haskell.GHC.ExactPrint.Utils import Language.Haskell.Refact.Refactoring.Renaming import Language.Haskell.Refact.Utils.GhcVersionSpecific import Language.Haskell.Refact.Utils.LocUtils import Language.Haskell.Refact.Utils.Monad import Language.Haskell.Refact.Utils.MonadFunctions import Language.Haskell.Refact.Utils.TypeUtils import Language.Haskell.Refact.Utils.Types import Language.Haskell.Refact.Utils.Utils import Language.Haskell.Refact.Utils.Variables import Language.Haskell.Refact.Refactoring.RoundTrip import System.Directory -- --------------------------------------------------------------------- main :: IO () main = do hspec spec spec :: Spec spec = do describe "locToExp on ParsedSource" $ do it "p:finds the largest leftmost expression contained in a given region #1" $ do t <- ct $ parsedFileGhc "./TypeUtils/B.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let (Just expr) = locToExp (7,7) (7,43) parsed :: Maybe (GHC.Located (GHC.HsExpr GHC.RdrName)) getLocatedStart expr `shouldBe` (7,9) getLocatedEnd expr `shouldBe` (7,42) it "p:finds the largest leftmost expression contained in a given region #2" $ do -- ((_, _, mod), toks) <- parsedFileBGhc t <- ct $ parsedFileGhc "./TypeUtils/B.hs" let modu = GHC.pm_parsed_source $ tmParsedModule t let (Just expr) = locToExp (7,7) (7,41) modu :: Maybe (GHC.Located (GHC.HsExpr GHC.RdrName)) getLocatedStart expr `shouldBe` (7,12) getLocatedEnd expr `shouldBe` (7,19) it "finds the largest leftmost expression in RenamedSource" $ do t <- ct $ parsedFileGhc "./TypeUtils/B.hs" let renamed = tmRenamedSource t let (Just expr) = locToExp (7,7) (7,41) renamed :: Maybe (GHC.Located (GHC.HsExpr GHC.Name)) getLocatedStart expr `shouldBe` (7,12) getLocatedEnd expr `shouldBe` (7,19) describe "locToExp on RenamedSource" $ do it "r:finds the largest leftmost expression contained in a given region #1" $ do -- ((_, Just renamed, _), toks) <- parsedFileBGhc t <- ct $ parsedFileGhc "./TypeUtils/B.hs" let renamed = tmRenamedSource t let (Just expr) = locToExp (7,7) (7,43) renamed :: Maybe (GHC.Located (GHC.HsExpr GHC.Name)) getLocatedStart expr `shouldBe` (7,9) getLocatedEnd expr `shouldBe` (7,42) -- ------------------------------------------------------------------- describe "loading a file" $ do it "loads a file having the LANGUAGE CPP pragma" $ do t <- ct $ parsedFileGhc "./BCpp.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t (showGhc parsed) `shouldBe` "module BCpp where\nbob :: Int -> Int -> Int\nbob x y = x + y" -- --------------------------------- it "loads a file having a top comment and LANGUAGE CPP pragma" $ do t <- ct $ parsedFileGhc "./BCppTC.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t (showGhc parsed) `shouldBe` "module BCppTC where\nbob :: Int -> Int -> Int\nbob x y = x + y" -- --------------------------------- it "refactors a file having the LANGUAGE CPP pragma" $ do r <- ct $ roundTrip defaultTestSettings testOptions "BCpp.hs" -- r <- ct $ roundTrip logTestSettings testOptions "BCpp.hs" r' <- ct $ mapM makeRelativeToCurrentDirectory r r' `shouldBe` ["BCpp.hs"] diff <- compareFiles "./test/testdata/BCpp.refactored.hs" "./test/testdata/BCpp.hs" diff `shouldBe` [] -- --------------------------------- it "loads a series of files based on cabal1" $ do currentDir <- getCurrentDirectory setCurrentDirectory "./test/testdata/cabal/cabal1" let settings = defaultSettings { rsetEnabledTargets = (True,True,False,False) -- , rsetVerboseLevel = Debug } r <- rename settings testOptions "./src/Foo/Bar.hs" "baz1" (3, 1) -- r <- rename logTestSettings cradle "./src/Foo/Bar.hs" "baz1" (3, 1) r' <- mapM makeRelativeToCurrentDirectory r setCurrentDirectory currentDir (show r') `shouldBe` "[\"src/Foo/Bar.hs\"," ++"\"src/main.hs\"]" -- ----------------------------------- it "loads a series of files based on cabal2, which has 2 exe" $ do currentDir <- getCurrentDirectory setCurrentDirectory "./test/testdata/cabal/cabal2" let settings = defaultSettings { rsetEnabledTargets = (True,True,True,True) -- , rsetVerboseLevel = Debug } let handler = [Handler handler1] handler1 :: GHC.SourceError -> IO [String] handler1 e = do setCurrentDirectory currentDir return [show e] r <- catches (rename settings testOptions "./src/Foo/Bar.hs" "baz1" (3, 1)) handler r' <- mapM makeRelativeToCurrentDirectory r setCurrentDirectory currentDir (show r') `shouldBe` "[\"src/Foo/Bar.hs\","++ "\"src/main1.hs\","++ "\"src/main2.hs\"]" -- ----------------------------------- it "loads a file without a cabal project" $ do tmp <- getTemporaryDirectory let testDir = tmp ++ "/hare-test-no-cabal" testFileName = testDir ++ "/Foo.hs" testFileContents = unlines [ "main = putStrLn \"helo\"" , "x = 1" ] createDirectoryIfMissing True testDir writeFile testFileName testFileContents let comp = do parseSourceFileGhc testFileName tm <- getRefactTargetModule g <- clientModsAndFiles tm return g (mg,_s) <- cdAndDo testDir $ runRefactGhc comp initialState testOptions -- (mg,_s) <- cdAndDo testDir $ runRefactGhc comp initialLogOnState testOptions showGhc (map GM.mpModule mg) `shouldBe` "[]" -- ----------------------------------- it "loads a series of files based on cabal3, which has a lib and an exe" $ do currentDir <- getCurrentDirectory setCurrentDirectory "./test/testdata/cabal/cabal3" let settings = defaultSettings { rsetEnabledTargets = (True,True,True,True) -- , rsetVerboseLevel = Debug } let handler = [Handler handler1] handler1 :: GHC.SourceError -> IO [String] handler1 e = do setCurrentDirectory currentDir return [show e] r <- catches (rename settings testOptions "./src/main1.hs" "baz1" (7, 1)) handler r' <- mapM makeRelativeToCurrentDirectory r setCurrentDirectory currentDir (show r') `shouldBe` "[\"src/main1.hs\"]" -- ----------------------------------- it "loads a series of files based on cabal4, with different dependencies" $ do currentDir <- getCurrentDirectory setCurrentDirectory "./test/testdata/cabal/cabal4" let settings = defaultSettings { rsetEnabledTargets = (True,True,True,True) -- , rsetVerboseLevel = Debug } let handler = [Handler handler1] handler1 :: GHC.SourceError -> IO [String] handler1 e = do setCurrentDirectory currentDir return [show e] r <- catches (rename settings testOptions "./src/Foo/Bar.hs" "baz1" (3, 1)) handler -- r <- catches (rename settings testOptions "./src/main4.hs" "baz1" (3, 1)) handler r' <- mapM makeRelativeToCurrentDirectory r setCurrentDirectory currentDir (show r') `shouldBe` "[\"src/Foo/Bar.hs\",\"src/main4.hs\"]" -- ----------------------------------- {- TODO: this test fails on travis, due to missing hspec-discover it "renames in HaRe Utils 1" $ do currentDir <- getCurrentDirectory -- currentDir `shouldBe` "/home/alanz/mysrc/github/alanz/HaRe" setCurrentDirectory "./" -- d <- getCurrentDirectory -- d `shouldBe` "/home/alanz/mysrc/github/alanz/HaRe" cradle <- findCradle -- (show cradle) `shouldBe` "" -- (cradleCurrentDir cradle) `shouldBe` "/home/alanz/mysrc/github/alanz/HaRe" let settings = defaultSettings { rsetEnabledTargets = (True,True,True,True) -- , rsetVerboseLevel = Debug } let handler = [Handler handler1] handler1 :: GHC.SourceError -> IO [String] handler1 e = do setCurrentDirectory currentDir return [show e] r <- catches (rename settings cradle "./src/Language/Haskell/Refact/Utils.hs" "clientModsAndFiles1" (473, 6)) handler setCurrentDirectory currentDir r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"./src/Language/Haskell/Refact/Utils.hs\","++ "\"./src/Language/Haskell/Refact/Renaming.hs\","++ "\"./src/Language/Haskell/Refact/MoveDef.hs\","++ "\"./src/Language/Haskell/Refact/DupDef.hs\","++ "\"./src/Language/Haskell/Refact/Renaming.hs\","++ "\"./src/Language/Haskell/Refact/MoveDef.hs\","++ "\"./src/Language/Haskell/Refact/DupDef.hs\","++ "\"test/UtilsSpec.hs\","++ "\"./src/Language/Haskell/Refact/Renaming.hs\","++ "\"./src/Language/Haskell/Refact/MoveDef.hs\","++ "\"./src/Language/Haskell/Refact/DupDef.hs\"]" -} -- ----------------------------------- {- it "renames in HaRe Utils 2" $ do currentDir <- getCurrentDirectory -- currentDir `shouldBe` "/home/alanz/mysrc/github/alanz/HaRe" setCurrentDirectory "./" -- d <- getCurrentDirectory -- d `shouldBe` "/home/alanz/mysrc/github/alanz/HaRe" cradle <- findCradle -- (show cradle) `shouldBe` "" -- (cradleCurrentDir cradle) `shouldBe` "/home/alanz/mysrc/github/alanz/HaRe" let settings = defaultSettings { rsetEnabledTargets = (True,True,True,True) , rsetVerboseLevel = Debug } let handler = [Handler handler1] handler1 :: GHC.SourceError -> IO [String] handler1 e = do setCurrentDirectory currentDir return [show e] r <- catches (rename settings cradle "./test/UtilsSpec.hs" "parsed" (41, 10)) handler setCurrentDirectory currentDir r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"./src/Language/Haskell/Refact/Utils.hs\","++ "\"./src/Language/Haskell/Refact/Renaming.hs\","++ "\"./src/Language/Haskell/Refact/MoveDef.hs\","++ "\"./src/Language/Haskell/Refact/DupDef.hs\","++ "\"./src/Language/Haskell/Refact/Renaming.hs\","++ "\"./src/Language/Haskell/Refact/MoveDef.hs\","++ "\"./src/Language/Haskell/Refact/DupDef.hs\","++ "\"test/UtilsSpec.hs\","++ "\"./src/Language/Haskell/Refact/Renaming.hs\","++ "\"./src/Language/Haskell/Refact/MoveDef.hs\","++ "\"./src/Language/Haskell/Refact/DupDef.hs\"]" -} -- ----------------------------------- {- -- This test does not work properly on Travis, missing hspec-discover it "renames in HaRe Utils 3" $ do currentDir <- getCurrentDirectory -- currentDir `shouldBe` "/home/alanz/mysrc/github/alanz/HaRe" setCurrentDirectory "./" -- d <- getCurrentDirectory -- d `shouldBe` "/home/alanz/mysrc/github/alanz/HaRe" cradle <- findCradle -- (show cradle) `shouldBe` "" -- (cradleCurrentDir cradle) `shouldBe` "/home/alanz/mysrc/github/alanz/HaRe" let settings = defaultSettings { rsetEnabledTargets = (True,True,True,True) -- , rsetVerboseLevel = Debug } let handler = [Handler handler1] handler1 :: GHC.SourceError -> IO [String] handler1 e = do setCurrentDirectory currentDir return [show e] r <- catches (rename settings cradle "./test/UtilsSpec.hs" "parsed" (41, 11)) handler setCurrentDirectory currentDir r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/UtilsSpec.hs\"]" -} -- ------------------------------------------------------------------- describe "sameOccurrence" $ do it "checks that a given syntax element is the same occurrence as another" $ do pending -- "write this test" -- ------------------------------------------------------------------- describe "isVarId" $ do it "returns True if a string is a lexically valid variable name" $ do isVarId "foo" `shouldBe` True it "returns False if a string is not lexically valid variable name" $ do isVarId "Foo" `shouldBe` False -- ------------------------------------------------------------------- describe "getModuleName" $ do it "returns a string for the module name if there is one" $ do t <- ct $ parsedFileGhc "./TypeUtils/B.hs" let modu = GHC.pm_parsed_source $ tmParsedModule t let (Just (_modname,modNameStr)) = getModuleName modu modNameStr `shouldBe` "TypeUtils.B" it "returns Nothing for the module name otherwise" $ do t <- ct $ parsedFileGhc "./NoMod.hs" let modu = GHC.pm_parsed_source $ tmParsedModule t getModuleName modu `shouldBe` Nothing -- ------------------------------------------------------------------- describe "modIsExported" $ do it "needs a test or two" $ do pending -- "write this test" -- ------------------------------------------------------------------- describe "clientModsAndFiles" $ do it "can only be called in a live RefactGhc session" $ do pending -- "write this test" ------------------------------------ it "gets modules which directly or indirectly import a module #1" $ do -- TODO: harvest this commonality let comp = do parseSourceFileGhc "./S1.hs" tm <- getRefactTargetModule g <- clientModsAndFiles tm return g (mg,_s) <- ct $ runRefactGhc comp initialState testOptions -- (mg,_s) <- ct $ runRefactGhc comp initialLogOnState testOptions (sort $ map (showGhc . GM.mpModule) mg) `shouldBe` ["M2", "M3", "Main"] ------------------------------------ it "gets modules which directly or indirectly import a module #2" $ do let comp = do parseSourceFileGhc "./M3.hs" tm <- getRefactTargetModule g <- clientModsAndFiles tm return g (mg,_s) <- ct $ runRefactGhc comp initialState testOptions showGhc (map GM.mpModule mg) `shouldBe` "[Main]" ------------------------------------ it "gets modules which import a module in different cabal targets" $ do currentDir <- getCurrentDirectory setCurrentDirectory "./test/testdata/cabal/cabal2" let comp = do parseSourceFileGhc "./src/Foo/Bar.hs" -- Load the file first tm <- getRefactTargetModule g <- clientModsAndFiles tm return g (mg,_s) <- runRefactGhc comp initialState testOptions showGhc (map GM.mpModule mg) `shouldBe` "[Main, Main]" setCurrentDirectory currentDir ------------------------------------ it "gets modules when loading without a cabal file" $ do tmp <- getTemporaryDirectory let testDir = tmp ++ "/hare-test-no-cabal-clientmodsandfiles" testFileBName = testDir ++ "/B.hs" testFileFooName = testDir ++ "/Foo.hs" testFileBContents = unlines [ "module B where" , "y = 2" ] testFileFooContents = unlines [ "import B" , "main = putStrLn \"hello\"" , "x = y + 1" ] createDirectoryIfMissing True testDir writeFile testFileBName testFileBContents writeFile testFileFooName testFileFooContents let comp = do parseSourceFileGhc "./Foo.hs" -- Load the file first parseSourceFileGhc "./B.hs" -- Load the file first tm <- getRefactTargetModule g <- clientModsAndFiles tm return g (mg,_s) <- cdAndDo testDir $ runRefactGhc comp initialState testOptions showGhc (map GM.mpModule mg) `shouldBe` "[]" ------------------------------------ it "gets modules for HaRe" $ do {- let comp = do parseSourceFileGhc "src/Language/Haskell/Refact/Utils/TypeUtils.hs" -- Load the file first tm <- getRefactTargetModule g <- clientModsAndFiles tm return g (mg,_s) <- runRefactGhc comp initialState testOptions -- (mg,_s) <- runRefactGhc comp initialLogOnState testOptions show (sort $ map GM.mpModule mg) `shouldBe` "[ModuleName \"Language.Haskell.Refact.API\",ModuleName \"Language.Haskell.Refact.HaRe\",ModuleName \"Language.Haskell.Refact.Refactoring.Case\",ModuleName \"Language.Haskell.Refact.Refactoring.DupDef\",ModuleName \"Language.Haskell.Refact.Refactoring.MoveDef\",ModuleName \"Language.Haskell.Refact.Refactoring.Renaming\",ModuleName \"Language.Haskell.Refact.Refactoring.RoundTrip\",ModuleName \"Language.Haskell.Refact.Refactoring.SwapArgs\",ModuleName \"Language.Haskell.Refact.Refactoring.Simple\",ModuleName \"MoveDefSpec\",ModuleName \"Main\",ModuleName \"Main\",ModuleName \"CaseSpec\",ModuleName \"DupDefSpec\",ModuleName \"GhcUtilsSpec\",ModuleName \"RenamingSpec\",ModuleName \"RoundTripSpec\",ModuleName \"SimpleSpec\",ModuleName \"SwapArgsSpec\",ModuleName \"TypeUtilsSpec\",ModuleName \"UtilsSpec\"]" -} pendingWith "make an equivalent test using testdata/cabal" -- ------------------------------------------------------------------- describe "serverModsAndFiles" $ do it "can only be called in a live RefactGhc session" $ do pending -- "write this test" it "gets modules which are directly or indirectly imported by a module #1" $ do let comp = do parseSourceFileGhc "./M.hs" -- Load the file first g <- serverModsAndFiles $ GHC.mkModuleName "S1" return g (mg,_s) <- ct $ runRefactGhc comp initialState testOptions -- (mg,_s) <- ct $ runRefactGhc comp initialLogOnState testOptions showGhc (map GHC.ms_mod mg) `shouldBe` "[]" it "gets modules which are directly or indirectly imported by a module #2" $ do let comp = do parseSourceFileGhc "./M3.hs" -- Load the file first g <- serverModsAndFiles $ GHC.mkModuleName "M3" return g (mg,_s) <- ct $ runRefactGhc comp initialState testOptions showGhc (map GHC.ms_mod mg) `shouldBe` "[M2, S1]" -- ------------------------------------------------------------------- {- describe "getCurrentModuleGraph" $ do it "gets the module graph for the currently loaded modules" $ do let comp = do (_p,_toks) <- parseFileBGhc -- Load the file first g <- getCurrentModuleGraph return g (mg,_s) <- runRefactGhcState comp map (\m -> GHC.moduleNameString $ GHC.ms_mod_name m) mg `shouldBe` (["TypeUtils.B","TypeUtils.C"]) map (\m -> show $ GHC.ml_hs_file $ GHC.ms_location m) mg `shouldBe` (["Just \"./test/testdata/TypeUtils/B.hs\"" ,"Just \"./test/testdata/TypeUtils/C.hs\""]) it "gets the updated graph, after a refactor" $ do pending -- "write this test" -} -- ------------------------------------------------------------------- {- describe "sortCurrentModuleGraph" $ do it "needs a test or two" $ do let comp = do (_p,_toks) <- parseFileBGhc -- Load the file first g <- sortCurrentModuleGraph return g (mg,_s) <- runRefactGhcState comp (showGhc $ map (\m -> GHC.ms_mod m) (GHC.flattenSCCs mg)) `shouldBe` "[main:TypeUtils.C, main:TypeUtils.B]" -} -- ------------------------------------------------------------------- describe "parseSourceFileGhc" $ do it "retrieves a module from an existing module graph #1" $ do let comp = do parseSourceFileGhc "./S1.hs" pr <- getTypecheckedModule tm <- getRefactTargetModule g <- clientModsAndFiles tm return (pr,g) ( (t, mg), _s) <- ct $ runRefactGhc comp initialState testOptions let parsed = GHC.pm_parsed_source $ tmParsedModule t (show $ getModuleName parsed) `shouldBe` "Just (ModuleName \"S1\",\"S1\")" (sort $ map (showGhc . GM.mpModule) mg) `shouldBe` ["M2", "M3", "Main"] -- --------------------------------- it "loads the module and dependents if no existing module graph" $ do let comp = do parseSourceFileGhc "./S1.hs" pr <- getTypecheckedModule tm <- getRefactTargetModule g <- clientModsAndFiles tm return (pr,g) ((t, mg ), _s) <- ct $ runRefactGhc comp initialState testOptions let parsed = GHC.pm_parsed_source $ tmParsedModule t (show $ getModuleName parsed) `shouldBe` "Just (ModuleName \"S1\",\"S1\")" (sort $ map (showGhc . GM.mpModule) mg) `shouldBe` ["M2", "M3", "Main"] -- --------------------------------- it "retrieves a module from an existing module graph #2" $ do let comp = do parseSourceFileGhc "./DupDef/Dd1.hs" pr <- getTypecheckedModule tm <- getRefactTargetModule g <- clientModsAndFiles tm return (pr,g) ((t, mg), _s) <- ct $ runRefactGhc comp initialState testOptions let parsed = GHC.pm_parsed_source $ tmParsedModule t (show $ getModuleName parsed) `shouldBe` "Just (ModuleName \"DupDef.Dd1\",\"DupDef.Dd1\")" showGhc (map GM.mpModule mg) `shouldBe` "[DupDef.Dd2, DupDef.Dd3]" -- ------------------------------------------------------------------- describe "runRefactGhc" $ do it "contains a State monad" $ do let comp = do s <- get parseSourceFileGhc "./TypeUtils/B.hs" g <- GHC.getModuleGraph gs <- mapM GHC.showModule g put (s {rsUniqState = 100}) return (show gs) (_,s) <- ct $ runRefactGhc comp (initialState { rsModule = Nothing }) testOptions (rsUniqState s) `shouldBe` 100 -- --------------------------------- it "contains the GhcT monad" $ do let comp = do s <- get parseSourceFileGhc "./TypeUtils/B.hs" g <- GHC.getModuleGraph gs <- mapM GHC.showModule g put (s {rsUniqState = 100}) return (gs) (r,_) <- ct $ runRefactGhc comp initialState testOptions (sort r) `shouldBe` ["TypeUtils.B ( TypeUtils/B.hs, nothing )", "TypeUtils.C ( TypeUtils/C.hs, nothing )"] -- ------------------------------------------------------------------- describe "RefactFlags" $ do it "puts the RefactDone flag through its paces" $ do let comp = do parseSourceFileGhc "./FreeAndDeclared/DeclareTypes.hs" v1 <- getRefactDone clearRefactDone v2 <- getRefactDone setRefactDone v3 <- getRefactDone return (v1,v2,v3) ((v1',v2',v3'), _s) <- ct $ runRefactGhc comp initialState testOptions (show (v1',v2',v3')) `shouldBe` "(False,False,True)" -- ------------------------------------------------------------------- describe "directoryManagement" $ do it "loads a file from a sub directory" $ do t <- ct $ parsedFileGhc "./FreeAndDeclared/DeclareS.hs" fileName <- canonicalizePath "./test/testdata/FreeAndDeclared/DeclareS.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let comp = do parseSourceFileGhc fileName r <- hsFreeAndDeclaredPNs parsed return r ((res),_s) <- cdAndDo "./test/testdata/FreeAndDeclared" $ runRefactGhc comp initialState testOptions -- Free Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (fst res)) `shouldBe` "[]" -- Declared Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (snd res)) `shouldBe` "[(FreeAndDeclared.DeclareS.c, (6, 1))]" -- ------------------------------------------------------------------- describe "stripCallStack" $ do it "strips a call stack from the end of an error string" $ do let s = "\nThe identifier is not a local function/pattern name!\nCallStack (from HasCallStack):\n error, called at ../src/Language/Haskell/Refact/Refactoring/MoveDef.hs:155:12 in main:Language.Haskell.Refact.Refactoring.MoveDef" (stripCallStack s) `shouldBe` "\nThe identifier is not a local function/pattern name!" it "noops if no call stack from the end of an error string" $ do let s = "\nThe identifier is not a local function/pattern name!" (stripCallStack s) `shouldBe` "\nThe identifier is not a local function/pattern name!" it "noops if no call stack from the end of an error string, trailing nl" $ do let s = "\nThe identifier is not a local function/pattern name!\n" (stripCallStack s) `shouldBe` "\nThe identifier is not a local function/pattern name!\n" -- ---------------------------------------------------------------------
RefactoringTools/HaRe
test/UtilsSpec.hs
bsd-3-clause
25,850
0
21
6,579
4,055
1,978
2,077
-1
-1
{-# LANGUAGE BangPatterns #-} foo = case v of !True -> x
bitemyapp/apply-refact
tests/examples/Structure17.hs
bsd-3-clause
57
1
8
12
21
9
12
2
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="hr-HR"> <title>Sequence Scanner | ZAP Extension</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>
kingthorin/zap-extensions
addOns/sequence/src/main/javahelp/org/zaproxy/zap/extension/sequence/resources/help_hr_HR/helpset_hr_HR.hs
apache-2.0
977
87
29
159
396
212
184
-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="el-GR"> <title>TreeTools</title> <maps> <homeID>treetools</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/treetools/src/main/javahelp/help_el_GR/helpset_el_GR.hs
apache-2.0
960
89
29
155
386
208
178
-1
-1
{-# LANGUAGE BangPatterns, RankNTypes, MagicHash, UnboxedTuples #-} module T5359a (linesT) where import GHC.Base import GHC.Word import GHC.ST (ST(..), runST) nullT :: Text -> Bool nullT (Text _ _ len) = len <= 0 {-# INLINE [1] nullT #-} spanT :: (Char -> Bool) -> Text -> (Text, Text) spanT p t@(Text arr off len) = (textP arr off k, textP arr (off+k) (len-k)) where k = loop 0 loop !i | i >= len || not (p c) = i | otherwise = loop (i+d) where Iter c d = iter t i {-# INLINE spanT #-} linesT :: Text -> [Text] linesT ps | nullT ps = [] | otherwise = h : if nullT t then [] else linesT (unsafeTail t) where (h,t) = spanT (/= '\n') ps {-# INLINE linesT #-} unsafeTail :: Text -> Text unsafeTail t@(Text arr off len) = Text arr (off+d) (len-d) where d = iter_ t 0 {-# INLINE unsafeTail #-} data Iter = Iter {-# UNPACK #-} !Char {-# UNPACK #-} !Int iter :: Text -> Int -> Iter iter (Text arr _ _) i = Iter (unsafeChrT m) 1 where m = unsafeIndex arr i {-# INLINE iter #-} iter_ :: Text -> Int -> Int iter_ (Text arr off _) i | m < 0xD800 || m > 0xDBFF = 1 | otherwise = 2 where m = unsafeIndex arr (off+i) {-# INLINE iter_ #-} data Text = Text {-# UNPACK #-}!Array {-# UNPACK #-}!Int {-# UNPACK #-}!Int text :: Array -> Int -> Int -> Text text arr off len = Text arr off len {-# INLINE text #-} emptyT :: Text emptyT = Text empty 0 0 {-# INLINE [1] emptyT #-} textP :: Array -> Int -> Int -> Text textP arr off len | len == 0 = emptyT | otherwise = text arr off len {-# INLINE textP #-} unsafeChrT :: Word16 -> Char unsafeChrT (W16# w#) = C# (chr# (word2Int# w#)) {-# INLINE unsafeChrT #-} data Array = Array ByteArray# data MArray s = MArray (MutableByteArray# s) new :: forall s. Int -> ST s (MArray s) new n@(I# len#) | n < 0 || n /= 0 = error $ "Data.Text.Array.new: size overflow" | otherwise = ST $ \s1# -> case newByteArray# len# s1# of (# s2#, marr# #) -> (# s2#, MArray marr# #) {-# INLINE new #-} unsafeFreeze :: MArray s -> ST s Array unsafeFreeze (MArray maBA) = ST $ \s# -> (# s#, Array (unsafeCoerce# maBA) #) {-# INLINE unsafeFreeze #-} unsafeIndex :: Array -> Int -> Word16 unsafeIndex (Array aBA) (I# i#) = case indexWord16Array# aBA i# of r# -> (W16# r#) {-# INLINE unsafeIndex #-} empty :: Array empty = runST (new 0 >>= unsafeFreeze)
frantisekfarka/ghc-dsi
testsuite/tests/simplCore/should_compile/T5359a.hs
bsd-3-clause
2,494
0
13
702
978
505
473
68
2
{-# LANGUAGE CPP, MagicHash #-} {-# OPTIONS_GHC -optc-DNON_POSIX_SOURCE #-} -- -- (c) The University of Glasgow 2002-2006 -- -- | ByteCodeItbls: Generate infotables for interpreter-made bytecodes module ByteCodeItbls ( ItblEnv, ItblPtr(..), itblCode, mkITbls, peekItbl , StgInfoTable(..) ) where #include "HsVersions.h" import DynFlags import Panic import Platform import Name ( Name, getName ) import NameEnv import DataCon ( DataCon, dataConRepArgTys, dataConIdentity ) import TyCon ( TyCon, tyConFamilySize, isDataTyCon, tyConDataCons ) import Type ( flattenRepType, repType, typePrimRep ) import StgCmmLayout ( mkVirtHeapOffsets ) import Util import Control.Monad import Control.Monad.Trans.Class import Control.Monad.Trans.State.Strict import Data.Maybe import Foreign import Foreign.C import GHC.Exts ( Int(I#), addr2Int# ) import GHC.Ptr ( FunPtr(..) ) {- Manufacturing of info tables for DataCons -} newtype ItblPtr = ItblPtr (Ptr ()) deriving Show itblCode :: DynFlags -> ItblPtr -> Ptr () itblCode dflags (ItblPtr ptr) | ghciTablesNextToCode = castPtr ptr `plusPtr` conInfoTableSizeB dflags | otherwise = castPtr ptr -- XXX bogus conInfoTableSizeB :: DynFlags -> Int conInfoTableSizeB dflags = 3 * wORD_SIZE dflags type ItblEnv = NameEnv (Name, ItblPtr) -- We need the Name in the range so we know which -- elements to filter out when unloading a module mkItblEnv :: [(Name,ItblPtr)] -> ItblEnv mkItblEnv pairs = mkNameEnv [(n, (n,p)) | (n,p) <- pairs] -- Make info tables for the data decls in this module mkITbls :: DynFlags -> [TyCon] -> IO ItblEnv mkITbls _ [] = return emptyNameEnv mkITbls dflags (tc:tcs) = do itbls <- mkITbl dflags tc itbls2 <- mkITbls dflags tcs return (itbls `plusNameEnv` itbls2) mkITbl :: DynFlags -> TyCon -> IO ItblEnv mkITbl dflags tc | not (isDataTyCon tc) = return emptyNameEnv | dcs `lengthIs` n -- paranoia; this is an assertion. = make_constr_itbls dflags dcs where dcs = tyConDataCons tc n = tyConFamilySize tc mkITbl _ _ = error "Unmatched patter in mkITbl: assertion failed!" #include "../includes/rts/storage/ClosureTypes.h" cONSTR :: Int -- Defined in ClosureTypes.h cONSTR = CONSTR -- Assumes constructors are numbered from zero, not one make_constr_itbls :: DynFlags -> [DataCon] -> IO ItblEnv make_constr_itbls dflags cons = do is <- mapM mk_dirret_itbl (zip cons [0..]) return (mkItblEnv is) where mk_dirret_itbl (dcon, conNo) = mk_itbl dcon conNo stg_interp_constr_entry mk_itbl :: DataCon -> Int -> EntryFunPtr -> IO (Name,ItblPtr) mk_itbl dcon conNo entry_addr = do let rep_args = [ (typePrimRep rep_arg,rep_arg) | arg <- dataConRepArgTys dcon, rep_arg <- flattenRepType (repType arg) ] (tot_wds, ptr_wds, _) = mkVirtHeapOffsets dflags False{-not a THUNK-} rep_args ptrs' = ptr_wds nptrs' = tot_wds - ptr_wds nptrs_really | ptrs' + nptrs' >= mIN_PAYLOAD_SIZE dflags = nptrs' | otherwise = mIN_PAYLOAD_SIZE dflags - ptrs' code' = mkJumpToAddr dflags entry_addr itbl = StgInfoTable { entry = if ghciTablesNextToCode then Nothing else Just entry_addr, ptrs = fromIntegral ptrs', nptrs = fromIntegral nptrs_really, tipe = fromIntegral cONSTR, srtlen = fromIntegral conNo, code = if ghciTablesNextToCode then Just code' else Nothing } -- Make a piece of code to jump to "entry_label". -- This is the only arch-dependent bit. addrCon <- newExecConItbl dflags itbl (dataConIdentity dcon) --putStrLn ("SIZE of itbl is " ++ show (sizeOf itbl)) --putStrLn ("# ptrs of itbl is " ++ show ptrs) --putStrLn ("# nptrs of itbl is " ++ show nptrs_really) return (getName dcon, ItblPtr (castFunPtrToPtr addrCon)) -- Make code which causes a jump to the given address. This is the -- only arch-dependent bit of the itbl story. -- For sparc_TARGET_ARCH, i386_TARGET_ARCH, etc. #include "nativeGen/NCG.h" type ItblCodes = Either [Word8] [Word32] funPtrToInt :: FunPtr a -> Int funPtrToInt (FunPtr a#) = I# (addr2Int# a#) mkJumpToAddr :: DynFlags -> EntryFunPtr -> ItblCodes mkJumpToAddr dflags a = case platformArch (targetPlatform dflags) of ArchSPARC -> -- After some consideration, we'll try this, where -- 0x55555555 stands in for the address to jump to. -- According to includes/rts/MachRegs.h, %g3 is very -- likely indeed to be baggable. -- -- 0000 07155555 sethi %hi(0x55555555), %g3 -- 0004 8610E155 or %g3, %lo(0x55555555), %g3 -- 0008 81C0C000 jmp %g3 -- 000c 01000000 nop let w32 = fromIntegral (funPtrToInt a) hi22, lo10 :: Word32 -> Word32 lo10 x = x .&. 0x3FF hi22 x = (x `shiftR` 10) .&. 0x3FFFF in Right [ 0x07000000 .|. (hi22 w32), 0x8610E000 .|. (lo10 w32), 0x81C0C000, 0x01000000 ] ArchPPC -> -- We'll use r12, for no particular reason. -- 0xDEADBEEF stands for the address: -- 3D80DEAD lis r12,0xDEAD -- 618CBEEF ori r12,r12,0xBEEF -- 7D8903A6 mtctr r12 -- 4E800420 bctr let w32 = fromIntegral (funPtrToInt a) hi16 x = (x `shiftR` 16) .&. 0xFFFF lo16 x = x .&. 0xFFFF in Right [ 0x3D800000 .|. hi16 w32, 0x618C0000 .|. lo16 w32, 0x7D8903A6, 0x4E800420 ] ArchX86 -> -- Let the address to jump to be 0xWWXXYYZZ. -- Generate movl $0xWWXXYYZZ,%eax ; jmp *%eax -- which is -- B8 ZZ YY XX WW FF E0 let w32 = fromIntegral (funPtrToInt a) :: Word32 insnBytes :: [Word8] insnBytes = [0xB8, byte0 w32, byte1 w32, byte2 w32, byte3 w32, 0xFF, 0xE0] in Left insnBytes ArchX86_64 -> -- Generates: -- jmpq *.L1(%rip) -- .align 8 -- .L1: -- .quad <addr> -- -- which looks like: -- 8: ff 25 02 00 00 00 jmpq *0x2(%rip) # 10 <f+0x10> -- with addr at 10. -- -- We need a full 64-bit pointer (we can't assume the info table is -- allocated in low memory). Assuming the info pointer is aligned to -- an 8-byte boundary, the addr will also be aligned. let w64 = fromIntegral (funPtrToInt a) :: Word64 insnBytes :: [Word8] insnBytes = [0xff, 0x25, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, byte0 w64, byte1 w64, byte2 w64, byte3 w64, byte4 w64, byte5 w64, byte6 w64, byte7 w64] in Left insnBytes ArchAlpha -> let w64 = fromIntegral (funPtrToInt a) :: Word64 in Right [ 0xc3800000 -- br at, .+4 , 0xa79c000c -- ldq at, 12(at) , 0x6bfc0000 -- jmp (at) # with zero hint -- oh well , 0x47ff041f -- nop , fromIntegral (w64 .&. 0x0000FFFF) , fromIntegral ((w64 `shiftR` 32) .&. 0x0000FFFF) ] ArchARM { } -> -- Generates Thumb sequence, -- ldr r1, [pc, #0] -- bx r1 -- -- which looks like: -- 00000000 <.addr-0x8>: -- 0: 4900 ldr r1, [pc] ; 8 <.addr> -- 4: 4708 bx r1 let w32 = fromIntegral (funPtrToInt a) :: Word32 in Left [ 0x49, 0x00 , 0x47, 0x08 , byte0 w32, byte1 w32, byte2 w32, byte3 w32] arch -> panic ("mkJumpToAddr not defined for " ++ show arch) byte0 :: (Integral w) => w -> Word8 byte0 w = fromIntegral w byte1, byte2, byte3, byte4, byte5, byte6, byte7 :: (Integral w, Bits w) => w -> Word8 byte1 w = fromIntegral (w `shiftR` 8) byte2 w = fromIntegral (w `shiftR` 16) byte3 w = fromIntegral (w `shiftR` 24) byte4 w = fromIntegral (w `shiftR` 32) byte5 w = fromIntegral (w `shiftR` 40) byte6 w = fromIntegral (w `shiftR` 48) byte7 w = fromIntegral (w `shiftR` 56) -- entry point for direct returns for created constr itbls foreign import ccall "&stg_interp_constr_entry" stg_interp_constr_entry :: EntryFunPtr -- Ultra-minimalist version specially for constructors #if SIZEOF_VOID_P == 8 type HalfWord = Word32 #else type HalfWord = Word16 #endif data StgConInfoTable = StgConInfoTable { conDesc :: Ptr Word8, infoTable :: StgInfoTable } sizeOfConItbl :: DynFlags -> StgConInfoTable -> Int sizeOfConItbl dflags conInfoTable = sum [ fieldSz conDesc conInfoTable , sizeOfItbl dflags (infoTable conInfoTable) ] pokeConItbl :: DynFlags -> Ptr StgConInfoTable -> Ptr StgConInfoTable -> StgConInfoTable -> IO () pokeConItbl dflags wr_ptr ex_ptr itbl = flip evalStateT (castPtr wr_ptr) $ do when ghciTablesNextToCode $ do let con_desc = conDesc itbl `minusPtr` (ex_ptr `plusPtr` conInfoTableSizeB dflags) store (fromIntegral con_desc :: Word32) when (wORD_SIZE dflags == 8) $ store (fromIntegral con_desc :: Word32) store' (sizeOfItbl dflags) (pokeItbl dflags) (infoTable itbl) unless ghciTablesNextToCode $ store (conDesc itbl) type EntryFunPtr = FunPtr (Ptr () -> IO (Ptr ())) data StgInfoTable = StgInfoTable { entry :: Maybe EntryFunPtr, -- Just <=> not ghciTablesNextToCode ptrs :: HalfWord, nptrs :: HalfWord, tipe :: HalfWord, srtlen :: HalfWord, code :: Maybe ItblCodes -- Just <=> ghciTablesNextToCode } sizeOfItbl :: DynFlags -> StgInfoTable -> Int sizeOfItbl dflags itbl = sum [ if ghciTablesNextToCode then 0 else fieldSz (fromJust . entry) itbl, fieldSz ptrs itbl, fieldSz nptrs itbl, fieldSz tipe itbl, fieldSz srtlen itbl, if ghciTablesNextToCode then case mkJumpToAddr dflags undefined of Left xs -> sizeOf (head xs) * length xs Right xs -> sizeOf (head xs) * length xs else 0 ] pokeItbl :: DynFlags -> Ptr StgInfoTable -> StgInfoTable -> IO () pokeItbl _ a0 itbl = flip evalStateT (castPtr a0) $ do case entry itbl of Nothing -> return () Just e -> store e store (ptrs itbl) store (nptrs itbl) store (tipe itbl) store (srtlen itbl) case code itbl of Nothing -> return () Just (Left xs) -> mapM_ store xs Just (Right xs) -> mapM_ store xs peekItbl :: DynFlags -> Ptr StgInfoTable -> IO StgInfoTable peekItbl dflags a0 = flip evalStateT (castPtr a0) $ do entry' <- if ghciTablesNextToCode then return Nothing else liftM Just load ptrs' <- load nptrs' <- load tipe' <- load srtlen' <- load code' <- if ghciTablesNextToCode then liftM Just $ case mkJumpToAddr dflags undefined of Left xs -> liftM Left $ sequence (replicate (length xs) load) Right xs -> liftM Right $ sequence (replicate (length xs) load) else return Nothing return StgInfoTable { entry = entry', ptrs = ptrs', nptrs = nptrs', tipe = tipe', srtlen = srtlen' ,code = code' } fieldSz :: Storable b => (a -> b) -> a -> Int fieldSz sel x = sizeOf (sel x) type PtrIO = StateT (Ptr Word8) IO advance :: Storable a => PtrIO (Ptr a) advance = advance' sizeOf advance' :: (a -> Int) -> PtrIO (Ptr a) advance' fSizeOf = state adv where adv addr = case castPtr addr of addrCast -> (addrCast, addr `plusPtr` sizeOfPointee fSizeOf addrCast) sizeOfPointee :: (a -> Int) -> Ptr a -> Int sizeOfPointee fSizeOf addr = fSizeOf (typeHack addr) where typeHack = undefined :: Ptr a -> a store :: Storable a => a -> PtrIO () store = store' sizeOf poke store' :: (a -> Int) -> (Ptr a -> a -> IO ()) -> a -> PtrIO () store' fSizeOf fPoke x = do addr <- advance' fSizeOf lift (fPoke addr x) load :: Storable a => PtrIO a load = do addr <- advance lift (peek addr) newExecConItbl :: DynFlags -> StgInfoTable -> [Word8] -> IO (FunPtr ()) newExecConItbl dflags obj con_desc = alloca $ \pcode -> do let lcon_desc = length con_desc + 1{- null terminator -} dummy_cinfo = StgConInfoTable { conDesc = nullPtr, infoTable = obj } sz = fromIntegral (sizeOfConItbl dflags dummy_cinfo) -- Note: we need to allocate the conDesc string next to the info -- table, because on a 64-bit platform we reference this string -- with a 32-bit offset relative to the info table, so if we -- allocated the string separately it might be out of range. wr_ptr <- _allocateExec (sz + fromIntegral lcon_desc) pcode ex_ptr <- peek pcode let cinfo = StgConInfoTable { conDesc = ex_ptr `plusPtr` fromIntegral sz , infoTable = obj } pokeConItbl dflags wr_ptr ex_ptr cinfo pokeArray0 0 (castPtr wr_ptr `plusPtr` fromIntegral sz) con_desc _flushExec sz ex_ptr -- Cache flush (if needed) return (castPtrToFunPtr ex_ptr) foreign import ccall unsafe "allocateExec" _allocateExec :: CUInt -> Ptr (Ptr a) -> IO (Ptr a) foreign import ccall unsafe "flushExec" _flushExec :: CUInt -> Ptr a -> IO ()
urbanslug/ghc
compiler/ghci/ByteCodeItbls.hs
bsd-3-clause
14,828
0
19
5,270
3,490
1,838
1,652
265
7
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} module SingletonsBug where import Control.Applicative import Data.Traversable (for) import GHC.Exts( Constraint ) ----------------------------------- -- From 'constraints' library -- import Data.Constraint (Dict(..)) data Dict :: Constraint -> * where Dict :: a => Dict a ----------------------------------- -- From 'singletons' library -- import Data.Singletons hiding( withSomeSing ) class SingI (a :: k) where -- | Produce the singleton explicitly. You will likely need the @ScopedTypeVariables@ -- extension to use this method the way you want. sing :: Sing a data family Sing (a :: k) data KProxy (a :: *) = KProxy data SomeSing (kproxy :: KProxy k) where SomeSing :: Sing (a :: k) -> SomeSing ('KProxy :: KProxy k) -- SingKind :: forall k. KProxy k -> Constraint class (kparam ~ 'KProxy) => SingKind (kparam :: KProxy k) where -- | Get a base type from a proxy for the promoted kind. For example, -- @DemoteRep ('KProxy :: KProxy Bool)@ will be the type @Bool@. type DemoteRep kparam :: * -- | Convert a singleton to its unrefined version. fromSing :: Sing (a :: k) -> DemoteRep kparam -- | Convert an unrefined type to an existentially-quantified singleton type. toSing :: DemoteRep kparam -> SomeSing kparam withSomeSing :: SingKind ('KProxy :: KProxy k) => DemoteRep ('KProxy :: KProxy k) -> (forall (a :: k). Sing a -> r) -> r withSomeSing _ _ = error "urk" ----------------------------------- data SubscriptionChannel = BookingsChannel type BookingsChannelSym0 = BookingsChannel data instance Sing (z_a5I7 :: SubscriptionChannel) where SBookingsChannel :: Sing BookingsChannel instance SingKind ('KProxy :: KProxy SubscriptionChannel) where type DemoteRep ('KProxy :: KProxy SubscriptionChannel) = SubscriptionChannel fromSing SBookingsChannel = BookingsChannel toSing BookingsChannel = SomeSing SBookingsChannel instance SingI BookingsChannel where sing = SBookingsChannel type family T (c :: SubscriptionChannel) :: * type instance T 'BookingsChannel = Bool witnessC :: Sing channel -> Dict (Show (T channel), SingI channel) witnessC SBookingsChannel = Dict forAllSubscriptionChannels :: forall m r. (Applicative m) => (forall channel. (SingI channel, Show (T channel)) => Sing channel -> m r) -> m r forAllSubscriptionChannels f = withSomeSing BookingsChannel $ \(sChannel) -> case witnessC sChannel of Dict -> f sChannel
shlevy/ghc
testsuite/tests/indexed-types/should_compile/T9316.hs
bsd-3-clause
2,804
5
13
503
610
340
270
54
1
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE ViewPatterns #-} {- Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.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 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.Reader.Odt.Generic.Utils Copyright : Copyright (C) 2015 Martin Linnemann License : GNU GPL, version 2 or above Maintainer : Martin Linnemann <theCodingMarlin@googlemail.com> Stability : alpha Portability : portable General utility functions for the odt reader. -} module Text.Pandoc.Readers.Odt.Generic.Utils ( uncurry3 , uncurry4 , uncurry5 , uncurry6 , uncurry7 , uncurry8 , swap , reverseComposition , bool , tryToRead , Lookupable(..) , readLookupables , readLookupable , readPercent , findBy , swing , composition ) where import Control.Category ( Category, (>>>), (<<<) ) import qualified Control.Category as Cat ( id ) import Control.Monad ( msum ) import qualified Data.Foldable as F ( Foldable, foldr ) import Data.Maybe -- | Aequivalent to -- > foldr (.) id -- where '(.)' are 'id' are the ones from "Control.Category" -- and 'foldr' is the one from "Data.Foldable". -- The noun-form was chosen to be consistend with 'sum', 'product' etc -- based on the discussion at -- <https://groups.google.com/forum/#!topic/haskell-cafe/VkOZM1zaHOI> -- (that I was not part of) composition :: (Category cat, F.Foldable f) => f (cat a a) -> cat a a composition = F.foldr (<<<) Cat.id -- | Aequivalent to -- > foldr (flip (.)) id -- where '(.)' are 'id' are the ones from "Control.Category" -- and 'foldr' is the one from "Data.Foldable". -- A reversed version of 'composition'. reverseComposition :: (Category cat, F.Foldable f) => f (cat a a) -> cat a a reverseComposition = F.foldr (>>>) Cat.id -- | 'Either' has 'either', 'Maybe' has 'maybe'. 'Bool' should have 'bool'. -- Note that the first value is selected if the boolean value is 'False'. -- That makes 'bool' consistent with the other two. Also, 'bool' now takes its -- arguments in the exact opposite order compared to the normal if construct. bool :: a -> a -> Bool -> a bool x _ False = x bool _ x True = x -- | This function often makes it possible to switch values with the functions -- that are applied to them. -- -- Examples: -- > swing map :: [a -> b] -> a -> [b] -- > swing any :: [a -> Bool] -> a -> Bool -- > swing foldr :: b -> a -> [a -> b -> b] -> b -- > swing scanr :: c -> a -> [a -> c -> c] -> c -- > swing zipWith :: [a -> b -> c] -> a -> [b] -> [c] -- > swing find :: [a -> Bool] -> a -> Maybe (a -> Bool) -- -- Stolen from <https://wiki.haskell.org/Pointfree> swing :: (((a -> b) -> b) -> c -> d) -> c -> a -> d swing = flip.(.flip id) -- swing f c a = f ($ a) c -- | Alternative to 'read'/'reads'. The former of these throws errors -- (nobody wants that) while the latter returns "to much" for simple purposes. -- This function instead applies 'reads' and returns the first match (if any) -- in a 'Maybe'. tryToRead :: (Read r) => String -> Maybe r tryToRead = reads >>> listToMaybe >>> fmap fst -- | A version of 'reads' that requires a '%' sign after the number readPercent :: ReadS Int readPercent s = [ (i,s') | (i , r ) <- reads s , ("%" , s') <- lex r ] -- | Data that can be looked up. -- This is mostly a utility to read data with kind *. class Lookupable a where lookupTable :: [(String, a)] -- | The idea is to use this function as if there was a declaration like -- -- > instance (Lookupable a) => (Read a) where -- > readsPrec _ = readLookupables -- . -- But including this code in this form would need UndecideableInstances. -- That is a bad idea. Luckily 'readLookupable' (without the s at the end) -- can be used directly in almost any case. readLookupables :: (Lookupable a) => String -> [(a,String)] readLookupables s = [ (a,rest) | (word,rest) <- lex s, let result = lookup word lookupTable, isJust result, let Just a = result ] -- | Very similar to a simple 'lookup' in the 'lookupTable', but with a lexer. readLookupable :: (Lookupable a) => String -> Maybe a readLookupable s = msum $ map ((`lookup` lookupTable).fst) $ lex s uncurry3 :: (a->b->c -> z) -> (a,b,c ) -> z uncurry4 :: (a->b->c->d -> z) -> (a,b,c,d ) -> z uncurry5 :: (a->b->c->d->e -> z) -> (a,b,c,d,e ) -> z uncurry6 :: (a->b->c->d->e->f -> z) -> (a,b,c,d,e,f ) -> z uncurry7 :: (a->b->c->d->e->f->g -> z) -> (a,b,c,d,e,f,g ) -> z uncurry8 :: (a->b->c->d->e->f->g->h -> z) -> (a,b,c,d,e,f,g,h) -> z uncurry3 fun (a,b,c ) = fun a b c uncurry4 fun (a,b,c,d ) = fun a b c d uncurry5 fun (a,b,c,d,e ) = fun a b c d e uncurry6 fun (a,b,c,d,e,f ) = fun a b c d e f uncurry7 fun (a,b,c,d,e,f,g ) = fun a b c d e f g uncurry8 fun (a,b,c,d,e,f,g,h) = fun a b c d e f g h swap :: (a,b) -> (b,a) swap (a,b) = (b,a) -- | A version of "Data.List.find" that uses a converter to a Maybe instance. -- The returned value is the first which the converter returns in a 'Just' -- wrapper. findBy :: (a -> Maybe b) -> [a] -> Maybe b findBy _ [] = Nothing findBy f ((f -> Just x):_ ) = Just x findBy f ( _:xs) = findBy f xs
gbataille/pandoc
src/Text/Pandoc/Readers/Odt/Generic/Utils.hs
gpl-2.0
6,112
2
14
1,504
1,362
786
576
70
1
module Level1 where l1 = undefined :: ()
ezyang/ghc
testsuite/tests/ghci/prog015/Level1.hs
bsd-3-clause
42
0
5
9
14
9
5
2
1
data Foo = Foo {x :: Int, str :: String} deriving (Eq, Read, Show, Ord) -- instance Eq Foo where -- (==) (Foo x1 s1) (Foo x2 s2) = (x1 == x2) && (s1 == s2)
fredmorcos/attic
snippets/haskell/classes.hs
isc
164
1
8
44
41
25
16
2
0
{-# OPTIONS_HADDOCK hide, prune #-} module Handler.Mooc.ExpertReview ( postWriteExpertReviewR , writeExpertReview , viewExpertReviews ) where import Control.Monad.Trans.Except import Import import Import.Util import Application.Grading import Application.Edx postWriteExpertReviewR :: ScenarioId -> Handler Value postWriteExpertReviewR scId = runJSONExceptT $ do userId <- maybeE "You must login to review." maybeAuthId grade <- maybeE "You must specify a grade." $ liftM (>>= readMay) $ lookupPostParam "grade" comment <- lift $ fromMaybe "" <$> lookupPostParam "comment" t <- liftIO getCurrentTime ExceptT $ runDB $ runExceptT $ do scenario <- maybeE "Cannot find a corresponding scenario." $ get scId when (userId == scenarioAuthorId scenario) $ throwE "You cannot review yourself!" when (length comment < 80) $ throwE "Comment needs to be at least 80 characters." _ <- lift $ upsert (ExpertReview userId scId comment grade t) [ ExpertReviewGrade =. grade , ExpertReviewComment =. comment , ExpertReviewTimestamp =. t ] -- expert grade overrules votes and thus overwrites existing grade lift $ updateCurrentScenarioGrade scId -- queue new grade for sending to edX lift $ queueDesignGrade scId return $ object [ "grade" .= grade , "comment" .= comment , "timestamp" .= t ] viewExpertReviews :: ScenarioId -> Handler Widget viewExpertReviews scId = do reviews <- runDB $ selectList [ExpertReviewScenarioId ==. scId] [] reviewsAndUsers <- forM reviews $ \(Entity _ r) -> do mReviewer <- runDB $ get $ expertReviewReviewerId r return (r, mReviewer) let avgGrade = (fromIntegral $ sum grades) / (fromIntegral $ length reviews) :: Double where extrGrade (Entity _ r) = expertReviewGrade r grades = map extrGrade reviews return $ do let stars review = let grade = expertReviewGrade review in mconcat $ (replicate grade [whamlet|<span.icon.icon-lg>star</span>|]) ++ replicate (5 - grade) [whamlet|<span.icon.icon-lg>star_border</span>|] [whamlet| $if not $ null reviews <div.comment-table> #{length reviewsAndUsers} grade(s) with an average of #{ avgGrade } stars $forall (review, mReviewer) <- reviewsAndUsers <div.card-comment.card> <div.card-comment.card-main> <div.card-comment.card-inner> <div> ^{ stars review } #{ formatTime defaultTimeLocale "%Y.%m.%d - %H:%M " $ expertReviewTimestamp review } $maybe reviewer <- mReviewer - #{userName reviewer} #{expertReviewComment review} |] writeExpertReview :: UserId -> ScenarioId -> Handler Widget writeExpertReview userId scId = do reviewExists <- liftM isJust $ runDB $ getBy $ ExpertReviewOf userId scId return $ do let starNrs = [1..5]::[Int] [whamlet| <div.comment-table #writeExpertReviewTable> <div.card-comment.card> <div.card-comment.card-main> <div.card-comment.card-inner> $if reviewExists <div class="alert alert-danger"> Replace the grade you previously submitted for this version: <div.card-comment.form-group.form-group-label> <label.floating-label for="commentER">Comments... <textarea.form-control.textarea-autosize #commentER rows="1" name="comment"> <div .expertReviewStars> $forall i <- starNrs <span.icon.icon-lg.reviewStar data-starid="#{ i }">star_border</span> <a.btn.btn-flat #submitExpertReview>Grade</a> |] toWidgetHead [cassius| .expertReviewStars .icon cursor: pointer; |] toWidgetHead [julius| $(function(){ var grade , commentField = $('#commentER')[0] ; $('.reviewStar').click(function(e){ var starId = e.target.getAttribute('data-starid'); grade = starId; $('.reviewStar').each(function(){ if (parseInt( this.getAttribute('data-starid') ) <= starId) { this.innerHTML = 'star'; } else { this.innerHTML = 'star_border'; } }); }); $('#submitExpertReview').click(function(e){ if (grade && commentField.value.length > 80) { $.post( { url: '@{WriteExpertReviewR scId}' , data: { grade: grade , comment: commentField.value } , success: function(result){ $('#writeExpertReviewTable').remove(); $("body").snackbar({ content: (result.error ? result.error : "Review sent. Refresh the page to see it.") }); } }); } else { alert('Please rate this design by clicking a star and add at least 80 characters of text before submitting.'); } }); }); |]
mb21/qua-kit
apps/hs/qua-server/src/Handler/Mooc/ExpertReview.hs
mit
5,415
0
18
1,815
673
337
336
-1
-1
module Homework.Week09Spec ( main, spec ) where import Test.Hspec import Homework.Week09.Assignment main :: IO () main = hspec spec spec :: Spec spec = do describe "week 9" $ do it "needs some tests!" $ do pending
jxv/cis-194-winter-2016
test/Homework/Week09Spec.hs
mit
233
0
12
56
76
40
36
12
1
{-# LANGUAGE PackageImports #-} import "haskell-src-exts" Language.Haskell.Exts main = undefined
Pnom/haskell-ast-pretty
Test/examples/PackageImport.hs
mit
98
1
5
11
18
9
9
3
1
main = print . length $ concatMap say [1..999] ++ "onethousand" say :: Int -> String say n = putAnd (hundreds h) (two [o, t]) where (o:t:h:_) = reverse (show n) ++ repeat '0' putAnd "" b = b putAnd a "" = a putAnd a b = a ++ "and" ++ b two "00" = "" two [o,'0'] = ones o two "01" = "ten" two "11" = "eleven" two "21" = "twelve" two "31" = "thirteen" two "41" = "fourteen" two "51" = "fifteen" two "61" = "sixteen" two "71" = "seventeen" two "81" = "eighteen" two "91" = "nineteen" two [o, t ] = tens t ++ ones o -- ones place ones '0' = "" ones '1' = "one" ones '2' = "two" ones '3' = "three" ones '4' = "four" ones '5' = "five" ones '6' = "six" ones '7' = "seven" ones '8' = "eight" ones '9' = "nine" tens '2' = "twenty" tens '3' = "thirty" tens '4' = "forty" tens '5' = "fifty" tens '6' = "sixty" tens '7' = "seventy" tens '8' = "eighty" tens '9' = "ninety" hundreds '0' = "" hundreds h = ones h ++ "hundred"
nickspinale/euler
complete/017.hs
mit
922
2
8
209
487
223
264
40
1
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Hadoop.Protos.ClientNamenodeProtocolProtos.MetaSaveResponseProto (MetaSaveResponseProto(..)) where import Prelude ((+), (/)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data MetaSaveResponseProto = MetaSaveResponseProto{} deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data) instance P'.Mergeable MetaSaveResponseProto where mergeAppend MetaSaveResponseProto MetaSaveResponseProto = MetaSaveResponseProto instance P'.Default MetaSaveResponseProto where defaultValue = MetaSaveResponseProto instance P'.Wire MetaSaveResponseProto where wireSize ft' self'@(MetaSaveResponseProto) = case ft' of 10 -> calc'Size 11 -> P'.prependMessageSize calc'Size _ -> P'.wireSizeErr ft' self' where calc'Size = 0 wirePut ft' self'@(MetaSaveResponseProto) = case ft' of 10 -> put'Fields 11 -> do P'.putSize (P'.wireSize 10 self') put'Fields _ -> P'.wirePutErr ft' self' where put'Fields = do Prelude'.return () wireGet ft' = case ft' of 10 -> P'.getBareMessageWith update'Self 11 -> P'.getMessageWith update'Self _ -> P'.wireGetErr ft' where update'Self wire'Tag old'Self = case wire'Tag of _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self instance P'.MessageAPI msg' (msg' -> MetaSaveResponseProto) MetaSaveResponseProto where getVal m' f' = f' m' instance P'.GPB MetaSaveResponseProto instance P'.ReflectDescriptor MetaSaveResponseProto where getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList []) reflectDescriptorInfo _ = Prelude'.read "DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.hdfs.MetaSaveResponseProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"ClientNamenodeProtocolProtos\"], baseName = MName \"MetaSaveResponseProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"ClientNamenodeProtocolProtos\",\"MetaSaveResponseProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}" instance P'.TextType MetaSaveResponseProto where tellT = P'.tellSubMessage getT = P'.getSubMessage instance P'.TextMsg MetaSaveResponseProto where textPut msg = Prelude'.return () textGet = Prelude'.return P'.defaultValue
alexbiehl/hoop
hadoop-protos/src/Hadoop/Protos/ClientNamenodeProtocolProtos/MetaSaveResponseProto.hs
mit
2,861
1
16
531
554
291
263
53
0
module Light.Geometry.VectorTest (tests) where import Test.Framework (Test) import Test.Framework.Providers.QuickCheck2 (testProperty) import qualified Test.QuickCheck as QC import Light.Geometry.Vector instance QC.Arbitrary Vector where arbitrary = QC.vector 3 >>= \ [a, b, c] -> return $ Vector a b c prop_VectorAdditiveIdentity :: Vector -> Bool prop_VectorAdditiveIdentity v = v == (v ^+^ zeroVector) && v == (v ^-^ zeroVector) prop_MultiplicativeIdentity :: Vector -> Bool prop_MultiplicativeIdentity v = (v ^* 1) == v && (1 *^ v) == v && (v ^/ 1) == v prop_MultiplicativeCommutivity :: Vector -> Double -> Bool prop_MultiplicativeCommutivity v s = (v ^* s) == (s *^ v) prop_MultiplicationIsRepeatedAddition :: Vector -> Bool prop_MultiplicationIsRepeatedAddition v = (v ^* 2) == (v ^+^ v) && (v ^* 3) == (v ^+^ v ^+^ v) prop_DotProductCommutivity :: Vector -> Vector -> Bool prop_DotProductCommutivity v w = v ^.^ w == w ^.^ v prop_DoubleNegation :: Vector -> Bool prop_DoubleNegation v = negateV (negateV v) == v prop_NormalizeIsUnitLength :: Vector -> Bool prop_NormalizeIsUnitLength v = v == zeroVector || abs (magnitudeV (normalizeV v) - 1) < 0.000001 prop_ScalarMultiplicationIsMagnitude :: Double -> Bool prop_ScalarMultiplicationIsMagnitude s = abs (magnitudeV (Vector 1 0 0 ^* s) - abs s) < 0.000001 prop_CrossProductIsOrthogonal :: Vector -> Vector -> Bool prop_CrossProductIsOrthogonal u v = u == zeroVector || v == zeroVector || ( abs (cross (normalizeV u) (normalizeV v) ^.^ u) < 0.000001 && abs (cross (normalizeV u) (normalizeV v) ^.^ v) < 0.000001 ) tests :: [Test] tests = [ testProperty "VectorAdditiveIdentity" prop_VectorAdditiveIdentity , testProperty "MultiplicativeIdentity" prop_MultiplicativeIdentity , testProperty "MultiplicativeCommutivity" prop_MultiplicativeCommutivity , testProperty "MultiplicationIsRepeatedAddition" prop_MultiplicationIsRepeatedAddition , testProperty "DotProductCommutivity" prop_DotProductCommutivity , testProperty "DoubleNegation" prop_DoubleNegation , testProperty "NormalizeIsUnitLength" prop_NormalizeIsUnitLength , testProperty "ScalarMultiplicationIsMagnitude" prop_ScalarMultiplicationIsMagnitude , testProperty "CrossProductIsOrthogonal" prop_CrossProductIsOrthogonal ]
jtdubs/Light
testsuite/Light/Geometry/VectorTest.hs
mit
2,551
0
15
594
657
347
310
42
1
{-# LANGUAGE MultiParamTypeClasses , OverloadedStrings #-} module Data.API.LinkedIn.Profile ( ProfileQuery(..) , ProfileResult(..) , CurrentShare(..) , ShareVisibility(..) , ShareSource(..) , ShareAuthor(..) , SiteStandardProfileRequest(..) ) where import Data.API.LinkedIn.Query import Data.API.LinkedIn.QueryResponsePair import Data.API.LinkedIn.Response --import Network.API.LinkedIn --temp --import Network.API.ShimToken --temp import Text.XML.Stream.Parse.Skip --temp import Prelude hiding (concat) import Control.Applicative ((<$>), (<*>)) import Control.Monad (join) import Data.Conduit (MonadThrow, Sink) import Data.Default (Default(..)) import Data.Foldable (concat) import Data.List (intercalate) import Data.Text (Text, pack, unpack) import Data.XML.Types (Event, Name(..)) import Text.XML.Stream.Parse data ProfileQuery = ProfileQuery { queryMemberId :: Text , fieldSelectors :: [ProfileFieldSelector] } deriving (Show) instance Default ProfileQuery where def = ProfileQuery "" allProfileFieldSelectors instance Query ProfileQuery where toPathSegments q = ["people" , foldr (++) "" [ "id=" , (unpack $ queryMemberId q) , ":" , (formatSelectors $ fieldSelectors q) ] ] toQueryItems = const [] data ProfileResult = ProfileResult { profileId :: Maybe Text , firstName :: Maybe Text , lastName :: Maybe Text , maidenName :: Maybe Text , formattedName :: Maybe Text , phoneticFirstName :: Maybe Text , phoneticLastName :: Maybe Text , formattedPhoneticName :: Maybe Text , headline :: Maybe Text , industry :: Maybe Text , distance :: Maybe Integer , lastModifiedTimestamp :: Maybe Integer , currentShare :: Maybe CurrentShare , profileNetwork :: Maybe ProfileNetwork , numConnections :: Maybe Integer , numConnectionsCapped :: Maybe Bool , profileSummary :: Maybe Text , profileSpecialties :: Maybe Text , proposalComments :: Maybe Text , profileAssociations :: Maybe Text , profileHonors :: Maybe Text , profileInterests :: Maybe Text , siteStandardProfileRequest :: Maybe SiteStandardProfileRequest } deriving (Show) instance Response ProfileResult where parsePage = tagNoAttr "person" $ ProfileResult <$> tagNoAttr (toName IdS) content <*> tagNoAttr (toName FirstNameS) content <*> tagNoAttr (toName LastNameS) content <*> tagNoAttr (toName MaidenNameS) content <*> tagNoAttr (toName FormattedNameS) content <*> tagNoAttr (toName PhoneticFirstNameS) content <*> tagNoAttr (toName PhoneticLastNameS) content <*> tagNoAttr (toName FormattedPhoneticNameS) content <*> tagNoAttr (toName HeadlineS) content <*> tagNoAttr (toName IndustryS) content <*> (fmap (fmap (read . unpack)) $ tagNoAttr (toName DistanceS) content) <*> (fmap (fmap (read . unpack)) $ tagNoAttr (toName LastModifiedTimestampS) content) <*> parseCurrentShare <*> parseProfileNetwork <*> (fmap (fmap (read . unpack)) $ tagNoAttr (toName NumConnectionsS) content) <*> (fmap (fmap ("true"==)) $ tagNoAttr (toName NumConnectionsCappedS) content) <*> (fmap join $ tagNoAttr (toName SummaryS) contentMaybe) <*> (fmap join $ tagNoAttr (toName SpecialtiesS) contentMaybe) <*> (fmap join $ tagNoAttr (toName ProposalCommentsS) contentMaybe) <*> (fmap join $ tagNoAttr (toName AssociationsS) contentMaybe) <*> (fmap join $ tagNoAttr (toName HonorsS) contentMaybe) <*> (fmap join $ tagNoAttr (toName InterestsS) contentMaybe) <*> parseSiteStandardProfileRequest instance QueryResponsePair ProfileQuery ProfileResult data SiteStandardProfileRequest = SiteStandardProfileRequest { siteStandardProfileRequestUrl :: Text } deriving (Show) parseSiteStandardProfileRequest :: MonadThrow m => Sink Event m (Maybe SiteStandardProfileRequest) parseSiteStandardProfileRequest = tagNoAttr "site-standard-profile-request" $ SiteStandardProfileRequest <$> (force "site-standard-profile-request must contain an url" $ tagNoAttr "url" content) data CurrentShare = CurrentShare { shareId :: Text , shareTimestamp :: Integer , shareVisibility :: ShareVisibility , shareComment :: Text , shareSource :: ShareSource , shareAuthor :: ShareAuthor } deriving (Show) parseCurrentShare :: MonadThrow m => Sink Event m (Maybe CurrentShare) parseCurrentShare = tagNoAttr (toName CurrentShareS) $ CurrentShare <$> (force "current-share must contain an id" $ tagNoAttr "id" content) <*> (fmap (read . unpack) . force "current-share must contain a timestamp" $ tagNoAttr "timestamp" content) <*> force "current-share must contain visibility" parseShareVisibility <*> (force "current-share must contain a comment" $ tagNoAttr "comment" content) <*> force "current-share must contain a source" parseShareSource <*> force "current-share must contain an author" parseShareAuthor data ShareVisibility = ShareVisibility { visibilityCode :: Text } deriving (Show) parseShareVisibility :: MonadThrow m => Sink Event m (Maybe ShareVisibility) parseShareVisibility = tagNoAttr "visibility" $ ShareVisibility <$> (force "visibility must contain a code" $ tagNoAttr "code" content) data ShareSource = ShareSource { sourceServiceProviderName :: Maybe Text , sourceServiceProviderShareId :: Maybe Text , sourceServiceProviderAccountId :: Maybe Text , sourceServiceProviderAccountHandle :: Maybe Text } deriving (Show) parseShareSource :: MonadThrow m => Sink Event m (Maybe ShareSource) parseShareSource = tagNoAttr "source" $ ShareSource <$> (fmap join . tagNoAttr "service-provider" $ tagNoAttr "name" content) <*> tagNoAttr "service-provider-share-id" content <*> tagNoAttr "service-provider-account-id" content <*> tagNoAttr "service-provider-account-handle" content data ShareAuthor = ShareAuthor { authorId :: Text , authorFirstName :: Text , authorLastName :: Text } deriving (Show) parseShareAuthor :: MonadThrow m => Sink Event m (Maybe ShareAuthor) parseShareAuthor = tagNoAttr "author" $ ShareAuthor <$> (force "author must contain id" $ tagNoAttr "id" content) <*> (force "author must contain first-name" $ tagNoAttr "first-name" content) <*> (force "author must contain last-name" $ tagNoAttr "last-name" content) data ProfileNetwork = ProfileNetwork { networkStats :: Maybe NetworkStats , networkUpdates :: NetworkUpdates } deriving (Show) parseProfileNetwork :: MonadThrow m => Sink Event m (Maybe ProfileNetwork) parseProfileNetwork = tagNoAttr (toName NetworkS) $ ProfileNetwork <$> parseNetworkStats <*> force "network must contain updates" parseNetworkUpdates data NetworkStats = NetworkStats { networkStatsTotal :: Integer , networkStatsProperties :: [Property] } deriving (Show) parseNetworkStats :: MonadThrow m => Sink Event m (Maybe NetworkStats) parseNetworkStats = tagName "network-stats" (requireAttr "total") $ \t -> fmap (NetworkStats (read $ unpack t)) $ many parseProperty data Property = Property { propertyKey :: Text , propertyValue :: Text } deriving (Show) parseProperty :: MonadThrow m => Sink Event m (Maybe Property) parseProperty = tagName "property" (requireAttr "key") $ \k -> fmap (Property k) content data NetworkUpdates = NetworkUpdates { networkUpdatesTotal :: Integer , networkUpdatesCount :: Maybe Integer , networkUpdatesStart :: Maybe Integer , allNetworkUpdates :: [NetworkUpdate] } deriving (Show) parseNetworkUpdates :: MonadThrow m => Sink Event m (Maybe NetworkUpdates) parseNetworkUpdates = tagName "updates" tcsAttr $ \(t, c, s) -> NetworkUpdates t c s <$> many parseNetworkUpdate where tcsAttr = (,,) <$> reqIntAttr "total" <*> optIntAttr "count" <*> optIntAttr "start" reqIntAttr = fmap (read . unpack) . requireAttr optIntAttr = fmap (fmap (read . unpack)) . optionalAttr data NetworkUpdate = NetworkUpdate { updateTimestamp :: Integer , updateKey :: Text , updateType :: Text , updateContent :: () -- incomplete , updateIsCommentable :: Bool , updateComments :: () -- incomplete , updatedFields :: [Text] , updateisLikable :: Bool , updateIsLiked :: Maybe Bool , updateNumLikes :: Maybe Integer } deriving (Show) parseNetworkUpdate :: MonadThrow m => Sink Event m (Maybe NetworkUpdate) parseNetworkUpdate = tagNoAttr "update" $ NetworkUpdate <$> (fmap (read . unpack) . force "update must contain timestamp" $ tagNoAttr "timestamp" content) <*> (force "update must contain update-key" $ tagNoAttr "update-key" content) <*> (force "update must contain update-type" $ tagNoAttr "update-type" content) <*> (skipTag "update-content" >> return ()) <*> (fmap ("true"==) . force "update must contain is-commentable" $ tagNoAttr "is-commentable" content) <*> (skipTag "update-comments" >> return ()) <*> fields <*> (fmap ("true"==) . force "update must contain is-likable" $ tagNoAttr "is-likable" content) <*> (fmap (fmap ("true"==)) $ tagNoAttr "is-liked" content) <*> (fmap (fmap (read . unpack)) $ tagNoAttr "num-likes" content) where fields = fmap concat . tagName "updated-fields" ignoreAttrs . const . many . tagNoAttr "update-field" . force "update-field must contain name" $ tagNoAttr "name" content data ProfileFieldSelector = IdS | FirstNameS | LastNameS | MaidenNameS | FormattedNameS | PhoneticFirstNameS | PhoneticLastNameS | FormattedPhoneticNameS | HeadlineS | IndustryS | DistanceS | LastModifiedTimestampS | CurrentShareS | NetworkS | NumConnectionsS | NumConnectionsCappedS | SummaryS | SpecialtiesS | ProposalCommentsS | AssociationsS | HonorsS | InterestsS | PositionsS | PublicationsS | PatentsS | LanguagesS | SkillsS | CertificationsS | EducationsS | CoursesS | VolunteerS | ThreeCurrentPositionsS | ThreePastPositionsS | NumRecommendersS | RecommendationsReceivedS | PhoneNumbersS | ImAccountsS | TwitterAccountsS | PrimaryTwitterAccountS | BoundAccountTypesS | MfeedRssUrlS | FollowingS | JobBookMarksS | GroupMembershipsS | SuggestionsS | DateOfBirthS | MainAddressS | MemberUrlResourcesS | PictureUrlS | SiteStandardProfileRequestS | PublicProfileUrlS | RelatedProfileViewsS deriving (Show) allProfileFieldSelectors = [ IdS, FirstNameS, LastNameS, MaidenNameS , FormattedNameS, PhoneticFirstNameS , PhoneticLastNameS, FormattedPhoneticNameS , HeadlineS, IndustryS, DistanceS , LastModifiedTimestampS, CurrentShareS , NumConnectionsS, NumConnectionsCappedS, SummaryS , SpecialtiesS, ProposalCommentsS, AssociationsS , HonorsS, InterestsS , SiteStandardProfileRequestS] fieldName :: ProfileFieldSelector -> String fieldName IdS = "id" fieldName FirstNameS = "first-name" fieldName LastNameS = "last-name" fieldName MaidenNameS = "maiden-name" fieldName FormattedNameS = "formatted-name" fieldName PhoneticFirstNameS = "phonetic-first-name" fieldName PhoneticLastNameS = "phonetic-last-name" fieldName FormattedPhoneticNameS = "formatted-phonetic-name" fieldName HeadlineS = "headline" -- fieldName = "location:(name)" -- fieldName = "location:(country:(code))" fieldName IndustryS = "industry" fieldName DistanceS = "distance" -- fieldName = "relation-to-viewer:(distance)" fieldName LastModifiedTimestampS = "last-modified-timestamp" fieldName CurrentShareS= "current-share" fieldName NetworkS = "network" fieldName NumConnectionsS = "num-connections" fieldName NumConnectionsCappedS = "num-connections-capped" fieldName SummaryS = "summary" fieldName SpecialtiesS = "specialties" fieldName ProposalCommentsS = "proposal-comments" fieldName AssociationsS = "associations" fieldName HonorsS = "honors" fieldName InterestsS = "interests" fieldName PositionsS = "positions" fieldName PublicationsS = "publications" fieldName PatentsS = "patents" fieldName LanguagesS = "languages" fieldName SkillsS = "skills" fieldName CertificationsS = "certifications" fieldName EducationsS = "educations" fieldName CoursesS = "courses" fieldName VolunteerS = "volunteer" fieldName ThreeCurrentPositionsS = "three-current-positions" fieldName ThreePastPositionsS = "three-past-positions" fieldName NumRecommendersS = "num-recommenders" fieldName RecommendationsReceivedS = "recommendations-received" fieldName PhoneNumbersS = "phone-numbers" fieldName ImAccountsS = "im-accounts" fieldName TwitterAccountsS = "twitter-accounts" fieldName PrimaryTwitterAccountS = "primary-twitter-account" fieldName BoundAccountTypesS = "bound-account-types" fieldName MfeedRssUrlS = "mfeed-rss-url" fieldName FollowingS = "following" fieldName JobBookMarksS = "job-bookmarks" fieldName GroupMembershipsS = "group-memberships" fieldName SuggestionsS = "suggestions" fieldName DateOfBirthS = "date-of-birth" fieldName MainAddressS = "main-address" fieldName MemberUrlResourcesS = "member-url-resources" -- fieldName = "member-url-resources:(url)" -- fieldName = "member-url-resources:(name)" fieldName PictureUrlS = "picture-url" fieldName SiteStandardProfileRequestS = "site-standard-profile-request" -- fieldName = "api-standard-profile-request:(url)" -- fieldName = "api-standard-profile-request:(headers)" fieldName PublicProfileUrlS = "public-profile-url" fieldName RelatedProfileViewsS= "related-profile-views" formatSelectors :: [ProfileFieldSelector] -> String formatSelectors ps = "(" ++ fields' ps ++ ")" where fields' = intercalate "," . map fieldName toName :: ProfileFieldSelector -> Name toName s = Name (pack $ fieldName s) Nothing Nothing
whittle/linkedin-api
Data/API/LinkedIn/Profile.hs
mit
16,419
0
31
5,033
3,309
1,774
1,535
285
1
{-# LANGUAGE NoMonomorphismRestriction, FlexibleContexts, TypeFamilies #-} module Main where import Diagrams.Prelude import Diagrams.Backend.SVG.CmdLine sierpinski shape color alignment 1 = shape 1 # fc color sierpinski shape color alignment n = s === (s ||| s) # alignment where s = sierpinski shape color alignment (n-1) diagram :: Diagram B diagram = sierpinski 7 main = mainWith $ diagram # frame 0.1
jeffreyrosenbluth/NYC-meetup
meetup/SierpinskiGeneral.hs
mit
461
0
9
117
125
66
59
13
1
module ProjectEuler.Problem96 ( problem ) where import Control.Monad import Data.List.Split import Data.Char import qualified Math.SetCover.Exact as ESC import qualified Data.Text as T {- the decision to stick with Set instead of more efficient bit vector, is to make sure that we work with some interface that we are familiar with so we can more easily develop our own version of the solver. -} import qualified Data.Set as Set import qualified Data.Map.Strict as Map import qualified Data.Array as Array import ProjectEuler.GetData {- TODO: the problem is solved with set-cover, but I actually wonder if we can do better than this if we actually write the solving logic ourselves. -} problem :: Problem problem = pureProblemWithData "p096_sudoku.txt" 96 Solved compute type Puzzle = [[Int]] parsePuzzles :: T.Text -> [Puzzle] parsePuzzles = fmap parsePuzzle . chunksOf 10 . T.lines where parsePuzzle :: [T.Text] -> Puzzle parsePuzzle (_h:xs) = fmap (T.foldr (\c r -> (ord c - ord '0') : r) []) xs parsePuzzle _ = error "Unexpectd extra lines" compute :: T.Text -> Int compute = sum . fmap solve . parsePuzzles data X = Pos Int Int | Row Int Int | Column Int Int | Square Int Int Int deriving (Eq, Ord) type Assign = ESC.Assign ((Int, Int), Int) assign :: Int -> Int -> Int -> Assign (Set.Set X) assign k i j = ESC.assign ((i,j), k) $ Set.fromList [Pos i j, Row k i, Column k j, Square k (div i 3) (div j 3)] assigns :: [Assign (Set.Set X)] assigns = liftM3 assign [1..9] [0..8] [0..8] stateFromString :: (ESC.Set set) => [Assign set] -> Puzzle -> ESC.State ((Int, Int), Int) set stateFromString asgns css = foldl (flip ESC.updateState) (ESC.initState asgns) $ do let asnMap = foldMap (\asn -> Map.singleton (ESC.label asn) asn) asgns (i,cs) <- zip [0..] css (j,c) <- zip [0..] cs guard $ c /= 0 pure $ Map.findWithDefault (error "coordinates not available") ((i,j), c) asnMap solve :: Puzzle -> Int solve inp = (\[a,b,c] -> a*100 + b*10 +c) . take 3 . Array.elems . Array.array ((0,0),(8,8)) . head . ESC.search $ stateFromString assigns inp
Javran/Project-Euler
src/ProjectEuler/Problem96.hs
mit
2,191
0
17
497
804
438
366
59
2
import Data.Char main = do putStrLn "What's your first name?" firstName <- getLine putStrLn "What's your last name?" lastName <- getLine bigFirstName = map toUpper firstName bigLastName = map toUpper lastName putStrLn $ "hey " ++ bigFirstName ++ " " ++ bigLastName ++ ", how are you?"
arnabgho/RLearnHaskell
tests/Test.hs
mit
334
2
11
96
84
37
47
-1
-1
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} module Cenary.Lexer where -------------------------------------------------------------------------------- import qualified Text.Parsec.Token as Tok -------------------------------------------------------------------------------- import Cenary.Lexer.Language (style) -------------------------------------------------------------------------------- lexer :: Tok.TokenParser () lexer = Tok.makeTokenParser style integer = Tok.integer lexer float = Tok.float lexer parens = Tok.parens lexer commaSep = Tok.commaSep lexer semiSep = Tok.semiSep lexer identifier = Tok.identifier lexer whitespace = Tok.whiteSpace lexer reserved = Tok.reserved lexer reservedOp = Tok.reservedOp lexer natural = Tok.natural lexer operator = Tok.operator lexer symbol = Tok.symbol lexer charLiteral = Tok.charLiteral lexer stringLiteral = Tok.stringLiteral lexer braces = Tok.braces lexer
yigitozkavci/ivy
src/Cenary/Lexer.hs
mit
993
0
6
166
202
108
94
21
1
{-# LANGUAGE FlexibleInstances, OverloadedStrings #-} module Data.BlockChain.Block.Transactions where import Control.Arrow ((&&&), (>>>)) import Control.Monad ((>=>)) import Crypto.Hash import Data.Aeson import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as BL import Data.Maybe (fromJust) import qualified Data.Text as T import Network.Socket -- below import available on 1HaskellADay git repository import Data.BlockChain.Block.Types import Data.BlockChain.Block.Utils {-- Last Friday we looked at reading in a summary of a Block of the block chain. Part of that summary data was a set of transaction indices (called 'tx' in the JSON). But what are these transactions? Today we will take a sample transaction, represent it in Haskell, and read in that transaction-as-JSON. --} data Packet = Pck [Transaction] deriving Show instance FromJSON Packet where parseJSON (Object o) = Pck <$> o .: "tx" data Transaction = TX { lockTime, version, size :: Integer, inputs :: [Input], time, txIndex, vInSize, vOutSize :: Integer, hashCode :: Hash, relayedBy :: HostName, out :: [Output] } deriving (Eq, Ord, Show) instance Sheesh Transaction where hash = hashCode instance FromJSON Transaction where parseJSON (Object o) = TX <$> o .: "lock_time" <*> o .: "ver" <*> o .: "size" <*> o .: "inputs" <*> o .: "time" <*> o .: "tx_index" <*> o .: "vin_sz" <*> o .: "vout_sz" <*> o .: "hash" <*> o .: "relayed_by" <*> o .: "out" -- of course, to read in a SHA256 digest as JSON, we need to define that instance FromJSON (Digest SHA256) where parseJSON (String s) = return . fromJust . digestFromByteString . B.pack $ T.unpack s data Input = In { sequence :: Integer, prevOut :: Maybe Output, inScript :: String } deriving (Eq, Ord, Show) instance FromJSON Input where parseJSON (Object o) = In <$> o .: "sequence" <*> o .:? "prev_out" <*> o .: "script" data Output = Out { spent :: Bool, outTxIndex, typ, value, n :: Integer, addr :: Maybe String, outScript :: String } deriving (Eq, Ord, Show) instance FromJSON Output where parseJSON (Object o) = Out <$> o .: "spent" <*> o .: "tx_index" <*> o .: "type" <*> o .: "value" <*> o .: "n" <*> o .:? "addr" <*> o .: "script" -- With the above types having FromJSON instances defined, read in the two -- transactions at this directory or also at the url: -- https://raw.githubusercontent.com/geophf/1HaskellADay/master/exercises/HAD/Y2016/M09/D05/txs.json -- (ignoring, for now, the other paired-values outside the tx-json-list) readTransactions :: FilePath -> IO [Transaction] readTransactions = BL.readFile >=> (\(Just (Pck txns)) -> return txns) . decode {-- *Y2016.M09.D05.Solution BL> BL.readFile "Y2016/M09/D05/txs.json" ~> json *Y2016.M09.D05.Solution BL> let mbpcks = (decode json) :: Maybe Packet *Y2016.M09.D05.Solution BL> let (Pck txns) = fromJust mbpcks --} -- what is the average size of the (albeit very small) sample set of transcactions? transactionsMeanSize :: [Transaction] -> Int transactionsMeanSize = sum . map (fromIntegral . size) &&& length >>> uncurry div -- *Y2016.M09.D05.Solution> transactionsMeanSize txns ~> 201
geophf/1HaskellADay
exercises/HAD/Data/BlockChain/Block/Transactions.hs
mit
3,466
0
27
833
730
419
311
-1
-1
{-# LANGUAGE FlexibleContexts, OverloadedStrings #-} -- | Module : Network.MPD.Commands.Parse -- Copyright : (c) Ben Sinclair 2005-2009, Joachim Fasting 2010 -- License : MIT (see LICENSE) -- Maintainer : Joachim Fasting <joachifm@fastmail.fm> -- Stability : alpha -- -- Parsers for MPD data types. module Network.MPD.Commands.Parse where import Network.MPD.Commands.Types import Control.Applicative import Control.Monad.Error import Data.Maybe (fromMaybe) import Network.MPD.Util import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.UTF8 as UTF8 -- | Builds a 'Count' instance from an assoc. list. parseCount :: [ByteString] -> Either String Count parseCount = foldM f def . toAssocList where f :: Count -> (ByteString, ByteString) -> Either String Count f a ("songs", x) = return $ parse parseNum (\x' -> a { cSongs = x'}) a x f a ("playtime", x) = return $ parse parseNum (\x' -> a { cPlaytime = x' }) a x f _ x = Left $ show x -- | Builds a list of 'Device' instances from an assoc. list parseOutputs :: [ByteString] -> Either String [Device] parseOutputs = mapM (foldM f def) . splitGroups ["outputid"] . toAssocList where f a ("outputid", x) = return $ parse parseNum (\x' -> a { dOutputID = x' }) a x f a ("outputname", x) = return a { dOutputName = UTF8.toString x } f a ("outputenabled", x) = return $ parse parseBool (\x' -> a { dOutputEnabled = x'}) a x f _ x = Left $ show x -- | Builds a 'Stats' instance from an assoc. list. parseStats :: [ByteString] -> Either String Stats parseStats = foldM f def . toAssocList where f a ("artists", x) = return $ parse parseNum (\x' -> a { stsArtists = x' }) a x f a ("albums", x) = return $ parse parseNum (\x' -> a { stsAlbums = x' }) a x f a ("songs", x) = return $ parse parseNum (\x' -> a { stsSongs = x' }) a x f a ("uptime", x) = return $ parse parseNum (\x' -> a { stsUptime = x' }) a x f a ("playtime", x) = return $ parse parseNum (\x' -> a { stsPlaytime = x' }) a x f a ("db_playtime", x) = return $ parse parseNum (\x' -> a { stsDbPlaytime = x' }) a x f a ("db_update", x) = return $ parse parseNum (\x' -> a { stsDbUpdate = x' }) a x f _ x = Left $ show x parseMaybeSong :: [ByteString] -> Either String (Maybe Song) parseMaybeSong xs | null xs = Right Nothing | otherwise = Just <$> (parseSong . toAssocList) xs -- | Builds a 'Song' instance from an assoc. list. parseSong :: [(ByteString, ByteString)] -> Either String Song parseSong xs = case xs of ("file", path):ys -> foldM f (defaultSong (Path path)) ys _ -> Left "Got a song without a file path! This indicates a bug in either libmpd-haskell or MPD itself!" where f :: Song -> (ByteString, ByteString) -> Either String Song f s ("Last-Modified", v) = return s { sgLastModified = parseIso8601 v } f s ("Time", v) = return s { sgLength = fromMaybe 0 $ parseNum v } f s ("Id", v) = return $ parse parseNum (\v' -> s { sgId = Just $ Id v' }) s v f s ("Pos", v) = maybe (return $ parse parseNum (\v' -> s { sgIndex = Just v' }) s v) (const $ return s) (sgIndex s) f s (k, v) = return . maybe s (\m -> sgAddTag m (Value v) s) $ readMeta k -- Custom-made Read instance readMeta "ArtistSort" = Just ArtistSort readMeta "Artist" = Just Artist readMeta "Album" = Just Album readMeta "AlbumArtist" = Just AlbumArtist readMeta "AlbumArtistSort" = Just AlbumArtistSort readMeta "Title" = Just Title readMeta "Genre" = Just Genre readMeta "Name" = Just Name readMeta "Composer" = Just Composer readMeta "Performer" = Just Performer readMeta "Comment" = Just Comment readMeta "Date" = Just Date readMeta "Track" = Just Track readMeta "Disc" = Just Disc readMeta "MUSICBRAINZ_ARTISTID" = Just MUSICBRAINZ_ARTISTID readMeta "MUSICBRAINZ_ALBUMID" = Just MUSICBRAINZ_ALBUMID readMeta "MUSICBRAINZ_ALBUMARTISTID" = Just MUSICBRAINZ_ALBUMARTISTID readMeta "MUSICBRAINZ_TRACKID" = Just MUSICBRAINZ_TRACKID readMeta "MUSICBRAINZ_RELEASETRACKID" = Just MUSICBRAINZ_RELEASETRACKID readMeta _ = Nothing -- | A helper that runs a parser on a string and, depending on the -- outcome, either returns the result of some command applied to the -- result, or a default value. Used when building structures. parse :: (ByteString -> Maybe a) -> (a -> b) -> b -> ByteString -> b parse parser f x = maybe x f . parser -- | A helper for running a parser returning Maybe on a pair of strings. -- Returns Just if both strings where parsed successfully, Nothing otherwise. pair :: (ByteString -> Maybe a) -> (ByteString, ByteString) -> Maybe (a, a) pair p (x, y) = case (p x, p y) of (Just a, Just b) -> Just (a, b) _ -> Nothing
matthewleon/libmpd-haskell
src/Network/MPD/Commands/Parse.hs
mit
5,693
0
15
1,974
1,596
849
747
91
25
{-# LANGUAGE OverloadedStrings #-} -- This is the complete and final code of nomeata's bot (nomeataintercept2 in -- the game). Feel free to use it for your own bot. If you are successful with -- it, let me know. Or give it a name that ends with "2n". Or both. -- -- 2013 Joachim Breitner <mail@joachim-breitner.de> import Game.Spacegoo import Control.Monad import Data.List import Data.VectorSpace import Data.Ord -- Client is provided by Game.Spacegoo and takes a port, a hostname, a -- username, a password and a function that takes the state of the game and -- returns a Maybe Move main :: IO () main = client 6000 "spacegoo.gpn.entropia.de" "nomeataintercept2" "foo42" $ \s -> -- msum takes a list of (Maybe Move) and returns the first Move found (or -- Nothing if none of the strategy returns a move -- -- Here we combine four strategies msum [ guard (currentRound s > 50) >> cheapNeutral s -- The guard prevents the strategy afterwards from being considered -- if the condition does not hol , fullForceOn (he s) s , tickleNearNeutral s , guard (currentRound s > 200) >> fullForceOn 0 s , guard (currentRound s > 100) >> tickle (he s) s ] -- Strategy 1: Try to capture neutral planets that -- * we can definitely conquer -- * are much closer to us than to the enemy cheapNeutral :: Strategy cheapNeutral s = do pickLowest [ (d , (planetId p, planetId op, minimizeUnits (planetShips p) goal)) | p <- planets s -- Iterate through all our planets , planetOwner p == me s -- and look at each other planet , op <- planets s , planetId p /= planetId op -- Check who owns the planet when we would reach it (o'), and how much -- ships are there (goal) , let (o', goal) = ownerAt s (planetId op) (currentRound s + distance p op + 2) -- Make sure that the planet is still neutral then... , o' == 0 -- ..that we can win it.. , planetShips p `winsAgainst` goal , let d = distance p op -- And that the planet is far from the enemy , and [ distance op p2' > 2 * d | p2' <- planets s, planetOwner p2' == he s ] ] -- Strategy 2+4: If we can conquer a planet owned by the specified player, do it. fullForceOn :: Int -> Strategy fullForceOn victim s = do -- We send the smallest number of ships that still kills it; possibly -- chosing a good type (see Game.Spacegoo.minimizeUnits) pickLowest [ (d, (planetId p, planetId op, minimizeUnits (planetShips p) goal)) | p <- planets s -- p is our planet , planetOwner p == me s , op <- planets s , planetId p /= planetId op -- op is the target , let d = distance p op , let (o', goal) = ownerAt s (planetId op) (currentRound s + d + 2) , o' == victim -- and we really win against it , planetShips p `winsAgainst` goal ] -- Strategy 3: Reduce the strength of nearby neutral planets with (1,1,1) -- fleets (which are very effective) tickleNearNeutral :: Strategy tickleNearNeutral s = do pickLowest [ (d, (planetId p, planetId op, (1,1,1))) | p <- planets s , planetOwner p == me s , op <- planets s , planetId p /= planetId op , let (o', _) = ownerAt s (planetId op) (currentRound s + distance p op + 2) , o' == 0 , let d = distance p op , and [ distance op p2' > 2*d | p2' <- planets s, planetOwner p2' == he s ] ] -- | Strategy 5: Send (1,1,1) fleets to the planet of the enemy with the -- smallest number of ships tickle :: Int -> Strategy tickle victim s = do -- Pick the other planet otherPlanet <- pickLowest [ ( magnitudeSq (planetShips p) , p) | p <- planets s, planetOwner p == victim ] -- Pick our planet (the closest one with ships) myPlanet <- pickLowest [ (distance p otherPlanet, p) | p <- planets s, planetOwner p == me s, planetShips p /= (0,0,0) ] return (planetId myPlanet, planetId otherPlanet, (1,1,1)) -- Utility function: Pick the tuple with the lowest entry in the first -- component and return its second component pickLowest :: Ord a => [(a,b)] -> Maybe b pickLowest [] = Nothing pickLowest l = Just (snd (minimumBy (comparing fst) l))
nomeata/haskell-spacegoo
nomeatas_bot.hs
mit
4,564
0
17
1,422
1,086
554
532
62
1
import System.Environment import Data.List main = do args <- getArgs progName <- getProgName putStrLn "The arguments are:" mapM putStrLn args putStrLn "The program name is:" putStrLn progName {- $ ./arg_test first second w0t "multi word arg" -}
yhoshino11/learning_haskell
ch9/arg_test.hs
mit
259
0
7
51
57
25
32
9
1
module Station where import Import hiding (set) import qualified Data.ByteString as BS import qualified Data.HashMap.Strict as HM import qualified Data.Set as SET import qualified Data.Text as T import qualified System.Directory as SD import System.FilePath ((</>)) import qualified Station.Implementation as IM import qualified Station.Implementation.PlainFilesystem as PF import qualified Station.Procedures.Add as SPA import Station.Procedures.Build (VersionNotFound(..), buildDeck) import qualified Station.Procedures.General as SP import Station.JSON (encodeProper) import qualified Station.Original as SO import qualified Station.Schema as SC import Station.Schema.Failure (Invalid) import Station.Types -- * Main API -- -- These are your basic CRUD operations (only renamed). -- -- This is definitely a datastore and not a database. To perform more -- compicated queries than 'resolve' you have to get the 'Deck' value -- out of the @MonadState@ and examine it manually. resolve :: Station m n => Id -> m (Maybe VersionInfo) new :: Station m n => CardBytes -> m (Either Invalid (Link VersionHash)) update :: Station m n => Link VersionHash -> CardBytes -> m (Either Invalid VersionHash) archive :: Station m n => Link VersionHash -> m () data IdConflict = IdConflict Id [VersionInfo] | IdConflictHashes Id [VersionHash] deriving (Show, Typeable) instance Exception IdConflict resolve i = do deck <- get case SP.resolveId deck i of [] -> pure Nothing [versionInfo] -> pure (Just versionInfo) versionInfos -> throwM (IdConflict i versionInfos) new card = do station <- ask i <- liftBase (_imNewId (_stationImplementation station)) deck <- get res <- SPA.add station deck i Nothing card case res of Left e -> pure (Left e) Right (deck',hash) -> put deck' >> pure (Right (Link i hash)) data CardNotFound = CardNotFound Id deriving (Show, Typeable) instance Exception CardNotFound data ParentHasChanged = ParentHasChanged Id VersionHash VersionHash deriving (Show, Typeable) instance Exception ParentHasChanged update (Link i argHash) card = do station <- ask deck <- get case SP.resolveId deck i of [] -> throwM (CardNotFound i) [parent] -> do let parentHash = _vcHash parent when (argHash /= parentHash) (throwM (ParentHasChanged i argHash parentHash)) res <- SPA.add station deck i (Just parent) card case res of Left e -> pure (Left e) Right (deck',hash) -> put deck' >> pure (Right hash) parents -> throwM (IdConflict i parents) -- NOTE: If the target card isn't found then nothing happens. archive (Link i argHash) = do station <- ask tm <- liftBase (_imGetTAI (_stationImplementation station)) deck <- get case SP.resolveId deck i of [] -> pure () [parent] -> do let parentHash = _vcHash parent when (argHash /= parentHash) (throwM (ParentHasChanged i argHash parentHash)) let version = Version { _versionId = i , _versionParents = pure parentHash , _versionCard = Nothing , _versionAuthors = _stationAuthors station , _versionTime = Just tm } :: Version CardHash versionBts = encodeProper version versionHash = VersionHash (hashProper versionBts) whenLeft (SP.validateVersion deck version) (throwM . SPA.VersionInvalid version) vli <- case versionContents (`HM.lookup` _deckBytes deck) version of Left e -> throwM e Right a -> pure a let location = VersionLocation Nothing versionInfo = VersionContext { _vcHash = versionHash , _vcVersion = vli , _vcLocation = pure location } liftBase (_imWriteVersion (_stationImplementation station) versionHash versionBts) put $ deck & deckBytes %~ HM.insert (_unVersionHash versionHash) versionBts & deckVersions %~ HM.adjust (SET.insert versionHash) location & deckIds %~ HM.insert i (pure versionInfo) parents -> throwM (IdConflict i parents) -- * Convenience versionCount :: forall m n. Station m n => Id -> m Int versionCount i = do deck <- get case SP.resolveId deck i of [] -> pure 0 [versionInfo] -> f deck 1 (_vcHash versionInfo) versionInfos -> throwM (IdConflict i versionInfos) where f :: Deck -> Int -> VersionHash -> m Int f deck n hash = case SP.getVersion deck hash of Nothing -> throwM (VersionNotFound hash) Just version -> case _versionParents version of [] -> pure n [parentHash] -> f deck (n+1) parentHash parents -> throwM (IdConflictHashes i parents) -- | A glorified @type@ wrapper, not used to enforce invariants. newtype SchemaBytes = SchemaBytes { _unSchemaBytes :: ByteString } deriving (Eq, Show) -- | For casual use in places like tests. -- -- For actual schemas it's better to write them as bytestrings instead -- of 'SC.Schema's. Encoding an `SC.Schema` will do things like change -- `1` to `1.0`, which may not be what you want. encodeSchemaBytes :: SC.Schema -> SchemaBytes encodeSchemaBytes = SchemaBytes . encodeProper . Object . SC._unSchema -- | Specialized 'new'. newSchema :: Station m n => SchemaBytes -> Maybe Text -- ^ Schema name -> m (Either Invalid SchemaLink) newSchema sch name = fmap schemaLink <$> new card where card :: CardBytes card = Card { _cardSchema = SO.customSchemaLink , _cardInstance = _unSchemaBytes sch , _cardName = name } -- NOTE: By turning a @VersionHash@ into a @BlobOrVersionHash@ -- here using @BVVersion@ we lose data about what we're returning. -- Should this be changed? schemaLink :: Link VersionHash -> SchemaLink schemaLink = SchemaLink . fmap BVVersion -- * Convenience -- -- The following all use 'Station.Implementation.PlainFilesystem'. defaultPaths :: FilePath -> PF.Paths defaultPaths dir = PF.Paths { PF._pathHashes = dir </> "hashes" , PF._pathLocal = dir </> "local_versions" , PF._pathVersions = dir </> "versions" } loadDeckWithPaths :: PF.Paths -> IO (Implementation IO, Deck) loadDeckWithPaths paths = do SD.createDirectoryIfMissing True -- Create its parents too (PF._pathHashes paths) SD.createDirectoryIfMissing True -- Create its parents too (PF._pathVersions paths) traverse_ (\(t,bts) -> BS.writeFile (PF._pathHashes paths </> t) bts) SO.originalHashDir hasLocalVersions <- SD.doesFileExist (PF._pathLocal paths) unless hasLocalVersions $ writeFile (PF._pathLocal paths) mempty BS.writeFile (PF._pathVersions paths </> "builtin") SO.originalVersionBytes let impl = IM.plainFilesystem paths (impl,) <$> buildDeck impl -- | Loads from the current directory. loadDeck :: IO (Implementation IO, Deck) loadDeck = do dir <- SD.getCurrentDirectory loadDeckWithPaths (defaultPaths dir) runDeck :: PF.Paths -> Deck -> [AuthorLink] -> ReaderT (StationDetails IO) (StateT Deck IO) a -> IO (a, Deck) runDeck paths deck authors f = runStateT (runReaderT f (StationDetails (IM.plainFilesystem paths) authors)) deck tempDeck :: IO (PF.Paths, Deck) tempDeck = do tmp <- SD.getTemporaryDirectory i <- _unId <$> newId let dir = tmp </> T.unpack i paths = defaultPaths dir (_,deck) <- loadDeckWithPaths (defaultPaths dir) pure (paths,deck) -- | Doesn't set any authorship. runTempDeck :: (PF.Paths -> ReaderT (StationDetails IO) (StateT Deck IO) a) -- ^ The @PF.Paths@ is provided for debugging. -> IO (a, Deck) runTempDeck f = do (paths,deck) <- tempDeck runDeck paths deck mempty (f paths)
seagreen/station
src/Station.hs
mit
8,906
0
19
2,932
2,269
1,162
1,107
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnicodeSyntax #-} -- | -- Module: Tests.MonoidConfig -- Description: Test cases for monoidal configuration types -- Copyright: Copyright © 2015 PivotCloud, Inc. -- License: MIT -- Maintainer: Lars Kuhtz <lkuhtz@pivotmail.com> -- Stability: experimental -- module Tests.MonoidConfig ( monoidUpdateTests ) where import TestTools import Configuration.Utils import Configuration.Utils.Internal import Configuration.Utils.Internal.ConfigFileReader import Configuration.Utils.Validation import Data.Bifunctor import qualified Data.HashMap.Strict as HM import Data.Monoid.Unicode import Data.String import qualified Data.Text as T #if MIN_VERSION_base(4,13,0) import Prelude.Unicode hiding ((×)) #else import Prelude.Unicode #endif -- -------------------------------------------------------------------------- -- -- Test cases monoidUpdateTests ∷ PkgInfo → [IO Bool] monoidUpdateTests pkgInfo = concatMap ($ pkgInfo) [ routingTableTests , textAppendTestsR , textAppendTestsFilesR , textAppendTestsL , textAppendTestsFilesL ] -- -------------------------------------------------------------------------- -- -- HashMap newtype RoutingTable = RoutingTable { _routingTableMap ∷ HM.HashMap T.Text T.Text } routingTableMap ∷ Lens' RoutingTable (HM.HashMap T.Text T.Text) routingTableMap = lens _routingTableMap $ \a b → a { _routingTableMap = b } defaultRoutingTable ∷ RoutingTable defaultRoutingTable = RoutingTable HM.empty instance ToJSON RoutingTable where toJSON RoutingTable{..} = object [ "route_map" .= _routingTableMap ] instance FromJSON (RoutingTable → RoutingTable) where parseJSON = withObject "RoutingTable" $ \o → id <$< routingTableMap . fromLeftMonoidalUpdate %.: "route_map" % o pRoutingTable ∷ MParser RoutingTable pRoutingTable = routingTableMap %:: pLeftMonoidalUpdate pRoute where pRoute = option (eitherReader readRoute) % long "route" ⊕ help "add a route to the routing table; the APIROUTE part must not contain a colon character" ⊕ metavar "APIROUTE:APIURL" readRoute s = case break (== ':') s of (a,':':b) → first T.unpack $ do validateNonEmpty "APIROUTE" a validateHttpOrHttpsUrl "APIURL" b return $ HM.singleton (T.pack a) (T.pack b) _ → Left "missing colon between APIROUTE and APIURL" mainInfoRoutingTable ∷ ProgramInfoValidate RoutingTable [] mainInfoRoutingTable = programInfoValidate "Routing Table" pRoutingTable defaultRoutingTable (const $ return ()) -- Test Cases routingTableTests ∷ PkgInfo → [IO Bool] routingTableTests pkgInfo = [ run 0 [ConfAssertion ["--route=a:" ⊕ b0] (routingTableMap ∘ at "a") $ Just b0] , run 1 [ConfAssertion ["--route=a:" ⊕ b0, "--route=a:" ⊕ b1] (routingTableMap ∘ at "a") $ Just b1] , run 2 [ConfAssertion ["--route=a:" ⊕ b0, "--route=a:" ⊕ b1] (routingTableMap ∘ at "a") $ Just b1] , run 3 [ConfAssertion ["--route=a:" ⊕ b0, "--route=b:" ⊕ b1] (routingTableMap ∘ at "a") $ Just b0] , run 4 [ConfAssertion ["--route=a:" ⊕ b0, "--route=b:" ⊕ b1] (routingTableMap ∘ at "b") $ Just b1] , run 5 [ConfAssertion ["--route=a:" ⊕ b0, "--route=b:" ⊕ b1] (routingTableMap ∘ at "c") Nothing] ] where b0,b1 ∷ IsString a ⇒ a b0 = "http://b0" b1 = "https://b1" run (x ∷ Int) = runTest pkgInfo mainInfoRoutingTable ("routing-table-" ⊕ sshow x) True at k f m = f mv <&> \r → case r of Nothing → maybe m (const (HM.delete k m)) mv Just v' → HM.insert k v' m where mv = HM.lookup k m -- -------------------------------------------------------------------------- -- -- Text with right append newtype StringConfigR = StringConfigR { _stringConfigR ∷ T.Text } stringConfigR ∷ Lens' StringConfigR T.Text stringConfigR = lens _stringConfigR $ \a b → a { _stringConfigR = b } defaultStringConfigR ∷ StringConfigR defaultStringConfigR = StringConfigR "|" instance ToJSON StringConfigR where toJSON StringConfigR{..} = object [ "string" .= _stringConfigR ] instance FromJSON (StringConfigR → StringConfigR) where parseJSON = withObject "StringConfigR" $ \o → id <$< stringConfigR . fromRightMonoidalUpdate %.: "string" % o pStringConfigR ∷ MParser StringConfigR pStringConfigR = stringConfigR %:: pRightMonoidalUpdate pString where pString = T.pack <$> strOption % long "string" -- Test cases textAppendTestsR ∷ PkgInfo → [IO Bool] textAppendTestsR pkgInfo = [ run 0 True [ConfAssertion [] stringConfigR "|"] , run 1 True [ConfAssertion ["--string=a"] stringConfigR "|a"] , run 2 True [ConfAssertion ["--string=a", "--string=b"] stringConfigR "|ab"] , run 3 False [ConfAssertion ["--string=a", "--string=b"] stringConfigR "|ba"] , run 4 False [ConfAssertion ["--string=b", "--string=a"] stringConfigR "|ab"] , run 5 True [ConfAssertion ["--string=b", "--string=a"] stringConfigR "|ba"] , run 6 False [ConfAssertion ["--string=aaa", "--string=bbb"] stringConfigR "|bbbaaa"] , run 7 True [ConfAssertion ["--string=aaa", "--string=bbb"] stringConfigR "|aaabbb"] , run 8 True [ConfAssertion ["--string=bbb", "--string=aaa"] stringConfigR "|bbbaaa"] , run 9 False [ConfAssertion ["--string=bbb", "--string=aaa"] stringConfigR "|aaabbb"] ] where run (x ∷ Int) = runTest pkgInfo mi ("stringR-" ⊕ sshow x) mi = programInfoValidate "Text right append" pStringConfigR defaultStringConfigR (const $ return ()) textAppendTestsFilesR ∷ PkgInfo → [IO Bool] textAppendTestsFilesR pkgInfo = [ run ca 0 True [ConfAssertion [] stringConfigR "|a"] , run ca 2 True [ConfAssertion ["--string=b"] stringConfigR "|ab"] , run ca 3 False [ConfAssertion ["--string=b"] stringConfigR "|ba"] , run cb 4 False [ConfAssertion ["--string=a"] stringConfigR "|ab"] , run cb 5 True [ConfAssertion ["--string=a"] stringConfigR "|ba"] , run2 ca ca 6 True [ConfAssertion [] stringConfigR "|aa"] , run2 ca cb 6 False [ConfAssertion [] stringConfigR "|ba"] , run2 ca cb 7 True [ConfAssertion [] stringConfigR "|ab"] , run2 cb ca 8 True [ConfAssertion [] stringConfigR "|ba"] , run2 cb ca 9 False [ConfAssertion [] stringConfigR "|ab"] ] where ca = StringConfigR "a" cb = StringConfigR "b" run c (x ∷ Int) b a = withConfigFile Yaml c $ \file → runTest pkgInfo (mi [file]) ("stringR-file1-" ⊕ sshow x) b a run2 c0 c1 (x ∷ Int) b a = withConfigFile Json c0 $ \file0 → withConfigFile Yaml c1 $ \file1 → runTest pkgInfo (mi [file0,file1]) ("stringR-file2-" ⊕ sshow x) b a mi files = set piConfigurationFiles (map ConfigFileRequired files) $ programInfoValidate "Text right append with files" pStringConfigR defaultStringConfigR (const $ return ()) -- -------------------------------------------------------------------------- -- -- Text with left append newtype StringConfigL = StringConfigL { _stringConfigL ∷ T.Text } stringConfigL ∷ Lens' StringConfigL T.Text stringConfigL = lens _stringConfigL $ \a b → a { _stringConfigL = b } defaultStringConfigL ∷ StringConfigL defaultStringConfigL = StringConfigL "|" instance ToJSON StringConfigL where toJSON StringConfigL{..} = object [ "string" .= _stringConfigL ] instance FromJSON (StringConfigL → StringConfigL) where parseJSON = withObject "StringConfigL" $ \o → id <$< stringConfigL . fromLeftMonoidalUpdate %.: "string" % o pStringConfigL ∷ MParser StringConfigL pStringConfigL = stringConfigL %:: pLeftMonoidalUpdate pString where pString = T.pack <$> strOption % long "string" -- Test cases textAppendTestsL ∷ PkgInfo → [IO Bool] textAppendTestsL pkgInfo = [ run 0 True [ConfAssertion [] stringConfigL "|"] , run 1 True [ConfAssertion ["--string=a"] stringConfigL "a|"] , run 2 True [ConfAssertion ["--string=a", "--string=b"] stringConfigL "ba|"] , run 3 False [ConfAssertion ["--string=a", "--string=b"] stringConfigL "ab|"] , run 4 False [ConfAssertion ["--string=b", "--string=a"] stringConfigL "ba|"] , run 5 True [ConfAssertion ["--string=b", "--string=a"] stringConfigL "ab|"] , run 6 True [ConfAssertion ["--string=aaa", "--string=bbb"] stringConfigL "bbbaaa|"] , run 7 False [ConfAssertion ["--string=aaa", "--string=bbb"] stringConfigL "aaabbb|"] , run 8 False [ConfAssertion ["--string=bbb", "--string=aaa"] stringConfigL "bbbaaa|"] , run 9 True [ConfAssertion ["--string=bbb", "--string=aaa"] stringConfigL "aaabbb|"] ] where run (x ∷ Int) = runTest pkgInfo mi ("stringL-" ⊕ sshow x) mi = programInfoValidate "Text left append" pStringConfigL defaultStringConfigL (const $ return ()) textAppendTestsFilesL ∷ PkgInfo → [IO Bool] textAppendTestsFilesL pkgInfo = [ run ca 1 True [ConfAssertion [] stringConfigL "a|"] , run ca 2 True [ConfAssertion ["--string=b"] stringConfigL "ba|"] , run ca 3 False [ConfAssertion ["--string=b"] stringConfigL "ab|"] , run cb 4 False [ConfAssertion ["--string=a"] stringConfigL "ba|"] , run cb 5 True [ConfAssertion ["--string=a"] stringConfigL "ab|"] , run2 ca ca 1 True [ConfAssertion [] stringConfigL "aa|"] , run2 ca cb 2 True [ConfAssertion [] stringConfigL "ba|"] , run2 ca cb 3 False [ConfAssertion [] stringConfigL "ab|"] , run2 cb ca 4 False [ConfAssertion [] stringConfigL "ba|"] , run2 cb ca 5 True [ConfAssertion [] stringConfigL "ab|"] ] where ca = StringConfigL "a" cb = StringConfigL "b" run c (x ∷ Int) b a = withConfigFile Json c $ \file → runTest pkgInfo (mi [file]) ("stringL-file1-" ⊕ sshow x) b a run2 c0 c1 (x ∷ Int) b a = withConfigFile Yaml c0 $ \file0 → withConfigFile Json c1 $ \file1 → runTest pkgInfo (mi [file0,file1]) ("stringL-file2-" ⊕ sshow x) b a mi files = set piConfigurationFiles (map ConfigFileRequired files) $ programInfoValidate "Text left append with file" pStringConfigL defaultStringConfigL (const $ return ())
alephcloud/hs-configuration-tools
test/Tests/MonoidConfig.hs
mit
10,367
0
17
1,965
2,994
1,570
1,424
-1
-1
module Tests.Readers.Docx (tests) where import Text.Pandoc.Options import Text.Pandoc.Readers.Native import Text.Pandoc.Definition import Tests.Helpers import Test.Framework import Test.HUnit (assertBool) import Test.Framework.Providers.HUnit import qualified Data.ByteString.Lazy as B import Text.Pandoc.Readers.Docx import Text.Pandoc.Writers.Native (writeNative) import qualified Data.Map as M import Text.Pandoc.MediaBag (MediaBag, lookupMedia, mediaDirectory) import Codec.Archive.Zip -- We define a wrapper around pandoc that doesn't normalize in the -- tests. Since we do our own normalization, we want to make sure -- we're doing it right. data NoNormPandoc = NoNormPandoc {unNoNorm :: Pandoc} deriving Show noNorm :: Pandoc -> NoNormPandoc noNorm = NoNormPandoc instance ToString NoNormPandoc where toString d = writeNative def{ writerStandalone = s } $ toPandoc d where s = case d of NoNormPandoc (Pandoc (Meta m) _) | M.null m -> False | otherwise -> True instance ToPandoc NoNormPandoc where toPandoc = unNoNorm compareOutput :: ReaderOptions -> FilePath -> FilePath -> IO (NoNormPandoc, NoNormPandoc) compareOutput opts docxFile nativeFile = do df <- B.readFile docxFile nf <- Prelude.readFile nativeFile let (p, _) = readDocx opts df return $ (noNorm p, noNorm (readNative nf)) testCompareWithOptsIO :: ReaderOptions -> String -> FilePath -> FilePath -> IO Test testCompareWithOptsIO opts name docxFile nativeFile = do (dp, np) <- compareOutput opts docxFile nativeFile return $ test id name (dp, np) testCompareWithOpts :: ReaderOptions -> String -> FilePath -> FilePath -> Test testCompareWithOpts opts name docxFile nativeFile = buildTest $ testCompareWithOptsIO opts name docxFile nativeFile testCompare :: String -> FilePath -> FilePath -> Test testCompare = testCompareWithOpts def getMedia :: FilePath -> FilePath -> IO (Maybe B.ByteString) getMedia archivePath mediaPath = do zf <- B.readFile archivePath >>= return . toArchive return $ findEntryByPath ("word/" ++ mediaPath) zf >>= (Just . fromEntry) compareMediaPathIO :: FilePath -> MediaBag -> FilePath -> IO Bool compareMediaPathIO mediaPath mediaBag docxPath = do docxMedia <- getMedia docxPath mediaPath let mbBS = case lookupMedia mediaPath mediaBag of Just (_, bs) -> bs Nothing -> error ("couldn't find " ++ mediaPath ++ " in media bag") docxBS = case docxMedia of Just bs -> bs Nothing -> error ("couldn't find " ++ mediaPath ++ " in media bag") return $ mbBS == docxBS compareMediaBagIO :: FilePath -> IO Bool compareMediaBagIO docxFile = do df <- B.readFile docxFile let (_, mb) = readDocx def df bools <- mapM (\(fp, _, _) -> compareMediaPathIO fp mb docxFile) (mediaDirectory mb) return $ and bools testMediaBagIO :: String -> FilePath -> IO Test testMediaBagIO name docxFile = do outcome <- compareMediaBagIO docxFile return $ testCase name (assertBool ("Media didn't match media bag in file " ++ docxFile) outcome) testMediaBag :: String -> FilePath -> Test testMediaBag name docxFile = buildTest $ testMediaBagIO name docxFile tests :: [Test] tests = [ testGroup "inlines" [ testCompare "font formatting" "docx/inline_formatting.docx" "docx/inline_formatting.native" , testCompare "font formatting with character styles" "docx/char_styles.docx" "docx/char_styles.native" , testCompare "hyperlinks" "docx/links.docx" "docx/links.native" , testCompare "inline image" "docx/image.docx" "docx/image_no_embed.native" , testCompare "VML image" "docx/image_vml.docx" "docx/image_vml.native" , testCompare "inline image in links" "docx/inline_images.docx" "docx/inline_images.native" , testCompare "handling unicode input" "docx/unicode.docx" "docx/unicode.native" , testCompare "literal tabs" "docx/tabs.docx" "docx/tabs.native" , testCompare "normalizing inlines" "docx/normalize.docx" "docx/normalize.native" , testCompare "normalizing inlines deep inside blocks" "docx/deep_normalize.docx" "docx/deep_normalize.native" , testCompare "move trailing spaces outside of formatting" "docx/trailing_spaces_in_formatting.docx" "docx/trailing_spaces_in_formatting.native" , testCompare "inline code (with VerbatimChar style)" "docx/inline_code.docx" "docx/inline_code.native" ] , testGroup "blocks" [ testCompare "headers" "docx/headers.docx" "docx/headers.native" , testCompare "headers already having auto identifiers" "docx/already_auto_ident.docx" "docx/already_auto_ident.native" , testCompare "numbered headers automatically made into list" "docx/numbered_header.docx" "docx/numbered_header.native" , testCompare "i18n blocks (headers and blockquotes)" "docx/i18n_blocks.docx" "docx/i18n_blocks.native" , testCompare "lists" "docx/lists.docx" "docx/lists.native" , testCompare "definition lists" "docx/definition_list.docx" "docx/definition_list.native" , testCompare "footnotes and endnotes" "docx/notes.docx" "docx/notes.native" , testCompare "blockquotes (parsing indent as blockquote)" "docx/block_quotes.docx" "docx/block_quotes_parse_indent.native" , testCompare "hanging indents" "docx/hanging_indent.docx" "docx/hanging_indent.native" , testCompare "tables" "docx/tables.docx" "docx/tables.native" , testCompare "code block" "docx/codeblock.docx" "docx/codeblock.native" , testCompare "dropcap paragraphs" "docx/drop_cap.docx" "docx/drop_cap.native" ] , testGroup "track changes" [ testCompare "insertion (default)" "docx/track_changes_insertion.docx" "docx/track_changes_insertion_accept.native" , testCompareWithOpts def{readerTrackChanges=AcceptChanges} "insert insertion (accept)" "docx/track_changes_insertion.docx" "docx/track_changes_insertion_accept.native" , testCompareWithOpts def{readerTrackChanges=RejectChanges} "remove insertion (reject)" "docx/track_changes_insertion.docx" "docx/track_changes_insertion_reject.native" , testCompare "deletion (default)" "docx/track_changes_deletion.docx" "docx/track_changes_deletion_accept.native" , testCompareWithOpts def{readerTrackChanges=AcceptChanges} "remove deletion (accept)" "docx/track_changes_deletion.docx" "docx/track_changes_deletion_accept.native" , testCompareWithOpts def{readerTrackChanges=RejectChanges} "insert deletion (reject)" "docx/track_changes_deletion.docx" "docx/track_changes_deletion_reject.native" , testCompareWithOpts def{readerTrackChanges=AllChanges} "keep insertion (all)" "docx/track_changes_deletion.docx" "docx/track_changes_deletion_all.native" , testCompareWithOpts def{readerTrackChanges=AllChanges} "keep deletion (all)" "docx/track_changes_deletion.docx" "docx/track_changes_deletion_all.native" ] , testGroup "media" [ testMediaBag "image extraction" "docx/image.docx" ] , testGroup "metadata" [ testCompareWithOpts def{readerStandalone=True} "metadata fields" "docx/metadata.docx" "docx/metadata.native" , testCompareWithOpts def{readerStandalone=True} "stop recording metadata with normal text" "docx/metadata_after_normal.docx" "docx/metadata_after_normal.native" ] ]
sapek/pandoc
tests/Tests/Readers/Docx.hs
gpl-2.0
9,052
0
16
2,906
1,423
737
686
223
3
module Fibonacci where fibs :: [Integer] fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
NorfairKing/project-euler
lib/haskell/Fibonacci.hs
gpl-2.0
86
0
8
18
40
23
17
3
1
{-# LANGUAGE NoMonomorphismRestriction #-} module Network.BitTorrent.Shepherd.Utils ( if' , maybeToEither , liftMaybe , (.*) , (.**) ) where import Control.Monad import Prelude as P -- UTILS if' c a b = if c then a else b maybeToEither :: a -> Maybe b -> Either a b maybeToEither errorValue = maybe (Left errorValue) (\x -> Right x) liftMaybe :: (MonadPlus m) => Maybe a -> m a liftMaybe = maybe mzero return (.*) :: (c -> d) -> (a -> b -> c) -> (a -> b -> d) (.*) = (.) . (.) (.**) :: (d -> e) -> (a -> b -> c -> d) -> (a -> b -> c -> e) (.**) = (.) . (.*)
danoctavian/shepherd
src/Network/BitTorrent/Shepherd/Utils.hs
gpl-2.0
578
0
10
140
272
159
113
18
2
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- -- Module : IDE.Metainfo.Provider -- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GNU-GPL -- -- Maintainer : <maintainer at leksah.org> -- Stability : provisional -- Portability : portable -- -- | This module provides the infos collected by the server before -- --------------------------------------------------------------------------------- module IDE.Metainfo.Provider ( getIdentifierDescr , getIdentifiersStartingWith , getCompletionOptions , getDescription , getActivePackageDescr , searchMeta , initInfo -- Update and rebuild , updateSystemInfo , rebuildSystemInfo , updateWorkspaceInfo , rebuildWorkspaceInfo , getPackageInfo -- Just retreive from State , getWorkspaceInfo , getSystemInfo , getPackageImportInfo -- Scope for the import tool , getAllPackageIds , getAllPackageIds' ) where import Prelude () import Prelude.Compat hiding(catch, readFile) import System.IO (hClose, openBinaryFile, IOMode(..)) import System.IO.Strict (readFile) import qualified Data.Map as Map import Control.Monad (void, filterM, foldM, liftM, when) import System.FilePath import System.Directory import Data.List (nub, (\\), find, partition, maximumBy, foldl') import Data.Maybe (catMaybes, fromJust, isJust, mapMaybe, fromMaybe) import Distribution.Package hiding (depends,packageId) import qualified Data.Set as Set import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy as BSL import Distribution.Version import Distribution.ModuleName import Control.DeepSeq import IDE.Utils.FileUtils import IDE.Core.State import Data.Char (toLower,isUpper,toUpper,isLower) import Text.Regex.TDFA import qualified Text.Regex.TDFA as Regex import System.IO.Unsafe (unsafePerformIO) import Text.Regex.TDFA.Text (execute,compile) import Data.Binary.Shared (decodeSer) import Language.Haskell.Extension (KnownExtension) import Distribution.Text (display) import IDE.Core.Serializable () import Data.Map (Map(..)) import Control.Exception (SomeException(..), catch) import IDE.Utils.ServerConnection(doServerCommand) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Trans.Class (MonadTrans(..)) import Distribution.PackageDescription (hsSourceDirs) import System.Log.Logger (infoM) import Data.Text (Text) import qualified Data.Text as T (null, isPrefixOf, unpack, pack) import Data.Monoid ((<>)) import qualified Control.Arrow as A (Arrow(..)) import Data.Function (on) import Distribution.Package (PackageIdentifier) -- --------------------------------------------------------------------- -- Updating metadata -- -- -- | Update and initialize metadata for the world -- Called at startup -- initInfo :: IDEAction -> IDEAction initInfo continuation = do prefs <- readIDE prefs if collectAtStart prefs then do ideMessage Normal "Now updating system metadata ..." callCollector False True True $ \ _ -> do ideMessage Normal "Finished updating system metadata" doLoad else doLoad where doLoad = do ideMessage Normal "Now loading metadata ..." loadSystemInfo ideMessage Normal "Finished loading metadata" updateWorkspaceInfo' False $ \ _ -> do void (triggerEventIDE (InfoChanged True)) continuation updateSystemInfo :: IDEAction updateSystemInfo = do liftIO $ infoM "leksah" "update sys info called" updateSystemInfo' False $ \ _ -> updateWorkspaceInfo' False $ \ _ -> void (triggerEventIDE (InfoChanged False)) rebuildSystemInfo :: IDEAction rebuildSystemInfo = do liftIO $ infoM "leksah" "rebuild sys info called" updateSystemInfo' True $ \ _ -> updateWorkspaceInfo' True $ \ _ -> void (triggerEventIDE (InfoChanged False)) updateWorkspaceInfo :: IDEAction updateWorkspaceInfo = do liftIO $ infoM "leksah" "update workspace info called" currentState' <- readIDE currentState case currentState' of IsStartingUp -> return () _ -> updateWorkspaceInfo' False $ \ _ -> void (triggerEventIDE (InfoChanged False)) rebuildWorkspaceInfo :: IDEAction rebuildWorkspaceInfo = do liftIO $ infoM "leksah" "rebuild workspace info called" updateWorkspaceInfo' True $ \ _ -> void (triggerEventIDE (InfoChanged False)) getAllPackageIds :: IDEM [PackageIdentifier] getAllPackageIds = either (const []) id <$> getAllPackageIds' getAllPackageIds' :: IDEM (Either Text [PackageIdentifier]) getAllPackageIds' = do mbWorkspace <- readIDE workspace liftIO . getInstalledPackageIds' $ map ipdPackageDir (maybe [] wsAllPackages mbWorkspace) getAllPackageDBs :: IDEM [[FilePath]] getAllPackageDBs = do mbWorkspace <- readIDE workspace liftIO . getPackageDBs $ map ipdPackageDir (maybe [] wsAllPackages mbWorkspace) -- -- | Load all infos for all installed and exposed packages -- (see shell command: ghc-pkg list) -- loadSystemInfo :: IDEAction loadSystemInfo = do collectorPath <- liftIO getCollectorPath mbPackageIds <- getAllPackageIds' case mbPackageIds of Left e -> logMessage ("Please check that ghc-pkg is in your PATH and restart leksah:\n " <> e) ErrorTag Right packageIds -> do packageList <- liftIO $ mapM (loadInfosForPackage collectorPath) (nub packageIds) let scope = foldr buildScope (PackScope Map.empty getEmptyDefaultScope) $ catMaybes packageList -- liftIO performGC modifyIDE_ (\ide -> ide{systemInfo = Just (GenScopeC (addOtherToScope scope False))}) return () -- -- | Updates the system info -- updateSystemInfo' :: Bool -> (Bool -> IDEAction) -> IDEAction updateSystemInfo' rebuild continuation = do ideMessage Normal "Now updating system metadata ..." wi <- getSystemInfo case wi of Nothing -> loadSystemInfo Just (GenScopeC (PackScope psmap psst)) -> do mbPackageIds <- getAllPackageIds' case mbPackageIds of Left e -> logMessage ("Please check that ghc-pkg is in your PATH and restart leksah:\n " <> e) ErrorTag Right packageIds -> do let newPackages = filter (`Map.member` psmap) packageIds let trashPackages = filter (`notElem` packageIds) (Map.keys psmap) if null newPackages && null trashPackages then continuation True else callCollector rebuild True True $ \ _ -> do collectorPath <- lift getCollectorPath newPackageInfos <- liftIO $ mapM (loadInfosForPackage collectorPath) newPackages let psmap2 = foldr ((\ e m -> Map.insert (pdPackage e) e m) . fromJust) psmap (filter isJust newPackageInfos) let psmap3 = foldr Map.delete psmap2 trashPackages let scope :: PackScope (Map Text [Descr]) = foldr buildScope (PackScope Map.empty symEmpty) (Map.elems psmap3) modifyIDE_ (\ide -> ide{systemInfo = Just (GenScopeC (addOtherToScope scope False))}) continuation True ideMessage Normal "Finished updating system metadata" getEmptyDefaultScope :: Map Text [Descr] getEmptyDefaultScope = symEmpty -- -- | Rebuilds system info -- rebuildSystemInfo' :: (Bool -> IDEAction) -> IDEAction rebuildSystemInfo' continuation = callCollector True True True $ \ _ -> do loadSystemInfo continuation True -- --------------------------------------------------------------------- -- Metadata for the workspace and active package -- updateWorkspaceInfo' :: Bool -> (Bool -> IDEAction) -> IDEAction updateWorkspaceInfo' rebuild continuation = do postAsyncIDE $ ideMessage Normal "Now updating workspace metadata ..." mbWorkspace <- readIDE workspace systemInfo' <- getSystemInfo case mbWorkspace of Nothing -> do liftIO $ infoM "leksah" "updateWorkspaceInfo' no workspace" modifyIDE_ (\ide -> ide{workspaceInfo = Nothing, packageInfo = Nothing}) continuation False Just ws -> updatePackageInfos rebuild (wsAllPackages ws) $ \ _ packDescrs -> do let dependPackIds = nub (concatMap pdBuildDepends packDescrs) \\ map pdPackage packDescrs let packDescrsI = case systemInfo' of Nothing -> [] Just (GenScopeC (PackScope pdmap _)) -> mapMaybe (`Map.lookup` pdmap) dependPackIds let scope1 :: PackScope (Map Text [Descr]) = foldr buildScope (PackScope Map.empty symEmpty) packDescrs let scope2 :: PackScope (Map Text [Descr]) = foldr buildScope (PackScope Map.empty symEmpty) packDescrsI modifyIDE_ (\ide -> ide{workspaceInfo = Just (GenScopeC (addOtherToScope scope1 True), GenScopeC(addOtherToScope scope2 False))}) -- Now care about active package activePack <- readIDE activePack case activePack of Nothing -> modifyIDE_ (\ ide -> ide{packageInfo = Nothing}) Just pack -> case filter (\pd -> pdPackage pd == ipdPackageId pack) packDescrs of [pd] -> let impPackDescrs = case systemInfo' of Nothing -> [] Just (GenScopeC (PackScope pdmap _)) -> mapMaybe (`Map.lookup` pdmap) (pdBuildDepends pd) -- The imported from the workspace should be treated different workspacePackageIds = map ipdPackageId (wsAllPackages ws) impPackDescrs' = filter (\pd -> pdPackage pd `notElem` workspacePackageIds) impPackDescrs impPackDescrs'' = mapMaybe (\ pd -> if pdPackage pd `elem` workspacePackageIds then find (\ pd' -> pdPackage pd == pdPackage pd') packDescrs else Nothing) impPackDescrs scope1 :: PackScope (Map Text [Descr]) = buildScope pd (PackScope Map.empty symEmpty) scope2 :: PackScope (Map Text [Descr]) = foldr buildScope (PackScope Map.empty symEmpty) (impPackDescrs' ++ impPackDescrs'') in modifyIDE_ (\ide -> ide{packageInfo = Just (GenScopeC (addOtherToScope scope1 False), GenScopeC(addOtherToScope scope2 False))}) _ -> modifyIDE_ (\ide -> ide{packageInfo = Nothing}) continuation True postAsyncIDE $ ideMessage Normal "Finished updating workspace metadata" -- | Update the metadata on several packages updatePackageInfos :: Bool -> [IDEPackage] -> (Bool -> [PackageDescr] -> IDEAction) -> IDEAction updatePackageInfos rebuild pkgs continuation = do -- calculate list of known packages once knownPackages <- getAllPackageIds updatePackageInfos' [] knownPackages rebuild pkgs continuation where updatePackageInfos' collector _ _ [] continuation = continuation True collector updatePackageInfos' collector knownPackages rebuild (hd:tail) continuation = updatePackageInfo knownPackages rebuild hd $ \ _ packDescr -> updatePackageInfos' (packDescr : collector) knownPackages rebuild tail continuation -- | Update the metadata on one package updatePackageInfo :: [PackageIdentifier] -> Bool -> IDEPackage -> (Bool -> PackageDescr -> IDEAction) -> IDEAction updatePackageInfo knownPackages rebuild idePack continuation = do liftIO $ infoM "leksah" ("updatePackageInfo " ++ show rebuild ++ " " ++ show (ipdPackageId idePack)) workspInfoCache' <- readIDE workspInfoCache let (packageMap, ic) = case pi `Map.lookup` workspInfoCache' of Nothing -> (Map.empty,True) Just m -> (m,False) modPairsMb <- liftIO $ mapM (\(modName, bi) -> do sf <- case LibModule modName `Map.lookup` packageMap of Nothing -> findSourceFile (srcDirs' bi) haskellSrcExts modName Just (_,Nothing,_) -> findSourceFile (srcDirs' bi) haskellSrcExts modName Just (_,Just fp,_) -> return (Just fp) return (LibModule modName, sf)) $ Map.toList $ ipdModules idePack mainModules <- liftIO $ mapM (\(fn, bi, isTest) -> do mbFn <- findSourceFile' (srcDirs' bi) fn return (MainModule (fromMaybe fn mbFn), mbFn)) (ipdMain idePack) -- we want all Main modules since they may be several with different files let modPairsMb' = mainModules ++ modPairsMb let (modWith,modWithout) = partition (\(x,y) -> isJust y) modPairsMb' let modWithSources = map (A.second fromJust) modWith let modWithoutSources = map fst modWithout -- Now see which modules have to be truely updated modToUpdate <- if rebuild then return modWithSources else liftIO $ figureOutRealSources idePack modWithSources liftIO . infoM "leksah" $ "updatePackageInfo modToUpdate " ++ show (map (displayModuleKey.fst) modToUpdate) callCollectorWorkspace rebuild (ipdPackageDir idePack) (ipdPackageId idePack) (map (\(x,y) -> (T.pack $ display (moduleKeyToName x),y)) modToUpdate) (\ b -> do let buildDepends = findFittingPackages knownPackages (ipdDepends idePack) collectorPath <- liftIO getCollectorPath let packageCollectorPath = collectorPath </> T.unpack (packageIdentifierToString pi) (moduleDescrs,packageMap, changed, modWithout) <- liftIO $ foldM (getModuleDescr packageCollectorPath) ([],packageMap,False,modWithoutSources) modPairsMb' when changed $ modifyIDE_ (\ide -> ide{workspInfoCache = Map.insert pi packageMap workspInfoCache'}) continuation True PackageDescr { pdPackage = pi, pdMbSourcePath = Just $ ipdCabalFile idePack, pdModules = moduleDescrs, pdBuildDepends = buildDepends}) where basePath = normalise $ takeDirectory (ipdCabalFile idePack) srcDirs' bi = map (basePath </>) ("dist/build":hsSourceDirs bi) pi = ipdPackageId idePack figureOutRealSources :: IDEPackage -> [(ModuleKey,FilePath)] -> IO [(ModuleKey,FilePath)] figureOutRealSources idePack modWithSources = do collectorPath <- getCollectorPath let packageCollectorPath = collectorPath </> T.unpack (packageIdentifierToString $ ipdPackageId idePack) filterM (ff packageCollectorPath) modWithSources where ff packageCollectorPath (md ,fp) = do let collectorModulePath = packageCollectorPath </> moduleCollectorFileName md <.> leksahMetadataWorkspaceFileExtension existCollectorFile <- doesFileExist collectorModulePath existSourceFile <- doesFileExist fp if not existSourceFile || not existCollectorFile then return True -- Maybe with preprocessing else do sourceModTime <- getModificationTime fp collModTime <- getModificationTime collectorModulePath return (sourceModTime > collModTime) getModuleDescr :: FilePath -> ([ModuleDescr],ModuleDescrCache,Bool,[ModuleKey]) -> (ModuleKey, Maybe FilePath) -> IO ([ModuleDescr],ModuleDescrCache,Bool,[ModuleKey]) getModuleDescr packageCollectorPath (modDescrs,packageMap,changed,problemMods) (modName,mbFilePath) = case modName `Map.lookup` packageMap of Just (eTime,mbFp,mdescr) -> do existMetadataFile <- doesFileExist moduleCollectorPath if existMetadataFile then do modificationTime <- liftIO $ getModificationTime moduleCollectorPath if modificationTime == eTime then return (mdescr:modDescrs,packageMap,changed,problemMods) else do liftIO . infoM "leksah" $ "getModuleDescr loadInfo: " ++ displayModuleKey modName mbNewDescr <- loadInfosForModule moduleCollectorPath case mbNewDescr of Just newDescr -> return (newDescr:modDescrs, Map.insert modName (modificationTime,mbFilePath,newDescr) packageMap, True, problemMods) Nothing -> return (mdescr:modDescrs,packageMap,changed, modName : problemMods) else return (mdescr:modDescrs,packageMap,changed, modName : problemMods) Nothing -> do existMetadataFile <- doesFileExist moduleCollectorPath if existMetadataFile then do modificationTime <- liftIO $ getModificationTime moduleCollectorPath mbNewDescr <- loadInfosForModule moduleCollectorPath case mbNewDescr of Just newDescr -> return (newDescr:modDescrs, Map.insert modName (modificationTime,mbFilePath,newDescr) packageMap, True, problemMods) Nothing -> return (modDescrs,packageMap,changed, modName : problemMods) else return (modDescrs,packageMap,changed, modName : problemMods) where moduleCollectorPath = packageCollectorPath </> moduleCollectorFileName modName <.> leksahMetadataWorkspaceFileExtension -- --------------------------------------------------------------------- -- Low level helpers for loading metadata -- -- -- | Loads the infos for the given packages -- loadInfosForPackage :: FilePath -> PackageIdentifier -> IO (Maybe PackageDescr) loadInfosForPackage dirPath pid = do let filePath = dirPath </> T.unpack (packageIdentifierToString pid) ++ leksahMetadataSystemFileExtension let filePath2 = dirPath </> T.unpack (packageIdentifierToString pid) ++ leksahMetadataPathFileExtension exists <- doesFileExist filePath if exists then catch (do file <- openBinaryFile filePath ReadMode liftIO . infoM "leksah" . T.unpack $ "now loading metadata for package " <> packageIdentifierToString pid bs <- BSL.hGetContents file let (metadataVersion'::Integer, packageInfo::PackageDescr) = decodeSer bs if metadataVersion /= metadataVersion' then do hClose file throwIDE ("Metadata has a wrong version." <> " Consider rebuilding metadata with: leksah-server -osb +RTS -N2 -RTS") else do packageInfo `deepseq` hClose file exists' <- doesFileExist filePath2 sourcePath <- if exists' then liftM Just (readFile filePath2) else return Nothing let packageInfo' = injectSourceInPack sourcePath packageInfo return (Just packageInfo')) (\ (e :: SomeException) -> do sysMessage Normal ("loadInfosForPackage: " <> packageIdentifierToString pid <> " Exception: " <> T.pack (show e)) return Nothing) else do sysMessage Normal $"packageInfo not found for " <> packageIdentifierToString pid return Nothing injectSourceInPack :: Maybe FilePath -> PackageDescr -> PackageDescr injectSourceInPack Nothing pd = pd{ pdMbSourcePath = Nothing, pdModules = map (injectSourceInMod Nothing) (pdModules pd)} injectSourceInPack (Just pp) pd = pd{ pdMbSourcePath = Just pp, pdModules = map (injectSourceInMod (Just (dropFileName pp))) (pdModules pd)} injectSourceInMod :: Maybe FilePath -> ModuleDescr -> ModuleDescr injectSourceInMod Nothing md = md{mdMbSourcePath = Nothing} injectSourceInMod (Just bp) md = case mdMbSourcePath md of Just sp -> md{mdMbSourcePath = Just (bp </> sp)} Nothing -> md -- -- | Loads the infos for the given module -- loadInfosForModule :: FilePath -> IO (Maybe ModuleDescr) loadInfosForModule filePath = do exists <- doesFileExist filePath if exists then catch (do file <- openBinaryFile filePath ReadMode bs <- BSL.hGetContents file let (metadataVersion'::Integer, moduleInfo::ModuleDescr) = decodeSer bs if metadataVersion /= metadataVersion' then do hClose file throwIDE ("Metadata has a wrong version." <> " Consider rebuilding metadata with -r option") else do moduleInfo `deepseq` hClose file return (Just moduleInfo)) (\ (e :: SomeException) -> do sysMessage Normal (T.pack $ "loadInfosForModule: " ++ show e); return Nothing) else do sysMessage Normal $ "moduleInfo not found for " <> T.pack filePath return Nothing -- | Find the packages fitting the dependencies findFittingPackages :: [PackageIdentifier] -- ^ the list of known packages -> [Dependency] -- ^ the dependencies -> [PackageIdentifier] -- ^ the known packages matching the dependencies findFittingPackages knownPackages = concatMap (fittingKnown knownPackages) where fittingKnown packages (Dependency dname versionRange) = -- find matching packages let filtered = filter (\ (PackageIdentifier name version) -> name == dname && withinRange version versionRange) packages -- take latest version if several versions match in if length filtered > 1 then [maximumBy (compare `on` pkgVersion) filtered] else filtered -- --------------------------------------------------------------------- -- Looking up and searching metadata -- getActivePackageDescr :: IDEM (Maybe PackageDescr) getActivePackageDescr = do mbActive <- readIDE activePack case mbActive of Nothing -> return Nothing Just pack -> do packageInfo' <- getPackageInfo case packageInfo' of Nothing -> return Nothing Just (GenScopeC (PackScope map _), GenScopeC (PackScope _ _)) -> return (ipdPackageId pack `Map.lookup` map) -- -- | Lookup of an identifier description -- getIdentifierDescr :: (SymbolTable alpha, SymbolTable beta) => Text -> alpha -> beta -> [Descr] getIdentifierDescr str st1 st2 = let r1 = str `symLookup` st1 r2 = str `symLookup` st2 in r1 ++ r2 -- -- | Lookup of an identifiers starting with the specified prefix and return a list. -- getIdentifiersStartingWith :: (SymbolTable alpha , SymbolTable beta) => Text -> alpha -> beta -> [Text] getIdentifiersStartingWith prefix st1 st2 = takeWhile (T.isPrefixOf prefix) $ if memberLocal || memberGlobal then prefix : Set.toAscList names else Set.toAscList names where (_, memberLocal, localNames) = Set.splitMember prefix (symbols st1) (_, memberGlobal, globalNames) = Set.splitMember prefix (symbols st2) names = Set.union globalNames localNames getCompletionOptions :: Text -> IDEM [Text] getCompletionOptions prefix = do workspaceInfo' <- getWorkspaceInfo case workspaceInfo' of Nothing -> return [] Just (GenScopeC (PackScope _ symbolTable1), GenScopeC (PackScope _ symbolTable2)) -> return $ getIdentifiersStartingWith prefix symbolTable1 symbolTable2 getDescription :: Text -> IDEM Text getDescription name = do workspaceInfo' <- getWorkspaceInfo case workspaceInfo' of Nothing -> return "" Just (GenScopeC (PackScope _ symbolTable1), GenScopeC (PackScope _ symbolTable2)) -> return $ T.pack (foldr (\d f -> shows (Present d) . showChar '\n' . f) id (getIdentifierDescr name symbolTable1 symbolTable2) "") getPackageInfo :: IDEM (Maybe (GenScope, GenScope)) getPackageInfo = readIDE packageInfo getWorkspaceInfo :: IDEM (Maybe (GenScope, GenScope)) getWorkspaceInfo = readIDE workspaceInfo getSystemInfo :: IDEM (Maybe GenScope) getSystemInfo = readIDE systemInfo -- | Only exported items getPackageImportInfo :: IDEPackage -> IDEM (Maybe (GenScope,GenScope)) getPackageImportInfo idePack = do mbActivePack <- readIDE activePack systemInfo' <- getSystemInfo if isJust mbActivePack && ipdPackageId (fromJust mbActivePack) == ipdPackageId idePack then do packageInfo' <- getPackageInfo case packageInfo' of Nothing -> do liftIO $ infoM "leksah" "getPackageImportInfo: no package info" return Nothing Just (GenScopeC (PackScope pdmap _), _) -> case Map.lookup (ipdPackageId idePack) pdmap of Nothing -> do liftIO $ infoM "leksah" "getPackageImportInfo: package not found in package" return Nothing Just pd -> buildIt pd systemInfo' else do workspaceInfo <- getWorkspaceInfo case workspaceInfo of Nothing -> do liftIO $ infoM "leksah" "getPackageImportInfo: no workspace info" return Nothing Just (GenScopeC (PackScope pdmap _), _) -> case Map.lookup (ipdPackageId idePack) pdmap of Nothing -> do liftIO $ infoM "leksah" "getPackageImportInfo: package not found in workspace" return Nothing Just pd -> buildIt pd systemInfo' where filterPrivate :: ModuleDescr -> ModuleDescr filterPrivate md = md{mdIdDescriptions = filter dscExported (mdIdDescriptions md)} buildIt pd systemInfo' = case systemInfo' of Nothing -> do liftIO $ infoM "leksah" "getPackageImportInfo: no system info" return Nothing Just (GenScopeC (PackScope pdmap' _)) -> let impPackDescrs = mapMaybe (`Map.lookup` pdmap') (pdBuildDepends pd) pd' = pd{pdModules = map filterPrivate (pdModules pd)} scope1 :: PackScope (Map Text [Descr]) = buildScope pd (PackScope Map.empty symEmpty) scope2 :: PackScope (Map Text [Descr]) = foldr buildScope (PackScope Map.empty symEmpty) impPackDescrs in return (Just (GenScopeC scope1, GenScopeC scope2)) -- -- | Searching of metadata -- searchMeta :: Scope -> Text -> SearchMode -> IDEM [Descr] searchMeta _ "" _ = return [] searchMeta (PackageScope False) searchString searchType = do packageInfo' <- getPackageInfo case packageInfo' of Nothing -> return [] Just (GenScopeC (PackScope _ rl), _) -> return (searchInScope searchType searchString rl) searchMeta (PackageScope True) searchString searchType = do packageInfo' <- getPackageInfo case packageInfo' of Nothing -> return [] Just (GenScopeC (PackScope _ rl), GenScopeC (PackScope _ rr)) -> return (searchInScope searchType searchString rl ++ searchInScope searchType searchString rr) searchMeta (WorkspaceScope False) searchString searchType = do workspaceInfo' <- getWorkspaceInfo case workspaceInfo' of Nothing -> return [] Just (GenScopeC (PackScope _ rl), _) -> return (searchInScope searchType searchString rl) searchMeta (WorkspaceScope True) searchString searchType = do workspaceInfo' <- getWorkspaceInfo case workspaceInfo' of Nothing -> return [] Just (GenScopeC (PackScope _ rl), GenScopeC (PackScope _ rr)) -> return (searchInScope searchType searchString rl ++ searchInScope searchType searchString rr) searchMeta SystemScope searchString searchType = do systemInfo' <- getSystemInfo packageInfo' <- getPackageInfo case systemInfo' of Nothing -> case packageInfo' of Nothing -> return [] Just (GenScopeC (PackScope _ rl), _) -> return (searchInScope searchType searchString rl) Just (GenScopeC (PackScope _ s)) -> case packageInfo' of Nothing -> return (searchInScope searchType searchString s) Just (GenScopeC (PackScope _ rl), _) -> return (searchInScope searchType searchString rl ++ searchInScope searchType searchString s) searchInScope :: SymbolTable alpha => SearchMode -> Text -> alpha -> [Descr] searchInScope (Exact _) l st = searchInScopeExact l st searchInScope (Prefix True) l st = (concat . symElems) (searchInScopePrefix l st) searchInScope (Prefix False) l _ | T.null l = [] searchInScope (Prefix False) l st = (concat . symElems) (searchInScopeCaseIns l st "") searchInScope (Regex b) l st = searchRegex l st b searchInScopeExact :: SymbolTable alpha => Text -> alpha -> [Descr] searchInScopeExact = symLookup searchInScopePrefix :: SymbolTable alpha => Text -> alpha -> alpha searchInScopePrefix searchString symbolTable = let (_, exact, mapR) = symSplitLookup searchString symbolTable (mbL, _, _) = symSplitLookup (searchString <> "{") mapR in case exact of Nothing -> mbL Just e -> symInsert searchString e mbL searchInScopeCaseIns :: SymbolTable alpha => Text -> alpha -> Text -> alpha searchInScopeCaseIns a symbolTable b = searchInScopeCaseIns' (T.unpack a) symbolTable (T.unpack b) where searchInScopeCaseIns' [] st _ = st searchInScopeCaseIns' (a:l) st pre | isLower a = let s1 = pre ++ [a] s2 = pre ++ [toUpper a] in symUnion (searchInScopeCaseIns' l (searchInScopePrefix (T.pack s1) st) s1) (searchInScopeCaseIns' l (searchInScopePrefix (T.pack s2) st) s2) | isUpper a = let s1 = pre ++ [a] s2 = pre ++ [toLower a] in symUnion (searchInScopeCaseIns' l (searchInScopePrefix (T.pack s1) st) s1) (searchInScopeCaseIns' l (searchInScopePrefix (T.pack s2) st) s2) | otherwise = let s = pre ++ [a] in searchInScopeCaseIns' l (searchInScopePrefix (T.pack s) st) s searchRegex :: SymbolTable alpha => Text -> alpha -> Bool -> [Descr] searchRegex searchString st caseSense = case compileRegex caseSense searchString of Left err -> unsafePerformIO $ sysMessage Normal (T.pack $ show err) >> return [] Right regex -> filter (\e -> case execute regex (dscName e) of Left e -> False Right Nothing -> False _ -> True) (concat (symElems st)) compileRegex :: Bool -> Text -> Either String Regex compileRegex caseSense searchString = let compOption = defaultCompOpt { Regex.caseSensitive = caseSense , multiline = True } in compile compOption defaultExecOpt searchString -- --------------------------------------------------------------------- -- Handling of scopes -- -- -- | Loads the infos for the given packages (has an collecting argument) -- buildScope :: SymbolTable alpha => PackageDescr -> PackScope alpha -> PackScope alpha buildScope packageD (PackScope packageMap symbolTable) = let pid = pdPackage packageD in if pid `Map.member` packageMap then PackScope packageMap symbolTable else PackScope (Map.insert pid packageD packageMap) (buildSymbolTable packageD symbolTable) buildSymbolTable :: SymbolTable alpha => PackageDescr -> alpha -> alpha buildSymbolTable pDescr symbolTable = foldl' buildScope' symbolTable allDescriptions where allDescriptions = concatMap mdIdDescriptions (pdModules pDescr) buildScope' st idDescr = let allDescrs = allDescrsFrom idDescr in foldl' (\ map descr -> symInsert (dscName descr) [descr] map) st allDescrs allDescrsFrom descr | isReexported descr = [descr] | otherwise = case dscTypeHint descr of DataDescr constructors fields -> descr : map (\(SimpleDescr fn ty loc comm exp) -> Real RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dscMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = FieldDescr descr, dscExported' = exp}) fields ++ map (\(SimpleDescr fn ty loc comm exp) -> Real RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dscMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = ConstructorDescr descr, dscExported' = exp}) constructors ClassDescr _ methods -> descr : map (\(SimpleDescr fn ty loc comm exp) -> Real RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dscMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = MethodDescr descr, dscExported' = exp}) methods NewtypeDescr (SimpleDescr fn ty loc comm exp) mbField -> descr : Real RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dscMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = ConstructorDescr descr, dscExported' = exp} : case mbField of Just (SimpleDescr fn ty loc comm exp) -> [Real RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dscMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = FieldDescr descr, dscExported' = exp}] Nothing -> [] InstanceDescr _ -> [] _ -> [descr] -- --------------------------------------------------------------------- -- Low level functions for calling the collector -- callCollector :: Bool -> Bool -> Bool -> (Bool -> IDEAction) -> IDEAction callCollector scRebuild scSources scExtract cont = do liftIO $ infoM "leksah" "callCollector" scPackageDBs <- getAllPackageDBs doServerCommand SystemCommand {..} $ \ res -> case res of ServerOK -> do liftIO $ infoM "leksah" "callCollector finished" cont True ServerFailed str -> do liftIO $ infoM "leksah" (T.unpack str) cont False _ -> do liftIO $ infoM "leksah" "impossible server answer" cont False callCollectorWorkspace :: Bool -> FilePath -> PackageIdentifier -> [(Text,FilePath)] -> (Bool -> IDEAction) -> IDEAction callCollectorWorkspace rebuild fp pi modList cont = do liftIO $ infoM "leksah" "callCollectorWorkspace" if null modList then do liftIO $ infoM "leksah" "callCollectorWorkspace: Nothing to do" cont True else doServerCommand command $ \ res -> case res of ServerOK -> do liftIO $ infoM "leksah" "callCollectorWorkspace finished" cont True ServerFailed str -> do liftIO $ infoM "leksah" (T.unpack str) cont False _ -> do liftIO $ infoM "leksah" "impossible server answer" cont False where command = WorkspaceCommand { wcRebuild = rebuild, wcPackage = pi, wcPath = fp, wcModList = modList} -- --------------------------------------------------------------------- -- Additions for completion -- keywords :: [Text] keywords = [ "as" , "case" , "of" , "class" , "data" , "default" , "deriving" , "do" , "forall" , "foreign" , "hiding" , "if" , "then" , "else" , "import" , "infix" , "infixl" , "infixr" , "instance" , "let" , "in" , "mdo" , "module" , "newtype" , "qualified" , "type" , "where"] keywordDescrs :: [Descr] keywordDescrs = map (\s -> Real $ RealDescr s Nothing Nothing Nothing (Just (BS.pack "Haskell keyword")) KeywordDescr True) keywords misc :: [(Text, String)] misc = [("--", "Haskell comment"), ("=", "Haskell definition")] miscDescrs :: [Descr] miscDescrs = map (\(s, d) -> Real $ RealDescr s Nothing Nothing Nothing (Just (BS.pack d)) KeywordDescr True) misc extensionDescrs :: [Descr] extensionDescrs = map (\ext -> Real $ RealDescr (T.pack $ "X" ++ show ext) Nothing Nothing Nothing (Just (BS.pack "Haskell language extension")) ExtensionDescr True) ([minBound..maxBound]::[KnownExtension]) moduleNameDescrs :: PackageDescr -> [Descr] moduleNameDescrs pd = map (\md -> Real $ RealDescr (T.pack . display . modu $ mdModuleId md) Nothing (Just (mdModuleId md)) Nothing (Just (BS.pack "Module name")) ModNameDescr True) (pdModules pd) addOtherToScope :: SymbolTable alpha => PackScope alpha -> Bool -> PackScope alpha addOtherToScope (PackScope packageMap symbolTable) addAll = PackScope packageMap newSymbolTable where newSymbolTable = foldl' (\ map descr -> symInsert (dscName descr) [descr] map) symbolTable (if addAll then keywordDescrs ++ extensionDescrs ++ modNameDescrs ++ miscDescrs else modNameDescrs) modNameDescrs = concatMap moduleNameDescrs (Map.elems packageMap)
jaccokrijnen/leksah
src/IDE/Metainfo/Provider.hs
gpl-2.0
42,113
0
32
14,692
9,787
5,002
4,785
741
8
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} module Robots3.Inverse where -- $Id$ import Robots3.Data import Robots3.Config import Robots3.Move import Robots3.Nice import Robots3.Final import Robots3.Examples import Robots3.Quiz import Robots3.Generator import Autolib.Reporter import Autolib.ToDoc import Challenger.Partial import Inter.Types import Inter.Quiz import Data.Maybe ( isJust ) import Data.List ( partition, inits ) instance OrderScore Robots3_Inverse where scoringOrder _ = None -- ? instance Partial Robots3_Inverse [ Zug ] Config where describe _ zs = vcat [ text "Inverse Solar Lockout:" , text "Geben Sie eine Startkonfiguration" , text "mit folgender minimaler Lösungsfolge an:" , nest 4 $ toDoc zs , text "alle Züge sollen ausführbar sein" , text "und erst der letzte Zug löst die Aufgabe." ] initial _ zs = Robots3.Examples.fourty partial _ zs k = do silent $ sequence $ do zs' <- inits zs guard $ zs' /= zs return $ do k' <- executes k zs' when ( is_final k' ) $ reject $ text "Zugfolge ist keine minimale Lösung." valid k total _ zs k = do k' <- executes k zs final k' make :: Make make = direct Robots3_Inverse $ map ( \ (s,d) -> Zug {robot = s, richtung = d} ) $ [("C",W),("E",W),("D",S),("A",O),("D",N),("B",N),("E",N),("D",W),("A",S)] qmake :: Make qmake = quiz Robots3_Inverse Robots3.Quiz.rc
Erdwolf/autotool-bonn
src/Robots3/Inverse.hs
gpl-2.0
1,489
11
19
355
479
262
217
49
1
{-# LANGUAGE OverloadedLists #-} module Kalkulu.Builtin.Function (functionBuiltins) where import Control.Monad import qualified Data.Vector as V import Kalkulu.Builtin import qualified Kalkulu.Pattern as Pattern import qualified Kalkulu.BuiltinSymbol as B functionBuiltins :: [(B.BuiltinSymbol, BuiltinDefinition)] functionBuiltins = [ (B.Function, function) , (B.Slot, slot) , (B.SlotSequence, slotSequence) , (B.Composition, composition) , (B.Identity, identity) , (B.InverseFunction, inverseFunction) ] function :: BuiltinDefinition function = defaultBuiltin { attributes = [HoldAll, Protected] , subcode = subcodeFunction } subcodeFunction :: Expression -> Kernel Expression subcodeFunction (Cmp (Cmp _ [body]) args) = subst body args where subst e@(CmpB B.Slot []) args = case args V.!? 0 of Nothing -> return e -- TODO: send message Just a -> return a subst e@(CmpB B.Slot [Number n]) args = case args V.!? (fromIntegral n) of Nothing -> return e -- TODO: Send Message Just a -> return a subst (CmpB B.SlotSequence []) args = return $ CmpB B.Sequence args subst (CmpB B.SlotSequence [Number n]) args = return $ CmpB B.Sequence (V.drop (fromIntegral n) args) subst (Cmp h as) args = do h' <- subst h args as' <- V.mapM (flip subst args) as return $ Cmp h' as' subst e _ = return e slot :: BuiltinDefinition slot = defaultBuiltin { attributes = [NHoldAll, Protected] } slotSequence :: BuiltinDefinition slotSequence = defaultBuiltin { attributes = [NHoldAll, Protected] } composition :: BuiltinDefinition composition = defaultBuiltin { attributes = [Flat, OneIdentity, Protected] , downcode = return . pureComposition , subcode = subcodeComposition } pureComposition :: Expression -> Expression pureComposition (Cmp _ args) = case nonTrivialArgs of [] -> SymbolB B.Identity [f] -> f _ -> CmpB B.Composition nonTrivialArgs where nonTrivialArgs = V.filter (/= SymbolB B.Identity) args pureComposition _ = error "unreachable" subcodeComposition :: Expression -> Kernel Expression subcodeComposition (Cmp (Cmp _ fs) args) | not (V.null fs) = return $ V.foldr (\f y -> Cmp f [y]) (Cmp (V.last fs) args) (V.init fs) subcodeComposition e = return e identity :: BuiltinDefinition identity = defaultBuiltin { downcode = return . pureIdentity -- TODO: 1 arg } pureIdentity :: Expression -> Expression pureIdentity (Cmp _ [e]) = e pureIdentity e = e inverseFunction :: BuiltinDefinition inverseFunction = defaultBuiltin { attributes = [NHoldAll, Protected] , upcode = upcodeInverseFunction , subcode = subcodeInverseFunction } upcodeInverseFunction :: Expression -> Kernel Expression upcodeInverseFunction (Cmp h [Cmp (CmpB B.InverseFunction [f]) [a]]) | h == f = return a -- send message upcodeInverseFunction (Cmp h [Cmp (CmpB B.InverseFunction [f]) args]) = return $ CmpB B.Identity args -- send message upcodeInverseFunction e = return e subcodeInverseFunction :: Expression -> Kernel Expression subcodeInverseFunction (Cmp (Cmp _ [e]) [Cmp h [a]]) | e == h = return a -- send message subcodeInverseFunction (Cmp (Cmp _ [e]) [Cmp h args]) | e == h = return $ CmpB B.Identity args -- send message subcodeInverseFunction e = return e
vizietto/kalkulu
src/Kalkulu/Builtin/Function.hs
gpl-3.0
3,325
0
12
657
1,158
616
542
81
8
{- My solution to http://codekata.com/kata/kata02-karate-chop/ - Kata #02 from - codekata.com - Author: Donovan Finch - Goal: a binary search of a sorted integer list. - -} chop :: Int -> [Int] -> Int
finchd/kata.hs
karatechop.hs
gpl-3.0
208
0
7
41
21
11
10
1
0
module HLinear.Matrix ( Matrix(..) , IsMatrix(..) , IsMatrixFactorization(..) , MatrixInvertible , (!) , (!?) , fromVectors , fromVectors' , fromLists , fromLists' , fromColumns , fromColumns' , fromVectorsSafe , fromVectorsSafe' , fromListsSafe , fromListsSafe' , fromColumnsSafe , fromColumnsSafe' , toVectors , toLists , toColumns , zipWith , headRows , tailRows , headCols , tailCols , splitAtRows , splitAtCols , sliceRows , sliceCols , zero , isZero , one , isOne , elementary , tensorProduct , transpose , diagonal , blockSum , blockSumRows , blockSumCols , blockMatrix , blockMatrixL , Column(..) ) where import qualified Prelude import HLinear.Matrix.Algebra import HLinear.Matrix.Basic import HLinear.Matrix.Block import HLinear.Matrix.Column ( Column(..) ) import HLinear.Matrix.Definition import HLinear.Matrix.Fraction import HLinear.Matrix.Invertible import HLinear.Matrix.QuickCheck () import HLinear.Matrix.SmallCheck ()
martinra/hlinear
src/HLinear/Matrix.hs
gpl-3.0
1,044
0
6
225
233
158
75
55
0
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} ---------------------------------------------------------------------- -- | -- Module : Text.Doc.Writer.Epub -- Copyright : 2015-2017 Mathias Schenner, -- 2015-2016 Language Science Press. -- License : GPL-3 -- -- Maintainer : mschenner.dev@gmail.com -- Stability : experimental -- Portability : GHC -- -- EPUB writer: Convert Doc to EPUB format. ---------------------------------------------------------------------- module Text.Doc.Writer.Epub ( -- * Doc to EPUB Conversion doc2epub -- * Types , Epub , EpubContainer(..) , EpubData(..) , EpubMedia(..) , EpubMeta(..) , File , TextFile ) where #if MIN_VERSION_base(4,8,0) #else import Control.Applicative import Data.Monoid (mempty) #endif import Codec.Archive.Zip ( Archive, Entry, toEntry, addEntryToArchive , emptyArchive, fromArchive) import Control.Monad (msum) import Data.Bits (clearBit, setBit) import Data.ByteString.Lazy (ByteString) import qualified Data.ByteString.Lazy as BL import Data.Char (isAlpha, isAlphaNum, isAscii) import Data.List (intercalate) import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Maybe (catMaybes, fromMaybe) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL import Data.Time.Clock (UTCTime, getCurrentTime) import Data.Time.Clock.POSIX (getPOSIXTime) import Data.Time.Format ( defaultTimeLocale, iso8601DateFormat , formatTime, parseTimeM) import Data.Word (Word64) import System.FilePath (takeExtension) import System.IO.Error (tryIOError) import System.Random (randomIO) import Text.Blaze (Markup, (!), string, text, stringValue, textValue) import Text.Blaze.Renderer.Text (renderMarkup) import Text.Printf (printf) import Text.Doc.Types import Text.Doc.Section import Text.Doc.Filter.DeriveSection import Text.Doc.Filter.MultiFile import Text.Doc.Writer.Core import Text.Doc.Writer.Html -------------------- Conversion -- | Convert a document to an EPUB file. doc2epub :: Doc -> IO ByteString doc2epub doc = do let mdoc = prepDoc doc epubMeta <- mkEpubMeta mdoc (ndoc, epubMedia) <- extractMedia mdoc timestamp <- getEpochTime return $ writeEpub timestamp (mkEpub ndoc epubMeta epubMedia) -- Convert a raw document to a multi-file document -- with auto-generated notes and bibliography sections. prepDoc :: Doc -> MultiFileDoc prepDoc = toMultiFileDoc 3 . addBibliography . addNotes . doc2secdoc . setHtmlVersion XHTML1 -- Create a structured representation of an EPUB document. mkEpub :: MultiFileDoc -> EpubMeta -> EpubMedia -> Epub mkEpub mdoc epubMeta epubMedia = let epubData = mkEpubData mdoc epubMeta epubCont = mkEpubContainer epubMeta epubData epubMedia in (epubCont, epubData, epubMedia) -- Serialize an EPUB document into its binary form. writeEpub :: EpochTime -> Epub -> ByteString writeEpub timestamp = fromArchive . mkEpubArchive timestamp -- Create a ZIP Archive from a structured EPUB representation. mkEpubArchive :: EpochTime -> Epub -> Archive mkEpubArchive timestamp epub = let mkEntry :: File -> Entry mkEntry (path, content) = toEntry path timestamp content entries = map mkEntry (getEpubFiles epub) in foldr addEntryToArchive emptyArchive entries -- Generate EPUB meta infos. -- -- Requires IO for generating a random UUID and -- for retrieving the current date. -- -- Step 1 of 3 in the EPUB creation pipeline. mkEpubMeta :: MultiFileDoc -> IO EpubMeta mkEpubMeta (MultiFileDoc meta nav _) = do uuid <- newRandomUUID date <- getFormattedDate (concatMap plain (metaDate meta)) let fromInlines = T.pack . concatMap plain return EpubMeta { epubMetaTitle = fromInlines (metaTitle meta) , epubMetaSubTitle = fromInlines (metaSubTitle meta) , epubMetaAuthors = map fromInlines (metaAuthors meta) , epubMetaDate = T.pack date , epubMetaUUID = T.pack uuid , epubMetaNavMap = nav , epubMetaAnchorDB = metaAnchorFileMap meta } -- Generate EPUB data files (content documents). -- -- Step 2 of 3 in the EPUB creation pipeline. mkEpubData :: MultiFileDoc -> EpubMeta -> EpubData mkEpubData doc epubMeta = EpubData { epubTitlePage = ("titlepage.xhtml", htmlTitlePage doc) , epubNavPage = ("toc.xhtml", htmlNavPage doc) , epubBody = M.assocs (mdoc2epubPages doc) , epubNCX = ("toc.ncx", renderMarkup (mkNCX epubMeta)) } -- Generate EPUB container files. -- -- Step 3 of 3 in the EPUB creation pipeline. mkEpubContainer :: EpubMeta -> EpubData -> EpubMedia -> EpubContainer mkEpubContainer epubMeta epubData epubMedia = let opfPath = "content.opf" in EpubContainer { epubOPF = (opfPath, renderMarkup (mkOPF epubMeta epubData epubMedia)) , epubContainerXml = ( "META-INF/container.xml" , renderMarkup (mkContainerXml opfPath)) , epubMimetype = ("mimetype", "application/epub+zip") } -------------------- Types ---------- Files -- | A binary file represented by its file path and content. type File = (FilePath, ByteString) -- | A text file represented by its file path and content. type TextFile = (FilePath, TL.Text) -- Convert a text file to a UTF-8 encoded binary file. toFile :: TextFile -> File toFile = fmap TL.encodeUtf8 ---------- EPUB documents -- | A structured representation of a complete EPUB document. type Epub = (EpubContainer, EpubData, EpubMedia) -- | EPUB top-level packaging files. data EpubContainer = EpubContainer { -- | The package document (OPF). epubOPF :: TextFile -- | The OCF container file (@META-INF/container.xml@). , epubContainerXml :: TextFile -- | The @mimetype@ file. , epubMimetype :: TextFile } deriving (Eq, Show) -- | EPUB textual data files. -- -- This includes all content documents -- as well as title and navigation pages. data EpubData = EpubData { epubTitlePage :: TextFile , epubNavPage :: TextFile , epubBody :: [TextFile] , epubNCX :: TextFile } deriving (Eq, Show) -- | EPUB media files. -- -- This includes all referenced image files. data EpubMedia = EpubMedia { epubMediaCover :: Maybe File , epubMediaFigures :: [File] } deriving (Eq, Show) -- | EPUB document meta information. data EpubMeta = EpubMeta { epubMetaTitle :: Text , epubMetaSubTitle :: Text , epubMetaAuthors :: [Text] , epubMetaDate :: Text , epubMetaUUID :: Text , epubMetaNavMap :: NavList , epubMetaAnchorDB :: AnchorFileMap } deriving (Eq, Show) ---------- Extract files -- Create a list of all files contained in an EPUB document. -- -- Note: The order of these files corresponds to their order in the -- ZIP Archive, so the @mimetype@ file must come first. getEpubFiles :: Epub -> [File] getEpubFiles (ec, ed, em) = map toFile ( getEpubContainerFiles ec ++ getEpubDataFiles ed) ++ getEpubMediaFiles em -- Extract all EPUB textual data files. -- -- Note: The order of these files corresponds to their order in the -- ZIP Archive, so the @mimetype@ file must come first. getEpubContainerFiles :: EpubContainer -> [TextFile] getEpubContainerFiles (EpubContainer opf cont mime) = [mime,cont,opf] -- Extract all EPUB textual data files. getEpubDataFiles :: EpubData -> [TextFile] getEpubDataFiles (EpubData title nav body ncx) = ncx : title : nav : body -- Extract all EPUB media files. getEpubMediaFiles :: EpubMedia -> [File] getEpubMediaFiles (EpubMedia cover figures) = maybe id (:) cover figures ---------- Extract filepaths -- Extract all filepaths of EPUB data documents -- and included media files. -- -- Note: This does not include the filepaths of -- EPUB container files (see @EpubContainer@). getEpubPaths :: EpubData -> EpubMedia -> [FilePath] getEpubPaths epubData epubMedia = getEpubDataPaths epubData ++ getEpubMediaPaths epubMedia -- Extract all filepaths of EPUB data documents. -- -- Note: This does not include the filepaths of -- referenced media files (see @EpubMedia@). getEpubDataPaths :: EpubData -> [FilePath] getEpubDataPaths = map fst . getEpubDataFiles -- Extract all filepaths of EPUB media files. getEpubMediaPaths :: EpubMedia -> [FilePath] getEpubMediaPaths = map fst . getEpubMediaFiles -------------------- IO functions ---------- IO: media files -- Extract and rename media files. extractMedia :: MultiFileDoc -> IO (MultiFileDoc, EpubMedia) extractMedia (MultiFileDoc meta nav body) = do let coverPath = metaCover meta mediaMap = metaMediaMap meta mediaDblPathMap = M.mapWithKey renameMediaFile mediaMap newMediaMap = M.map snd mediaDblPathMap newMeta = meta { metaMediaMap = newMediaMap } figures <- mkMediaFileMap (M.elems mediaDblPathMap) cover <- readCoverImage coverPath return (MultiFileDoc newMeta nav body, EpubMedia cover figures) -- Try to read all referenced media files -- and collect successful results. mkMediaFileMap :: [(Location, Location)] -> IO [File] mkMediaFileMap paths = catMaybes <$> mapM readMediaFile paths -- Try to read a single media file. readMediaFile :: (Location, Location) -> IO (Maybe File) readMediaFile (loc, newloc) = either (const Nothing) (\bs -> Just (T.unpack newloc, bs)) <$> tryIOError (BL.readFile (T.unpack loc)) -- Try to read the cover image. readCoverImage :: Maybe FilePath -> IO (Maybe File) readCoverImage Nothing = return Nothing readCoverImage (Just coverPath) = let ext = takeExtension coverPath in readMediaFile (T.pack coverPath, T.pack (printf "figures/cover%s" ext)) -- Generate a name of a media file based on its -- MediaID and its original file extension. -- Return the original and the new filepath as a pair. renameMediaFile :: MediaID -> Location -> (Location, Location) renameMediaFile i loc = let ext = takeExtension (T.unpack loc) in (loc, T.pack (printf "figures/image-%03d%s" i ext)) ---------- IO: date and time -- | Epoch time is an integer representation of POSIX time. -- -- This is the time format required for Entries in a ZIP Archive. type EpochTime = Integer -- | Get current timestamp as an EpochTime value. getEpochTime :: IO EpochTime getEpochTime = floor <$> getPOSIXTime -- | Create date in @YYYY[-MM[-DD]]@ format. -- -- Try to parse the input string as @YYYY[-MM[-DD]]@ and return it. -- If that fails, format the current day as @YYYY-MM-DD@ (ISO-8601). -- -- Invalid values for month and day will be sanitized to ensure correct -- dates. For example, @\"2016-80\"@ is changed to @\"2016-12\"@. getFormattedDate :: String -> IO String getFormattedDate userDate = let parseUserDateAs :: String -> Maybe UTCTime parseUserDateAs = flip (parseTimeM True defaultTimeLocale) userDate parsedUserDate = msum $ map parseUserDateAs ["%0Y", "%0Y-%m", "%0Y-%m-%d"] formatDate = formatTime defaultTimeLocale (iso8601DateFormat Nothing) in case parsedUserDate of Nothing -> formatDate <$> getCurrentTime Just date -> return $ take (length userDate) (formatDate date) ---------- IO: random -- | Generate a random (version 4) UUID. newRandomUUID :: IO String newRandomUUID = do let setVersion = (`clearBit` 15) . (`setBit` 14) . (`clearBit` 13) . (`clearBit` 12) setVariant = (`setBit` 63) . (`clearBit` 62) upper <- setVersion <$> randomIO :: IO Word64 lower <- setVariant <$> randomIO :: IO Word64 let uuid = concatMap (printf "%016x") [upper, lower] :: String return $ "urn:uuid:" ++ intercalate "-" (splitAtN [8,4,4,4] uuid) -- Split a list at the specified relative prefix lengths. splitAtN :: [Int] -> [a] -> [[a]] splitAtN [] xs = [xs] splitAtN (n:ns) xs = let (ys,zs) = splitAt n xs in ys : splitAtN ns zs -------------------- Generate EPUB packaging files ---------- Generate OCF Container file -- | The OCF Container file (@META-INF/container.xml@). mkContainerXml :: FilePath -> Markup mkContainerXml opfPath = withXmlDeclaration $ el "container" ! attr "version" "1.0" ! attr "xmlns" "urn:oasis:names:tc:opendocument:xmlns:container" $ el "rootfiles" $ leaf "rootfile" ! attr "full-path" (stringValue opfPath) ! attr "media-type" "application/oebps-package+xml" ---------- Generate package document (OPF) -- | The package document (OPF). mkOPF :: EpubMeta -> EpubData -> EpubMedia -> Markup mkOPF epubMeta epubData epubMedia = withXmlDeclaration $ do let idref = stringValue . mkNCName . fst el "package" ! attr "version" "2.0" ! attr "xmlns" "http://www.idpf.org/2007/opf" ! attr "unique-identifier" "BookId" $ do el "metadata" ! attr "xmlns:dc" "http://purl.org/dc/elements/1.1/" ! attr "xmlns:opf" "http://www.idpf.org/2007/opf" $ do el "dc:title" (text (epubMetaTitle epubMeta)) el "dc:language" "en" el "dc:identifier" ! attr "id" "BookId" ! attr "opf:scheme" "UUID" $ text (epubMetaUUID epubMeta) mapM_ ((el "dc:creator" ! attr "opf:role" "aut") . text) (epubMetaAuthors epubMeta) el "dc:date" (text (epubMetaDate epubMeta)) case epubMediaCover epubMedia of Nothing -> mempty Just cover -> leaf "meta" ! attr "name" "cover" ! attr "content" (idref cover) el "manifest" $ mapM_ (opfItem2xml . mkOpfItem) (getEpubPaths epubData epubMedia) el "spine" ! attr "toc" (idref (epubNCX epubData)) $ do leaf "itemref" ! attr "idref" (idref (epubTitlePage epubData)) ! attr "linear" "no" leaf "itemref" ! attr "idref" (idref (epubNavPage epubData)) ! attr "linear" "no" mapM_ (\i -> leaf "itemref" ! attr "idref" (idref i)) (epubBody epubData) -- Representation of an @\<item\>@ entry in the OPF manifest -- in the form: @(id-value, href-value, media-type)@. type OpfItem = (String, FilePath, String) -- Create an OPF manifest item from a filepath. mkOpfItem :: FilePath -> OpfItem mkOpfItem filepath = let idValue = mkNCName filepath mediaType = mimetypeOf filepath in (idValue, filepath, mediaType) -- Create XML fragment for an OPF manifest item. opfItem2xml :: OpfItem -> Markup opfItem2xml (idValue, filepath, mediaType) = leaf "item" ! attr "id" (stringValue idValue) ! attr "href" (stringValue filepath) ! attr "media-type" (stringValue mediaType) -- Convert a filename to a string that is somewhat better suited as -- a value of an @xml:id@ attribute. Does not ensure uniqueness. mkNCName :: FilePath -> String mkNCName [] = "unknown" mkNCName xs@(x:_) = alphaPrefix (map sanitize xs) where -- Prefix underscore if first char is not a letter. alphaPrefix = if isAlpha x then id else ('_':) -- Keep only alphanumeric (or whitelisted) ascii chars, -- replace all other chars by dashes. whitelist = "_-" :: String sanitize c | isAscii c && (isAlphaNum c || c `elem` whitelist) = c | otherwise = '-' -- Guess the MIME Media Type of a file from its name. mimetypeOf :: FilePath -> String mimetypeOf filepath = fromMaybe "application/xhtml+xml" $ -- defaulting to xhtml M.lookup (takeExtension filepath) mimetypeMap -- Simple mapping from filename extensions -- to corresponding MIME Media Types. -- -- Limited to selected EPUB content types. mimetypeMap :: Map String String mimetypeMap = M.fromList [ -- content documents (".xhtml", "application/xhtml+xml") , (".html", "text/html") , (".xml", "application/xml") , (".css", "text/css") -- image formats , (".svg", "image/svg+xml") , (".png", "image/png") , (".jpg", "image/jpeg") , (".jpeg", "image/jpeg") , (".gif", "image/gif") -- epub xml formats , (".ncx", "application/x-dtbncx+xml") ] ---------- Generate NCX file -- | The \"Navigation Center eXtended\" (NCX) file. mkNCX :: EpubMeta -> Markup mkNCX epubMeta = withXmlDeclaration $ el "ncx" ! attr "version" "2005-1" ! attr "xmlns" "http://www.daisy.org/z3986/2005/ncx/" $ do el "head" $ do leaf "meta" ! attr "name" "dtb:uid" ! attr "content" (textValue (epubMetaUUID epubMeta)) leaf "meta" ! attr "name" "dtb:depth" ! attr "content" (stringValue (show (navDepth (epubMetaNavMap epubMeta)))) leaf "meta" ! attr "name" "dtb:totalPageCount" ! attr "content" "0" leaf "meta" ! attr "name" "dtb:maxPageNumber" ! attr "content" "0" el "docTitle" . el "text" . text $ epubMetaTitle epubMeta mapM_ (el "docAuthor" . el "text" . text) (epubMetaAuthors epubMeta) mkNavMap (epubMetaAnchorDB epubMeta) (epubMetaNavMap epubMeta) -- Calculate maximum depth of a NavList -- (for the NCX @\<meta name=\"dtb:depth\"\>@ element). navDepth :: NavList -> Int navDepth xs = maximum (0: map itemDepth xs) where itemDepth (NavListItem _ _ subitems) = 1 + navDepth subitems -- Generate a @\<navMap\>@ element for an NCX file. mkNavMap :: AnchorFileMap -> NavList -> Markup mkNavMap db items = el "navMap" $ mapM_ (mkNavPoint db) items -- Generate a @\<navPoint\>@ element for an NCX file. mkNavPoint :: AnchorFileMap -> NavListItem -> Markup mkNavPoint db (NavListItem anchor title subitems) = let mkNcxAnchorID = textValue . T.append "ncx-" . internalAnchorID in el "navPoint" ! attr "id" (mkNcxAnchorID anchor) $ do el "navLabel" (el "text" (string (concatMap plain title))) leaf "content" ! attr "src" (textValue (internalAnchorTarget db anchor)) mapM_ (mkNavPoint db) subitems
synsem/texhs
src/Text/Doc/Writer/Epub.hs
gpl-3.0
17,448
0
20
3,328
4,028
2,183
1,845
309
2
------------------------------------------------------------------------------ -- -- LANGLANGDATA.HS -- -- Copyright © 2009-2010, Rehno Lindeque. All rights reserved. -- ------------------------------------------------------------------------------ module LangLang.Data where {- DOCUMENTATION -} {- Token for the LangLang programming language (represented as algebraic data types) -} {- INTERFACE -} {- Grammar tokens -} data Literal = LitChar Char | LitString String | LitInt Int | LitFloat Float | LitDouble Double data QueryExpr = SelectionDisjunct --Expression | SelectionExclusiveDisjunct --Expression | SelectionConjunct --IdDecl | SelectionStrictConjunct --IdDecl | MutationDisjunct --IdDecl | MutationExclusiveDisjunct --IdDecl | MutationConjunct --IdDecl | MutationStrictConjunct --IdDecl data Expression = Atom String | Set [Expression] | Query Expression QueryExpr Expression | SetQuery [Expression] QueryExpr Expression | Definition String Expression
rehno-lindeque/poet
src/haskell/LangLang/Data.hs
gpl-3.0
1,425
0
7
568
127
84
43
19
0
module Experiment.Process where import Prelude import System.Directory import System.Environment (</>) :: String -> String -> String d </> f = d ++ "/" ++ f main :: IO() main = do [d] <- getArgs fs <- fmap (filter ((== "time") . take 4)) $ getDirectoryContents d avgs <- mapM (\ f -> do fc <- readFile (d </> f) let ls = lines fc return (drop 4 f , {-sum-} minimum (map (read :: String -> Float) ls) {- / fromIntegral (length ls)-}) ) fs writeFile (d </> "result") (show avgs)
shayan-najd/QFeldspar
Experiment/Process.hs
gpl-3.0
748
0
19
362
225
115
110
18
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.AdExchangeBuyer.PretargetingConfig.List -- 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) -- -- Retrieves a list of the authenticated user\'s pretargeting -- configurations. -- -- /See:/ <https://developers.google.com/ad-exchange/buyer-rest Ad Exchange Buyer API Reference> for @adexchangebuyer.pretargetingConfig.list@. module Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.List ( -- * REST Resource PretargetingConfigListResource -- * Creating a Request , pretargetingConfigList' , PretargetingConfigList' -- * Request Lenses , pclAccountId ) where import Network.Google.AdExchangeBuyer.Types import Network.Google.Prelude -- | A resource alias for @adexchangebuyer.pretargetingConfig.list@ method which the -- 'PretargetingConfigList'' request conforms to. type PretargetingConfigListResource = "adexchangebuyer" :> "v1.4" :> "pretargetingconfigs" :> Capture "accountId" (Textual Int64) :> QueryParam "alt" AltJSON :> Get '[JSON] PretargetingConfigList -- | Retrieves a list of the authenticated user\'s pretargeting -- configurations. -- -- /See:/ 'pretargetingConfigList'' smart constructor. newtype PretargetingConfigList' = PretargetingConfigList'' { _pclAccountId :: Textual Int64 } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'PretargetingConfigList'' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pclAccountId' pretargetingConfigList' :: Int64 -- ^ 'pclAccountId' -> PretargetingConfigList' pretargetingConfigList' pPclAccountId_ = PretargetingConfigList'' { _pclAccountId = _Coerce # pPclAccountId_ } -- | The account id to get the pretargeting configs for. pclAccountId :: Lens' PretargetingConfigList' Int64 pclAccountId = lens _pclAccountId (\ s a -> s{_pclAccountId = a}) . _Coerce instance GoogleRequest PretargetingConfigList' where type Rs PretargetingConfigList' = PretargetingConfigList type Scopes PretargetingConfigList' = '["https://www.googleapis.com/auth/adexchange.buyer"] requestClient PretargetingConfigList''{..} = go _pclAccountId (Just AltJSON) adExchangeBuyerService where go = buildClient (Proxy :: Proxy PretargetingConfigListResource) mempty
rueshyna/gogol
gogol-adexchange-buyer/gen/Network/Google/Resource/AdExchangeBuyer/PretargetingConfig/List.hs
mpl-2.0
3,198
0
12
679
318
194
124
52
1
{-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# LANGUAGE RecordWildCards #-} import Data.Foldable (for_) import Test.Hspec (Spec, describe, it, shouldBe) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) -- base >= 4.8 re-exports Control.Applicative.(<$>). import Control.Applicative -- This is only need for <$>, if GHC < 7.10. import Prelude -- This trick avoids a warning if GHC >= 7.10. import SumOfMultiples (sumOfMultiples) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = describe "sum-of-multiples" $ describe "sumOfMultiples" $ for_ cases test where test Case{..} = it description assertion where description = unwords [show factors, show limit] assertion = expression `shouldBe` fromIntegral expected expression = sumOfMultiples (fromIntegral <$> factors) (fromIntegral limit ) -- Test cases adapted from `exercism/x-common/sum-of-multiples.json` on 2016-07-27. data Case = Case { factors :: [Integer] , limit :: Integer , expected :: Integer } cases :: [Case] cases = [ Case { factors = [3, 5] , limit = 1 , expected = 0 } , Case { factors = [3, 5] , limit = 4 , expected = 3 } , Case { factors = [3, 5] , limit = 10 , expected = 23 } , Case { factors = [3, 5] , limit = 100 , expected = 2318 } , Case { factors = [3, 5] , limit = 1000 , expected = 233168 } , Case { factors = [7, 13, 17] , limit = 20 , expected = 51 } , Case { factors = [4, 6] , limit = 15 , expected = 30 } , Case { factors = [5, 6, 8] , limit = 150 , expected = 4419 } , Case { factors = [5, 25] , limit = 51 , expected = 275 } , Case { factors = [43, 47] , limit = 10000 , expected = 2203160 } , Case { factors = [1] , limit = 100 , expected = 4950 } , Case { factors = [] , limit = 10000 , expected = 0 } ]
daewon/til
exercism/haskell/sum-of-multiples/test/Tests.hs
mpl-2.0
2,622
0
11
1,200
596
369
227
58
1
{-# LANGUAGE Arrows, FlexibleContexts #-} module BoTox.Bots.RollBot where import BoTox.Types import BoTox.Utils import BoTox.Utils.DiceParser import Control.Auto hiding (many) import Control.Auto.Effects import Control.Monad import Control.Monad.IO.Class import Data.Function (on) import Data.List import Prelude hiding ((.), id) import System.Random (randomRIO, newStdGen) import Text.Parsec rollBot :: MonadIO m => GroupBot m rollBot = proc event -> do infaCmds <- parseGroupBotCmd ["%инфа", "%info"] infaArgsParser -< event doCmds <- parseGroupBotCmd ["%зделоть", "%делать"] doArgsParser -< event diceCmds <- parseGroupBotCmd ["%dice", "%d", "%к"] diceArgsParser -< event outInfaCmds <- fromBlips mempty . arrMB (liftIO . doInfa) -< infaCmds outDoCmds <- fromBlips mempty . arrMB (liftIO . doDo) -< doCmds outDiceCmds <- fromBlips mempty . arrMB (liftIO . doDice) -< diceCmds id -< mconcat [outInfaCmds, outDoCmds, outDiceCmds] where infaArgsParser = leftOvers diceArgsParser = diceParser `sepBy` (char ',' *> spaces) doArgsParser = (many (noneOf ",")) `sepBy` (char ',' *> spaces) doDo (Right strs) = do vals <- liftIO $ forM strs $ \x -> (randomRIO (0,1000) :: IO Integer) >>= return . (,) x let v = sortVs vals let s = sum . snd . unzip $ v let outstr = intercalate "\n" $ map (\(ss,x) -> ss ++ " - " ++ show (x * 100 `div` s) ++ "%") v return $ groupBotSay outstr doDo (Left err) = return . groupBotSay . show $ err sortVs :: [(String, Integer)] -> [(String, Integer)] sortVs = sortBy (flip compare `on` snd) doInfa (Right str) = do rinfa <- randomRIO (0,146) :: IO Integer return $ groupBotSay $ str ++ " - инфа " ++ show rinfa ++ "%" doInfa (Left err) = return . groupBotSay . show $ err doDice (Right dice) = do diceStrs <- mapM getDiceStr dice return $ groupBotSay $ intercalate "\n" diceStrs doDice (Left err) = return . groupBotSay . show $ err getDiceStr diceExpr = do gen <- newStdGen let (s, _) = evalDiceStr diceExpr gen let (val, _) = evalDice diceExpr gen return $ s ++ " = " ++ show val
gordon-quad/botox
src/BoTox/Bots/RollBot.hs
agpl-3.0
2,179
8
21
478
846
432
414
48
4
import Control.Concurrent(forkIO,threadDelay) import Data.ByteString(ByteString,pack) import Data.Char(ord) import Data.Time(UTCTime,addUTCTime,getCurrentTime) import Data.Word(Word32) import Network(PortNumber,Socket,sClose,withSocketsDo) import System.Environment(getArgs) import Cache( Cache(get,set,add,replace,delete,expire), CacheError(EntryExists,NotFound,VersionMismatch,UnknownError), Expires(Expires),Timestamp(Timestamp),Version(Version)) import Listener(listener) import Logger(Logger,nullLogger,debugLogger) import Protocol( readPacket, writeResponse, packetCmd, packetVersion, packetExtras, packetKey, packetValue, makeFlags, getExpiry, getFlags, magicRequest, cmdGet, cmdSet, cmdAdd, cmdReplace, cmdDelete, cmdQuit, statusNoError, statusKeyNotFound, statusKeyExists, statusItemNotStored, statusNotSupported, statusInternalError) import TrieCache(newTrieCache) main :: IO () main = withSocketsDo $ do (logger,port) <- fmap (parseArgs nullLogger defaultPort) getArgs cache <- newTrieCache forkIO $ sequence_ $ repeat $ expirer cache listener port (handler logger cache) where expirer cache = do threadDelay 15000000 t <- getCurrentTime expire cache (Timestamp t) defaultPort :: PortNumber defaultPort = fromIntegral 22122 parseArgs :: Logger -> PortNumber -> [String] -> (Logger,PortNumber) parseArgs logger portNumber ("-d":args) = parseArgs (debugLogger "server") portNumber args parseArgs logger portNumber (arg:args) = parseArgs logger (parsePort portNumber arg) args parseArgs logger portNumber [] = (logger,portNumber) parsePort :: PortNumber -> String -> PortNumber parsePort portNumber arg = case reads arg of [(number,"")] -> fromIntegral number _ -> portNumber handler :: Cache cache => Logger -> cache UTCTime (Word32,ByteString) -> Socket -> IO () handler logger cache socket = do maybePacket <- readPacket logger socket magicRequest time <- getCurrentTime maybe (sClose socket) (handle (Timestamp time)) maybePacket where handle time packet = handleCmd (packetCmd packet) (packetExtras packet) (packetKey packet) (packetValue packet) where handleCmd cmd [] (Just key) Nothing | cmd == cmdGet = do result <- get cache key time sendGetResult result | cmd == cmdDelete = do result <- delete cache key requestVersion time sendDeleteResult result | otherwise = sendStatus statusNotSupported errorValue where sendGetResult (Right ((flags,value),Version version)) = do writeResponse logger socket packet statusNoError version [makeFlags flags] Nothing (Just value) handler logger cache socket sendGetResult (Left NotFound) = sendStatus statusKeyNotFound errorValue sendGetResult _ = sendStatus statusInternalError errorValue sendDeleteResult Nothing = sendStatus statusNoError Nothing sendDeleteResult (Just NotFound) = sendStatus statusKeyNotFound errorValue sendDeleteResult (Just VersionMismatch) = sendStatus statusItemNotStored errorValue sendDeleteResult _ = sendStatus statusInternalError errorValue handleCmd cmd [extras] (Just key) (Just value) | cmd == cmdSet = do result <- set cache key (flags,value) expires time sendResult result | cmd == cmdAdd = do result <- add cache key (flags,value) expires time sendResult result | cmd == cmdReplace = do result <- replace cache key requestVersion (flags,value) expires time sendResult result | otherwise = sendStatus statusNotSupported errorValue where expires = Expires $ getExpiry extras 4 `addUTCTime` (let Timestamp t = time in t) flags = getFlags extras 0 sendResult (Right (Version version)) = do writeResponse logger socket packet statusNoError version [] Nothing Nothing handler logger cache socket sendResult (Left EntryExists) = sendStatus statusKeyExists errorValue sendResult (Left NotFound) = sendStatus statusKeyNotFound errorValue sendResult (Left VersionMismatch) = sendStatus statusItemNotStored errorValue handleCmd cmd [] Nothing Nothing | cmd == cmdQuit = do writeResponse logger socket packet statusNoError 0 [] Nothing Nothing sClose socket | otherwise = sendStatus statusNotSupported errorValue handleCmd _ _ _ _ = sendStatus statusNotSupported errorValue errorValue = Just $ pack $ map (fromIntegral . ord) "error" requestVersion = Version $ packetVersion packet sendStatus status value = do writeResponse logger socket packet status 0 [] Nothing value handler logger cache socket
qpliu/lecache
hs/server.hs
lgpl-3.0
5,223
3
13
1,454
1,477
748
729
109
12
module Handler.Home where import Import -- This is a handler function for the GET request method on the HomeR -- resource pattern. All of your resource patterns are defined in -- config/routes -- -- The majority of the code you will write in Yesod lives in these handler -- functions. You can spread them across multiple files if you are so -- inclined, or create a single monolithic file. getHomeR :: Handler Html getHomeR = do maid <- maybeAuthId defaultLayout $ do aDomId <- newIdent setTitle "Haverer" $(widgetFile "homepage")
jml/haverer-api
Handler/Home.hs
apache-2.0
565
0
12
123
66
35
31
9
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE StaticPointers #-} module MapIOSpec where import Spark import Data.List (sort) import Control.Monad import Control.Distributed.Process import Control.Distributed.Static hiding (initRemoteTable) import Control.Distributed.Process.Closure import Control.Distributed.Process.Node import Network.Transport.TCP (createTransport, defaultTCPParameters) import Test.Framework.Providers.HUnit import Test.HUnit import Control.Concurrent import Control.Concurrent.MVar iDict :: SerializableDict [Int] iDict = SerializableDict square :: Int -> Int square x = x * x squareIO :: Int -> IO Int squareIO x = return (x * x) staticSquare :: Closure (Int -> IO Int) staticSquare = staticClosure $ staticPtr $ static squareIO input :: [Int] -> [Int] input = id remotable ['iDict, 'input] mapRemoteTable = Spark.remoteTable . MapIOSpec.__remoteTable $ initRemoteTable mapIOTest t = let dt = [1..10] :: [Int] in do node <- newLocalNode t mapRemoteTable slave0 <- newLocalNode t mapRemoteTable slave1 <- newLocalNode t mapRemoteTable sc <- createContextFrom mapRemoteTable (localNodeId node) [localNodeId slave0, localNodeId slave1] out <- newEmptyMVar runProcess node $ do let srdd = seedRDD sc (Just 2) $(mkStatic 'iDict) ( $(mkClosure 'input) dt) mrdd = mapRDDIO sc srdd $(mkStatic 'iDict) staticSquare dict = SerializableDict :: SerializableDict [Int] thispid <- getSelfPid output <- collect sc dict mrdd liftIO $ putMVar out output liftIO $ putStrLn $ "Output: " ++ (show output) closeLocalNode slave1 closeLocalNode slave0 closeLocalNode node os <- takeMVar out let squares = map square dt (sort squares) @=? (sort os)
yogeshsajanikar/hspark
test/MapIOSpec.hs
apache-2.0
1,915
0
20
484
557
286
271
51
1
module Positron.Util ( toByteString , for ) where import Positron.Import -- data types import qualified Data.ByteString.Builder as B import qualified Data.ByteString.Lazy as LB (toStrict) toByteString :: Builder -> ByteString toByteString = LB.toStrict . B.toLazyByteString for :: Functor f => f a -> (a -> b) -> f b for = flip fmap
xtendo-org/positron
library/Positron/Util.hs
apache-2.0
350
0
9
69
106
62
44
10
1
{-# LANGUAGE OverloadedStrings #-} module ScoreSpec (spec) where import Prelude hiding (minimum) import Test.Hspec import Score (Input(..), Choice(..), minimum, score) spec :: Spec spec = do describe "minimum" $ do it "is a safe version of Prelude.minimum that does not choke on empty inputs" $ minimum ([] :: [Int]) `shouldBe` Nothing it "finds a minimum value in the list" $ minimum [4, 6, 7, 1, 8] `shouldBe` Just 1 describe "score" $ do it "is maximal when the input is empty" $ score (Input "") (Choice "foo") `shouldBe` maxBound it "is minimal when the choice is empty" $ score (Input "foo") (Choice "") `shouldBe` minBound it "is minimal when the input is not a substring of the choice" $ score (Input "foo") (Choice "bar") `shouldBe` minBound it "is greater than minimum when the input is a substring of the choice" $ score (Input "foo") (Choice "fbarobazo") `compare` minBound `shouldBe` GT it "is greater for the input with a shorter substring" $ let s = score (Input "foo") (Choice "fbarobazo") t = score (Input "foo") (Choice "frozo") in compare s t `shouldBe` LT
supki/wybor
test/ScoreSpec.hs
bsd-2-clause
1,191
0
17
297
355
185
170
26
1
{-# LANGUAGE CPP, NoImplicitPrelude, DeriveDataTypeable #-} #if __GLASGOW_HASKELL__ >= 704 {-# LANGUAGE Trustworthy #-} #endif {-# OPTIONS_HADDOCK hide #-} -------------------------------------------------------------------------------- -- | -- Module : System.USB.IO.StandardDeviceRequests -- Copyright : (c) 2009–2014 Bas van Dijk -- License : BSD3 (see the file LICENSE) -- Maintainer : Bas van Dijk <v.dijk.bas@gmail.com> -- -- /This module is for testing purposes only!/ -- -- This module provides functions for performing standard device requests. -- The functions are primarily used for testing USB devices. -- -- To avoid name clashes with functions from @System.USB@ it is advised to use -- an explicit import list or a qualified import. -- -------------------------------------------------------------------------------- module System.USB.IO.StandardDeviceRequests ( setHalt , setConfig, getConfig , clearRemoteWakeup , setRemoteWakeup , setStandardTestMode, TestMode(..) , getInterfaceAltSetting , getDeviceStatus , getEndpointStatus , setDeviceAddress , synchFrame, FrameNumber ) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- -- from base: import Data.Bits ( testBit, shiftL ) import Data.Bool ( Bool ) import Data.Data ( Data ) import Data.Eq ( Eq, (==) ) import Data.Function ( ($), (.) ) import Data.Functor ( fmap ) import Data.Maybe ( Maybe(Nothing, Just), maybe ) import Data.Typeable ( Typeable ) import Data.Word ( Word8, Word16 ) import Prelude ( (+), (*), fromIntegral, Enum ) import System.IO ( IO ) import Text.Read ( Read ) import Text.Show ( Show ) #if __GLASGOW_HASKELL__ < 700 import Prelude ( fromInteger ) #endif -- from bytestring: import qualified Data.ByteString as B ( ByteString, head, unpack ) -- from bindings-libusb: import Bindings.Libusb ( c'LIBUSB_REQUEST_SET_FEATURE , c'LIBUSB_REQUEST_SET_CONFIGURATION , c'LIBUSB_REQUEST_GET_CONFIGURATION , c'LIBUSB_REQUEST_CLEAR_FEATURE , c'LIBUSB_REQUEST_GET_INTERFACE , c'LIBUSB_REQUEST_GET_STATUS , c'LIBUSB_REQUEST_SET_ADDRESS , c'LIBUSB_REQUEST_SYNCH_FRAME ) -- from usb: import System.USB.DeviceHandling ( DeviceHandle , ConfigValue , InterfaceNumber , InterfaceAltSetting ) #if __HADDOCK__ import qualified System.USB.DeviceHandling as USB ( setConfig, getConfig ) #endif import System.USB.Descriptors ( EndpointAddress , DeviceStatus(..) ) import System.USB.IO ( Timeout , ControlSetup(..) , RequestType(Standard) , Recipient( ToDevice , ToInterface , ToEndpoint ) , Value , control, readControlExact ) import System.USB.Base ( marshalEndpointAddress ) import Utils ( genFromEnum ) -------------------------------------------------------------------------------- -- Standard Device Requests ------------------------------------------------------------------------------- -- See: USB 2.0 Spec. section 9.4 -- Standard Feature Selectors: -- See: USB 2.0 Spec. table 9-6 haltFeature, remoteWakeupFeature, testModeFeature :: Value haltFeature = 0 remoteWakeupFeature = 1 testModeFeature = 2 -- | See: USB 2.0 Spec. section 9.4.9 setHalt :: DeviceHandle -> EndpointAddress -> (Timeout -> IO ()) setHalt devHndl endpointAddr = control devHndl ControlSetup { controlSetupRequestType = Standard , controlSetupRecipient = ToEndpoint , controlSetupRequest = c'LIBUSB_REQUEST_SET_FEATURE , controlSetupValue = haltFeature , controlSetupIndex = marshalEndpointAddress endpointAddr } -- | See: USB 2.0 Spec. section 9.4.7 -- -- /This function is for testing purposes only!/ -- -- You should normally use @System.USB.DeviceHandling.'USB.setConfig'@ because -- that function notifies the underlying operating system about the changed -- configuration. setConfig :: DeviceHandle -> Maybe ConfigValue -> (Timeout -> IO ()) setConfig devHndl mbConfigValue = control devHndl ControlSetup { controlSetupRequestType = Standard , controlSetupRecipient = ToDevice , controlSetupRequest = c'LIBUSB_REQUEST_SET_CONFIGURATION , controlSetupValue = marshal mbConfigValue , controlSetupIndex = 0 } where marshal :: Maybe ConfigValue -> Value marshal = maybe 0 fromIntegral -- | See: USB 2.0 Spec. section 9.4.2 -- -- /This function is for testing purposes only!/ -- -- You should normally use @System.USB.DeviceHandling.'USB.getConfig'@ because -- that functon may exploit operating system caches (no I/O involved). getConfig :: DeviceHandle -> (Timeout -> IO (Maybe ConfigValue)) getConfig devHndl = fmap (unmarshal . B.head) . readControlExact devHndl ctrlSetup 1 where ctrlSetup = ControlSetup { controlSetupRequestType = Standard , controlSetupRecipient = ToDevice , controlSetupRequest = c'LIBUSB_REQUEST_GET_CONFIGURATION , controlSetupValue = 0 , controlSetupIndex = 0 } unmarshal :: Word8 -> Maybe ConfigValue unmarshal 0 = Nothing unmarshal n = Just $ fromIntegral n -- | See: USB 2.0 Spec. section 9.4.1 clearRemoteWakeup :: DeviceHandle -> (Timeout -> IO ()) clearRemoteWakeup devHndl = control devHndl ControlSetup { controlSetupRequestType = Standard , controlSetupRecipient = ToDevice , controlSetupRequest = c'LIBUSB_REQUEST_CLEAR_FEATURE , controlSetupValue = remoteWakeupFeature , controlSetupIndex = 0 } -- | See: USB 2.0 Spec. section 9.4.9 setRemoteWakeup :: DeviceHandle -> (Timeout -> IO ()) setRemoteWakeup devHndl = control devHndl ControlSetup { controlSetupRequestType = Standard , controlSetupRecipient = ToDevice , controlSetupRequest = c'LIBUSB_REQUEST_SET_FEATURE , controlSetupValue = remoteWakeupFeature , controlSetupIndex = 0 } -- | See: USB 2.0 Spec. section 9.4.9 -- TODO: What about vendor-specific test modes? setStandardTestMode :: DeviceHandle -> TestMode -> (Timeout -> IO ()) setStandardTestMode devHndl testMode = control devHndl ControlSetup { controlSetupRequestType = Standard , controlSetupRecipient = ToDevice , controlSetupRequest = c'LIBUSB_REQUEST_SET_FEATURE , controlSetupValue = testModeFeature , controlSetupIndex = (genFromEnum testMode + 1) `shiftL` 8 } -- | See: USB 2.0 Spec. table 9-7 data TestMode = Test_J | Test_K | Test_SE0_NAK | Test_Packet | Test_Force_Enable deriving (Eq, Show, Read, Enum, Data, Typeable) -- | See: USB 2.0 Spec. section 9.4.4 getInterfaceAltSetting :: DeviceHandle -> InterfaceNumber -> (Timeout -> IO InterfaceAltSetting) getInterfaceAltSetting devHndl ifNum = fmap B.head . readControlExact devHndl ctrlSetup 1 where ctrlSetup = ControlSetup { controlSetupRequestType = Standard , controlSetupRecipient = ToInterface , controlSetupRequest = c'LIBUSB_REQUEST_GET_INTERFACE , controlSetupValue = 0 , controlSetupIndex = fromIntegral ifNum } -- | See: USB 2.0 Spec. section 9.4.5 getDeviceStatus :: DeviceHandle -> (Timeout -> IO DeviceStatus) getDeviceStatus devHndl = fmap (unmarshal . B.head) . readControlExact devHndl ctrlSetup 2 where ctrlSetup = ControlSetup { controlSetupRequestType = Standard , controlSetupRecipient = ToDevice , controlSetupRequest = c'LIBUSB_REQUEST_GET_STATUS , controlSetupValue = 0 , controlSetupIndex = 0 } unmarshal :: Word8 -> DeviceStatus unmarshal a = DeviceStatus { remoteWakeup = testBit a 1 , selfPowered = testBit a 0 } -- | See: USB 2.0 Spec. section 9.4.5 getEndpointStatus :: DeviceHandle -> EndpointAddress -> (Timeout -> IO Bool) getEndpointStatus devHndl endpointAddr = fmap ((1 ==) . B.head) . readControlExact devHndl ctrlSetup 2 where ctrlSetup = ControlSetup { controlSetupRequestType = Standard , controlSetupRecipient = ToEndpoint , controlSetupRequest = c'LIBUSB_REQUEST_GET_STATUS , controlSetupValue = 0 , controlSetupIndex = marshalEndpointAddress endpointAddr } -- | See: USB 2.0 Spec. section 9.4.6 setDeviceAddress :: DeviceHandle -> Word16 -> (Timeout -> IO ()) setDeviceAddress devHndl deviceAddr = control devHndl ControlSetup { controlSetupRequestType = Standard , controlSetupRecipient = ToDevice , controlSetupRequest = c'LIBUSB_REQUEST_SET_ADDRESS , controlSetupValue = deviceAddr , controlSetupIndex = 0 } -- TODO: setDescriptor See: USB 2.0 Spec. section 9.4.8 -- TODO Sync Frame klopt niet helemaal, je kunt met deze request ook het frame number setten! {-| This request is used to set and then report an endpoint's synchronization frame. When an endpoint supports isochronous transfers, the endpoint may also require per-frame transfers to vary in size according to a specific pattern. The host and the endpoint must agree on which frame the repeating pattern begins. The number of the frame in which the pattern began is returned to the host. If a high-speed device supports the Synch Frame request, it must internally synchronize itself to the zeroth microframe and have a time notion of classic frame. Only the frame number is used to synchronize and reported by the device endpoint (i.e., no microframe number). The endpoint must synchronize to the zeroth microframe. This value is only used for isochronous data transfers using implicit pattern synchronization. If the specified endpoint does not support this request, then the device will respond with a Request Error. See: USB 2.0 Spec. section 9.4.11 -} synchFrame :: DeviceHandle -> EndpointAddress -> (Timeout -> IO FrameNumber) synchFrame devHndl endpointAddr = fmap unmarshal . readControlExact devHndl ctrlSetup 2 where ctrlSetup = ControlSetup { controlSetupRequestType = Standard , controlSetupRecipient = ToEndpoint , controlSetupRequest = c'LIBUSB_REQUEST_SYNCH_FRAME , controlSetupValue = 0 , controlSetupIndex = marshalEndpointAddress endpointAddr } unmarshal :: B.ByteString -> FrameNumber unmarshal bs = let [h, l] = B.unpack bs in fromIntegral h * 256 + fromIntegral l -- | Endpoint's synchronization frame. type FrameNumber = Word16
alex1818/usb
System/USB/IO/StandardDeviceRequests.hs
bsd-3-clause
11,557
2
12
3,162
1,606
963
643
167
2
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilyDependencies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ViewPatterns #-} ----------------------------------------------------------------------------- -- | -- Module : Numeric.Tuple.Lazy -- Copyright : (c) Artem Chirkin -- License : BSD3 -- -- ----------------------------------------------------------------------------- module Numeric.Tuple.Lazy ( Id (..), Tuple , TypedList (U, (:*), (:$), (:!), Empty, TypeList, Cons, Snoc, Reverse) , (*$), ($*), (*!), (!*) ) where import Control.Arrow (first) import Control.Monad.Fix import Control.Monad.Zip import Data.Bits (Bits, FiniteBits) import Data.Coerce import Data.Data (Data) import Data.Foldable import Data.Functor.Classes import Data.Ix (Ix) import Data.Monoid as Mon (Monoid (..)) import Data.Semigroup as Sem (Semigroup (..)) import Data.String (IsString) import Foreign.Storable (Storable) import GHC.Base (Type, Any) import GHC.Generics (Generic, Generic1) import qualified Text.Read as P import Unsafe.Coerce (unsafeCoerce) import Data.Type.List import Numeric.TypedList -- | This is an almost complete copy of `Data.Functor.Identity` -- by (c) Andy Gill 2001. newtype Id a = Id { runId :: a } deriving ( Bits, Bounded, Data, Enum, Eq, FiniteBits, Floating, Fractional , Generic, Generic1, Integral, IsString, Ix, Monoid, Num, Ord , Real, RealFrac, RealFloat, Semigroup, Storable, Traversable) instance Read a => Read (Id a) where readsPrec d = fmap (first Id) . readsPrec d instance Show a => Show (Id a) where showsPrec d = showsPrec d . runId instance Read1 Id where liftReadPrec r _ = coerce r liftReadListPrec = liftReadListPrecDefault liftReadList = liftReadListDefault instance Show1 Id where liftShowsPrec f _ = coerce f instance Eq1 Id where liftEq = coerce instance Ord1 Id where liftCompare = coerce instance Foldable Id where foldMap = coerce elem = k (==) where k :: (a -> a -> Bool) -> a -> Id a -> Bool k = coerce foldl = coerce foldl' = coerce foldl1 _ = coerce foldr f z (Id x) = f x z foldr' = foldr foldr1 _ = coerce length _ = 1 maximum = coerce minimum = coerce null _ = False product = coerce sum = coerce toList (Id x) = [x] instance Functor Id where fmap = coerce instance Applicative Id where pure = Id (<*>) = coerce instance Monad Id where m >>= k = k (runId m) instance MonadFix Id where mfix f = Id (fix (runId . f)) instance MonadZip Id where mzipWith = coerce munzip = coerce -- | A tuple indexed by a list of types type Tuple = (TypedList Id :: [Type] -> Type) {-# COMPLETE U, (:$) #-} {-# COMPLETE U, (:!) #-} {-# COMPLETE Empty, (:$) #-} {-# COMPLETE Empty, (:!) #-} -- | Constructing a type-indexed list pattern (:$) :: forall (xs :: [Type]) . () => forall (y :: Type) (ys :: [Type]) . (xs ~ (y ': ys)) => y -> Tuple ys -> Tuple xs pattern (:$) x xs <- (Id x :* xs) where (:$) = (*$) infixr 5 :$ -- | Constructing a type-indexed list pattern (:!) :: forall (xs :: [Type]) . () => forall (y :: Type) (ys :: [Type]) . (xs ~ (y ': ys)) => y -> Tuple ys -> Tuple xs pattern (:!) x xs <- (forceCons -> Id x :* xs) where (:!) = (*!) infixr 5 :! -- | Grow a tuple on the left O(1). (*$) :: x -> Tuple xs -> Tuple (x :+ xs) (*$) x xs = unsafeCoerce (unsafeCoerce x : unsafeCoerce xs :: [Any]) {-# INLINE (*$) #-} infixr 5 *$ -- | Grow a tuple on the left while evaluating arguments to WHNF O(1). (*!) :: x -> Tuple xs -> Tuple (x :+ xs) (*!) !x !xs = let !r = unsafeCoerce x : unsafeCoerce xs :: [Any] in unsafeCoerce r {-# INLINE (*!) #-} infixr 5 *! -- | Grow a tuple on the right. -- Note, it traverses an element list inside O(n). ($*) :: Tuple xs -> x -> Tuple (xs +: x) ($*) xs x = unsafeCoerce (unsafeCoerce xs ++ [unsafeCoerce x] :: [Any]) {-# INLINE ($*) #-} infixl 5 $* -- | Grow a tuple on the right while evaluating arguments to WHNF. -- Note, it traverses an element list inside O(n). (!*) :: Tuple xs -> x -> Tuple (xs +: x) (!*) !xs !x = let !r = go (unsafeCoerce x) (unsafeCoerce xs) :: [Any] go :: Any -> [Any] -> [Any] go z [] = z `seq` [z] go z (y : ys) = y `seq` y : go z ys in unsafeCoerce r {-# INLINE (!*) #-} infixl 5 !* instance All Semigroup xs => Sem.Semigroup (Tuple xs) where U <> U = U (x :$ xs) <> (y :$ ys) = (x <> y) *$ ( xs <> ys) instance ( RepresentableList xs , All Semigroup xs , All Monoid xs) => Mon.Monoid (Tuple xs) where mempty = go (tList @xs) where go :: forall (ys :: [Type]) . All Monoid ys => TypeList ys -> Tuple ys go U = U go (_ :* xs) = mempty *$ go xs #if !(MIN_VERSION_base(4,11,0)) mappend = (<>) #endif instance (RepresentableList xs, All Bounded xs) => Bounded (Tuple xs) where minBound = go (tList @xs) where go :: forall (ys :: [Type]) . All Bounded ys => TypeList ys -> Tuple ys go U = U go (_ :* xs) = minBound *$ go xs maxBound = go (tList @xs) where go :: forall (ys :: [Type]) . All Bounded ys => TypeList ys -> Tuple ys go U = U go (_ :* xs) = maxBound *$ go xs instance All Eq xs => Eq (Tuple xs) where (==) U U = True (==) (x :* tx) (y :* ty) = eq1 x y && tx == ty (/=) U U = False (/=) (x :* tx) (y :* ty) = not (eq1 x y) || tx /= ty -- | Lexicorgaphic ordering; same as normal Haskell lists. instance (All Eq xs, All Ord xs) => Ord (Tuple xs) where compare U U = EQ compare (x :* tx) (y :* ty) = compare1 x y <> compare tx ty instance All Show xs => Show (Tuple xs) where showsPrec = typedListShowsPrecC @Show ":$" showsPrec1 instance (All Read xs, RepresentableList xs) => Read (Tuple xs) where readPrec = typedListReadPrec @Read ":$" readPrec1 (tList @xs) readList = P.readListDefault readListPrec = P.readListPrecDefault -------------------------------------------------------------------------------- -- internal -------------------------------------------------------------------------------- forceCons :: Tuple xs -> Tuple xs forceCons U = U forceCons (Id x :* xs) = x `seq` xs `seq` (Id x :* xs)
achirkin/easytensor
dimensions/src/Numeric/Tuple/Lazy.hs
bsd-3-clause
7,745
3
13
2,507
2,286
1,275
1,011
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Toy.Lang.Data where import Control.Lens (makePrisms) import Control.Monad.Error.Class (MonadError (..)) import Control.Monad.Reader (MonadReader) import Control.Monad.State (MonadState) import Control.Monad.Trans (MonadIO) import qualified Data.Map as M import Data.Monoid ((<>)) import Data.String (IsString (..)) import Formatting (sformat, shown, stext, (%)) import GHC.Exts (IsList (..)) import Universum hiding (toList) import Toy.Base (FunSign (..), Var (..)) import Toy.Exp (Exp (..), ExpRes, LocalVars, MonadRefEnv, charE, readE, (==:)) import Toy.Util.Error (mapError) -- | Statement of a program. data Stmt = Var := Exp | If Exp Stmt Stmt | DoWhile Stmt Exp -- ^ @do .. while@ is the most optimal / easy loop from -- asm point of view | Return Exp | ArrayAssign Exp Exp Exp -- ^ array, index and value to assign | Seq Stmt Stmt | Skip deriving (Show) infix 2 := instance Monoid Stmt where mempty = Skip mappend = Seq type FunDecl = (FunSign, Stmt) type FunDecls = M.Map Var FunDecl -- | Builds function declarations map mkFunDecls :: (IsList l, Item l ~ FunDecl) => l -> FunDecls mkFunDecls = fromList . map doLol . toList where doLol d@(FunSign n _, _) = (n, d) data Program = Program { pFunDecls :: FunDecls , pMain :: Stmt } deriving (Show) data ExecInterrupt = Error Text -- ^ Execution exception | Returned ExpRes -- ^ Function returns deriving (Show) makePrisms ''ExecInterrupt instance IsString ExecInterrupt where fromString = Error . fromString prefixError :: MonadError ExecInterrupt m => Text -> m a -> m a prefixError desc = mapError (_Error %~ (desc <>)) type MonadExec m = ( MonadIO m , MonadError ExecInterrupt m , MonadState LocalVars m , MonadReader FunDecls m , MonadRefEnv ExpRes m ) -- | Adds current statement info to probable evaluation error withStmt :: MonadError ExecInterrupt m => Stmt -> m a -> m a withStmt stmt = flip catchError $ throwError . (_Error %~ sformat (shown%": "%stext) stmt) -- TODO: move to separate module and remove suffix @s@ -- | Drops diven expression dropS :: Exp -> Stmt dropS e = "_" := e ifS :: Exp -> Stmt -> Stmt ifS cond onTrue = If cond onTrue Skip -- | @while@ loop in terms of `Stmt`. whileS :: Exp -> Stmt -> Stmt whileS cond stmt = If cond (DoWhile stmt cond) Skip -- | @repeat@ loop in terms of `Stmt`. repeatS :: Stmt -> Exp -> Stmt repeatS stmt stop = DoWhile stmt (stop ==: 0) -- | @repeat@ loop in terms of `Stmt`. forS :: (Stmt, Exp, Stmt) -> Stmt -> Stmt forS (s1, cond, sr) body = s1 <> whileS cond (body <> sr) -- | Similar to 'forS', sometimes is more convenient. forS' :: Stmt -> Exp -> Stmt -> Stmt -> Stmt forS' s1 cond sr body = s1 <> whileS cond (body <> sr) -- | @read@ to a given variable. readS :: Var -> Stmt readS v = v := readE -- | Function call in terms of `Stmt`. funCallS :: Var -> [Exp] -> Stmt funCallS name args = dropS $ FunE name args -- | @write@ given expression. writeS :: Exp -> Stmt writeS = funCallS "write" . pure -- | Array initializer, which imideatelly writes to variable. storeArrayS :: Var -> [Exp] -> Stmt storeArrayS var exps = mconcat [ var := ArrayUninitE (fromIntegral $ length exps) , uncurry (ArrayAssign $ VarE var) `foldMap` (zip (map ValueE [0..]) exps) ] -- | Array initializer, which allows to get array as exression. arrayS :: (Exp -> Stmt) -> [Exp] -> Stmt arrayS initWith exps = mconcat [ storeArrayS "_arr" exps , initWith "_arr" ] -- | String initializer, similar to 'arrayS'. stringS :: (Exp -> Stmt) -> String -> Stmt stringS initWith = arrayS initWith . map charE -- | String initializer, similar to 'arrayVarS'. storeStringS :: Var -> String -> Stmt storeStringS var = storeArrayS var . map charE
Martoon-00/toy-compiler
src/Toy/Lang/Data.hs
bsd-3-clause
4,243
0
12
1,195
1,168
654
514
-1
-1
module FR.Region (towns, roads, mountains) where import FR.Poi import FR.Points import FR.Terrain mountains :: [Terrain] mountains = [ (Terrain Mountain [ np (FP 98 238), np (FP 126 239) , np (FP 124 260), np (FP 131 267) , np (FP 123 276), np (FP 110 280) , np (FP 90 278), np (FP 81 272) , np (FP 95 253)]) , (Terrain Mountain [ np (FP 106 292), np (FP 125 287) , np (FP 145 270), np (FP 188 255) , np (FP 190 275), np (FP 172 290) , np (FP 161 313), np (FP 156 350) , np (FP 139 369), np (FP 127 365) , np (FP 118 350), np (FP 123 329) , np (FP 131 319), np (FP 126 310) , np (FP 114 308), np (FP 106 303)]) , (Terrain Forest [ np (FP 54 254), np (FP 70 253) , np (FP 72 264), np (FP 65 271) , np (FP 58 271), np (FP 59 265) , np (FP 52 262)]) , (Terrain Sea [ np (FP 0 494), np (FP 0 449) , np (FP 46 427), np (FP 68 426) , np (FP 65 440), np (FP 102 447) , np (FP 114 432), np (FP 136 437) , np (FP 139 457), np (FP 157 461) , np (FP 168 452), np (FP 231 468) , np (FP 269 464), np (FP 282 446) , np (FP 282 420), np (FP 299 394) , np (FP 314 390), np (FP 316 422) , np (FP 303 435), np (FP 311 451) , np (FP 343 446), np (FP 349 435) , np (FP 343 424), np (FP 352 413) , np (FP 357 418), np (FP 374 413) , np (FP 382 381), np (FP 364 358) , np (FP 375 350), np (FP 402 353) , np (FP 425 367), np (FP 436 359) , np (FP 457 375), np (FP 468 379) , np (FP 477 377), np (FP 476 365) , np (FP 494 349), np (FP 494 467) , np (FP 475 475), np (FP 453 494) , np (FP 172 494), np (FP 137 475) , np (FP 94 481), np (FP 83 480) , np (FP 47 489), np (FP 40 494)]) , (Terrain Forest [ np (FP 200 237), np (FP 208 219) , np (FP 229 219), np (FP 239 211) , np (FP 265 203), np (FP 272 205) , np (FP 293 201), np (FP 305 207) , np (FP 300 225), np (FP 280 226) , np (FP 244 240)]) , (Terrain Forest [ np (FP 209 258), np (FP 264 257) , np (FP 290 276), np (FP 315 277) , np (FP 325 286), np (FP 319 297) , np (FP 292 299), np (FP 284 304) , np (FP 265 303), np (FP 261 295) , np (FP 235 297), np (FP 226 291) , np (FP 227 279), np (FP 208 274)]) , (Terrain Forest [ np (FP 130 200), np (FP 175 174) , np (FP 212 141), np (FP 231 143) , np (FP 241 159), np (FP 250 162) , np (FP 256 179), np (FP 250 181) , np (FP 242 177), np (FP 230 185) , np (FP 233 193), np (FP 230 206) , np (FP 211 207), np (FP 192 215) , np (FP 170 236), np (FP 163 241) , np (FP 159 246), np (FP 151 245) , np (FP 152 235), np (FP 136 229)]) , (Terrain Forest [ np (FP 42 299), np (FP 55 286) , np (FP 83 286), np (FP 88 301) , np (FP 102 313), np (FP 107 335) , np (FP 92 336), np (FP 87 327) , np (FP 42 314)]) , (Terrain Lake [ np (FP 0 332), np (FP 10 333) , np (FP 35 309), np (FP 35 323) , np (FP 73 326), np (FP 74 332) , np (FP 53 339), np (FP 44 396) , np (FP 40 396), np (FP 33 353) , np (FP 0 374)]) , (Terrain Swamp [ np (FP 126 380), np (FP 151 384) , np (FP 158 412), np (FP 146 423) , np (FP 115 415), np (FP 110 405)]) ] highmoon = T { tLoc = np (FP 211 243) , tName = "Highmoon" , tPop = 8000 } ordulin = T { tLoc = np (FP 375 275) , tName = "Ordulin" , tPop = 36300 } archenbridge = T { tLoc = np (FP 228 320) , tName = "Archenbridge" , tPop = 8000 } daerlun = T { tLoc = np (FP 184 433) , tName = "Daerlun" , tPop = 52477 } urmlaspyr = T { tLoc = np (FP 220 455) , tName = "Urmlaspyr" , tPop = 18000 } saerloon = T { tLoc = np (FP 300 382) , tName = "Saerloon" , tPop = 54496 } selgaunt = T { tLoc = np (FP 353 357) , tName = "Selgaunt" , tPop = 56514 } yhaunn = T { tLoc = np (FP 438 254) , tName = "Yhaunn" , tPop = 25000 } arabel = T { tLoc = np (FP 13 305) , tName = "Arabel" , tPop = 30600 } scar = T { tLoc = np (FP 13 305) , tName = "Tilverton Scar" , tPop = 50 } ashabenford = T { tLoc = np (FP 216 130) , tName = "Ashabenford" , tPop = 455 } chandlerscross = T { tLoc = np (FP 471 196) , tName = "Chandlerscross" , tPop = 5303 } towns = [highmoon, ordulin, archenbridge, daerlun, urmlaspyr, saerloon, selgaunt, yhaunn, arabel, scar, ashabenford, chandlerscross] roads :: [Road] roads = [ arabel <~> highmoon , arabel <~> ashabenford , highmoon <~> ordulin , ordulin <~> yhaunn , ordulin <~> archenbridge , yhaunn <~> selgaunt , selgaunt <~> saerloon , urmlaspyr <~> saerloon , daerlun <~> saerloon , daerlun <~> urmlaspyr , daerlun <~> archenbridge ]
Codas/HWorldGen
src/FR/Region.hs
bsd-3-clause
7,000
0
11
3,771
2,804
1,462
1,342
132
1
-- | -- Module : Math.Probable -- Copyright : (c) 2014 Alp Mestanogullari -- License : BSD3 -- Maintainer : alpmestan@gmail.com -- Stability : experimental -- Portability : GHC -- -- Easy, composable and efficient random number generation, -- with support for distributions over a finite set -- and your usual probability distributions. module Math.Probable ( -- * random value generation module Math.Probable.Random , -- * distributions module Math.Probable.Distribution ) where import Math.Probable.Distribution import Math.Probable.Random
alpmestan/probable
src/Math/Probable.hs
bsd-3-clause
608
0
5
141
47
36
11
6
0
module Main where import Control.Monad.Except import Lexer import Parser import TypeCheck import Eval import TAC import AST main = do a <- readFile "samples/fib.txt" let c = either (const []) id $ scanner a print $ program c getAST = do a <- readFile "samples/factorial.txt" let c = either (const []) id $ scanner a d = either undefined id $ runExcept $ program c pure d expr :: Expr expr = BinOp OpPlus (Ident "a") (BinOp OpPlus (Ident "b") (Ident "c"))
VyacheslavHashov/parus
app/Main.hs
bsd-3-clause
491
0
14
118
198
98
100
19
1
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeFamilies #-} module B.Oracle ( Oracle(..) ) where import B.Question data Oracle m = Oracle { get :: (Question q, m ~ AnswerMonad q) => q -> m (Maybe (Answer q)) , put :: (Question q, m ~ AnswerMonad q) => q -> Answer q -> m () , recheck :: (Question q, m ~ AnswerMonad q) => q -> m () , recheckAll :: m () , addDependency :: ( Question from , Question to , m ~ AnswerMonad from , m ~ AnswerMonad to ) => from -> to -> m () }
strager/b
B/Oracle.hs
bsd-3-clause
527
0
15
158
221
117
104
16
0
-- {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ExplicitForAll #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeFamilyDependencies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module LSI.Grid where import Data.Array.Repa as R import Data.Vector.Unboxed.Base frequencyGrid1D :: forall f. (Unbox f, RealFloat f) => Int -> Array D DIM1 f frequencyGrid1D n | n <= 1 = error "n should be greater >= 2" frequencyGrid1D n = fromFunction (Z :. (2*n)) $ let m = 2*pi :: f offset = m / 2 :: f step = m / (fromInteger . fromIntegral $ 2*n) :: f in \(R.Z R.:. x) -> ((fromInteger $ fromIntegral x)*step - offset) frequencyGrid2D :: forall f. (Unbox f, RealFloat f) => Int -> Array D DIM2 (f, f) frequencyGrid2D n | n <= 1 = error "n should be greater >= 2" frequencyGrid2D n = fromFunction (Z :. (2*n) :. (2*n)) $ let m = 2*pi :: f offset = m / 2 :: f step = m / (fromInteger . fromIntegral $ 2*n) :: f in \(R.Z R.:. x R.:. y) -> ( (fromInteger $ fromIntegral x)*step - offset , (fromInteger $ fromIntegral y)*step - offset ) frequencyGrid3D :: forall f. (Unbox f, RealFloat f) => Int -> Array D DIM3 (f, f, f) frequencyGrid3D n | n <= 1 = error "n should be greater >= 2" frequencyGrid3D n = fromFunction (Z :. (2*n) :. (2*n) :. (2*n)) $ let m = 2*pi :: f offset = m / 2 :: f step = m / (fromInteger . fromIntegral $ 2*n) :: f in \(R.Z R.:. x R.:. y R.:. z) -> ( (fromInteger $ fromIntegral x)*step - offset , (fromInteger $ fromIntegral y)*step - offset , (fromInteger $ fromIntegral z)*step - offset )
gdeest/lsi-systems
src/LSI/Grid.hs
bsd-3-clause
1,712
0
14
387
699
376
323
38
1
----------------------------------------------------------------------------- -- | -- Module : Control.Exception -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (extended exceptions) -- -- This module provides support for raising and catching both built-in -- and user-defined exceptions. -- -- In addition to exceptions thrown by 'IO' operations, exceptions may -- be thrown by pure code (imprecise exceptions) or by external events -- (asynchronous exceptions), but may only be caught in the 'IO' monad. -- For more details, see: -- -- * /A semantics for imprecise exceptions/, by Simon Peyton Jones, -- Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson, -- in /PLDI'99/. -- -- * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton -- Jones, Andy Moran and John Reppy, in /PLDI'01/. -- ----------------------------------------------------------------------------- module Control.Exception ( -- * The Exception type Exception(..), -- instance Eq, Ord, Show, Typeable IOException, -- instance Eq, Ord, Show, Typeable ArithException(..), -- instance Eq, Ord, Show, Typeable ArrayException(..), -- instance Eq, Ord, Show, Typeable AsyncException(..), -- instance Eq, Ord, Show, Typeable -- * Throwing exceptions throwIO, -- :: Exception -> IO a throw, -- :: Exception -> a ioError, -- :: IOError -> IO a #ifdef __GLASGOW_HASKELL__ throwTo, -- :: ThreadId -> Exception -> a #endif -- * Catching Exceptions -- |There are several functions for catching and examining -- exceptions; all of them may only be used from within the -- 'IO' monad. -- ** The @catch@ functions catch, -- :: IO a -> (Exception -> IO a) -> IO a catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a -- ** The @handle@ functions handle, -- :: (Exception -> IO a) -> IO a -> IO a handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a -- ** The @try@ functions try, -- :: IO a -> IO (Either Exception a) tryJust, -- :: (Exception -> Maybe b) -> a -> IO (Either b a) -- ** The @evaluate@ function evaluate, -- :: a -> IO a -- ** The @mapException@ function mapException, -- :: (Exception -> Exception) -> a -> a -- ** Exception predicates -- $preds ioErrors, -- :: Exception -> Maybe IOError arithExceptions, -- :: Exception -> Maybe ArithException errorCalls, -- :: Exception -> Maybe String dynExceptions, -- :: Exception -> Maybe Dynamic assertions, -- :: Exception -> Maybe String asyncExceptions, -- :: Exception -> Maybe AsyncException userErrors, -- :: Exception -> Maybe String -- * Dynamic exceptions -- $dynamic throwDyn, -- :: Typeable ex => ex -> b #ifdef __GLASGOW_HASKELL__ throwDynTo, -- :: Typeable ex => ThreadId -> ex -> b #endif catchDyn, -- :: Typeable ex => IO a -> (ex -> IO a) -> IO a -- * Asynchronous Exceptions -- $async -- ** Asynchronous exception control -- |The following two functions allow a thread to control delivery of -- asynchronous exceptions during a critical region. block, -- :: IO a -> IO a unblock, -- :: IO a -> IO a -- *** Applying @block@ to an exception handler -- $block_handler -- *** Interruptible operations -- $interruptible -- * Assertions assert, -- :: Bool -> a -> a -- * Utilities bracket, -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO () bracket_, -- :: IO a -> IO b -> IO c -> IO () bracketOnError, finally, -- :: IO a -> IO b -> IO a #ifdef __GLASGOW_HASKELL__ setUncaughtExceptionHandler, -- :: (Exception -> IO ()) -> IO () getUncaughtExceptionHandler -- :: IO (Exception -> IO ()) #endif ) where #ifdef __GLASGOW_HASKELL__ import GHC.Base ( assert ) import GHC.Exception as ExceptionBase hiding (catch) import GHC.Conc ( throwTo, ThreadId ) import Data.IORef ( IORef, newIORef, readIORef, writeIORef ) import Foreign.C.String ( CString, withCString ) import System.IO ( stdout, hFlush ) #endif #ifdef __HUGS__ import Hugs.Exception as ExceptionBase #endif import Prelude hiding ( catch ) import System.IO.Error hiding ( catch, try ) import System.IO.Unsafe (unsafePerformIO) import Data.Dynamic ----------------------------------------------------------------------------- -- Catching exceptions -- |This is the simplest of the exception-catching functions. It -- takes a single argument, runs it, and if an exception is raised -- the \"handler\" is executed, with the value of the exception passed as an -- argument. Otherwise, the result is returned as normal. For example: -- -- > catch (openFile f ReadMode) -- > (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e)) -- -- For catching exceptions in pure (non-'IO') expressions, see the -- function 'evaluate'. -- -- Note that due to Haskell\'s unspecified evaluation order, an -- expression may return one of several possible exceptions: consider -- the expression @error \"urk\" + 1 \`div\` 0@. Does -- 'catch' execute the handler passing -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@? -- -- The answer is \"either\": 'catch' makes a -- non-deterministic choice about which exception to catch. If you -- call it again, you might get a different exception back. This is -- ok, because 'catch' is an 'IO' computation. -- -- Note that 'catch' catches all types of exceptions, and is generally -- used for \"cleaning up\" before passing on the exception using -- 'throwIO'. It is not good practice to discard the exception and -- continue, without first checking the type of the exception (it -- might be a 'ThreadKilled', for example). In this case it is usually better -- to use 'catchJust' and select the kinds of exceptions to catch. -- -- Also note that the "Prelude" also exports a function called -- 'Prelude.catch' with a similar type to 'Control.Exception.catch', -- except that the "Prelude" version only catches the IO and user -- families of exceptions (as required by Haskell 98). -- -- We recommend either hiding the "Prelude" version of 'Prelude.catch' -- when importing "Control.Exception": -- -- > import Prelude hiding (catch) -- -- or importing "Control.Exception" qualified, to avoid name-clashes: -- -- > import qualified Control.Exception as C -- -- and then using @C.catch@ -- catch :: IO a -- ^ The computation to run -> (Exception -> IO a) -- ^ Handler to invoke if an exception is raised -> IO a catch = ExceptionBase.catchException -- | The function 'catchJust' is like 'catch', but it takes an extra -- argument which is an /exception predicate/, a function which -- selects which type of exceptions we\'re interested in. There are -- some predefined exception predicates for useful subsets of -- exceptions: 'ioErrors', 'arithExceptions', and so on. For example, -- to catch just calls to the 'error' function, we could use -- -- > result <- catchJust errorCalls thing_to_try handler -- -- Any other exceptions which are not matched by the predicate -- are re-raised, and may be caught by an enclosing -- 'catch' or 'catchJust'. catchJust :: (Exception -> Maybe b) -- ^ Predicate to select exceptions -> IO a -- ^ Computation to run -> (b -> IO a) -- ^ Handler -> IO a catchJust p a handler = catch a handler' where handler' e = case p e of Nothing -> throw e Just b -> handler b -- | A version of 'catch' with the arguments swapped around; useful in -- situations where the code for the handler is shorter. For example: -- -- > do handle (\e -> exitWith (ExitFailure 1)) $ -- > ... handle :: (Exception -> IO a) -> IO a -> IO a handle = flip catch -- | A version of 'catchJust' with the arguments swapped around (see -- 'handle'). handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a handleJust p = flip (catchJust p) ----------------------------------------------------------------------------- -- 'mapException' -- | This function maps one exception into another as proposed in the -- paper \"A semantics for imprecise exceptions\". -- Notice that the usage of 'unsafePerformIO' is safe here. mapException :: (Exception -> Exception) -> a -> a mapException f v = unsafePerformIO (catch (evaluate v) (\x -> throw (f x))) ----------------------------------------------------------------------------- -- 'try' and variations. -- | Similar to 'catch', but returns an 'Either' result which is -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an -- exception was raised and its value is @e@. -- -- > try a = catch (Right `liftM` a) (return . Left) -- -- Note: as with 'catch', it is only polite to use this variant if you intend -- to re-throw the exception after performing whatever cleanup is needed. -- Otherwise, 'tryJust' is generally considered to be better. -- -- Also note that "System.IO.Error" also exports a function called -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try', -- except that it catches only the IO and user families of exceptions -- (as required by the Haskell 98 @IO@ module). try :: IO a -> IO (Either Exception a) try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e)) -- | A variant of 'try' that takes an exception predicate to select -- which exceptions are caught (c.f. 'catchJust'). If the exception -- does not match the predicate, it is re-thrown. tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a) tryJust p a = do r <- try a case r of Right v -> return (Right v) Left e -> case p e of Nothing -> throw e Just b -> return (Left b) ----------------------------------------------------------------------------- -- Dynamic exceptions -- $dynamic -- #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an -- interface for throwing and catching exceptions of type 'Dynamic' -- (see "Data.Dynamic") which allows exception values of any type in -- the 'Typeable' class to be thrown and caught. -- | Raise any value as an exception, provided it is in the -- 'Typeable' class. throwDyn :: Typeable exception => exception -> b throwDyn exception = throw (DynException (toDyn exception)) #ifdef __GLASGOW_HASKELL__ -- | A variant of 'throwDyn' that throws the dynamic exception to an -- arbitrary thread (GHC only: c.f. 'throwTo'). throwDynTo :: Typeable exception => ThreadId -> exception -> IO () throwDynTo t exception = throwTo t (DynException (toDyn exception)) #endif /* __GLASGOW_HASKELL__ */ -- | Catch dynamic exceptions of the required type. All other -- exceptions are re-thrown, including dynamic exceptions of the wrong -- type. -- -- When using dynamic exceptions it is advisable to define a new -- datatype to use for your exception type, to avoid possible clashes -- with dynamic exceptions used in other libraries. -- catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a catchDyn m k = catchException m handle where handle ex = case ex of (DynException dyn) -> case fromDynamic dyn of Just exception -> k exception Nothing -> throw ex _ -> throw ex ----------------------------------------------------------------------------- -- Exception Predicates -- $preds -- These pre-defined predicates may be used as the first argument to -- 'catchJust', 'tryJust', or 'handleJust' to select certain common -- classes of exceptions. ioErrors :: Exception -> Maybe IOError arithExceptions :: Exception -> Maybe ArithException errorCalls :: Exception -> Maybe String assertions :: Exception -> Maybe String dynExceptions :: Exception -> Maybe Dynamic asyncExceptions :: Exception -> Maybe AsyncException userErrors :: Exception -> Maybe String ioErrors (IOException e) = Just e ioErrors _ = Nothing arithExceptions (ArithException e) = Just e arithExceptions _ = Nothing errorCalls (ErrorCall e) = Just e errorCalls _ = Nothing assertions (AssertionFailed e) = Just e assertions _ = Nothing dynExceptions (DynException e) = Just e dynExceptions _ = Nothing asyncExceptions (AsyncException e) = Just e asyncExceptions _ = Nothing userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e) userErrors _ = Nothing ----------------------------------------------------------------------------- -- Some Useful Functions -- | When you want to acquire a resource, do some work with it, and -- then release the resource, it is a good idea to use 'bracket', -- because 'bracket' will install the necessary exception handler to -- release the resource in the event that an exception is raised -- during the computation. If an exception is raised, then 'bracket' will -- re-raise the exception (after performing the release). -- -- A common example is opening a file: -- -- > bracket -- > (openFile "filename" ReadMode) -- > (hClose) -- > (\handle -> do { ... }) -- -- The arguments to 'bracket' are in this order so that we can partially apply -- it, e.g.: -- -- > withFile name = bracket (openFile name) hClose -- bracket :: IO a -- ^ computation to run first (\"acquire resource\") -> (a -> IO b) -- ^ computation to run last (\"release resource\") -> (a -> IO c) -- ^ computation to run in-between -> IO c -- returns the value from the in-between computation bracket before after thing = block (do a <- before r <- catch (unblock (thing a)) (\e -> do { after a; throw e }) after a return r ) -- | A specialised variant of 'bracket' with just a computation to run -- afterward. -- finally :: IO a -- ^ computation to run first -> IO b -- ^ computation to run afterward (even if an exception -- was raised) -> IO a -- returns the value from the first computation a `finally` sequel = block (do r <- catch (unblock a) (\e -> do { sequel; throw e }) sequel return r ) -- | A variant of 'bracket' where the return value from the first computation -- is not required. bracket_ :: IO a -> IO b -> IO c -> IO c bracket_ before after thing = bracket before (const after) (const thing) -- | Like bracket, but only performs the final action if there was an -- exception raised by the in-between computation. bracketOnError :: IO a -- ^ computation to run first (\"acquire resource\") -> (a -> IO b) -- ^ computation to run last (\"release resource\") -> (a -> IO c) -- ^ computation to run in-between -> IO c -- returns the value from the in-between computation bracketOnError before after thing = block (do a <- before catch (unblock (thing a)) (\e -> do { after a; throw e }) ) -- ----------------------------------------------------------------------------- -- Asynchronous exceptions {- $async #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to external influences, and can be raised at any point during execution. 'StackOverflow' and 'HeapOverflow' are two examples of system-generated asynchronous exceptions. The primary source of asynchronous exceptions, however, is 'throwTo': > throwTo :: ThreadId -> Exception -> IO () 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one running thread to raise an arbitrary exception in another thread. The exception is therefore asynchronous with respect to the target thread, which could be doing anything at the time it receives the exception. Great care should be taken with asynchronous exceptions; it is all too easy to introduce race conditions by the over zealous use of 'throwTo'. -} {- $block_handler There\'s an implied 'block' around every exception handler in a call to one of the 'catch' family of functions. This is because that is what you want most of the time - it eliminates a common race condition in starting an exception handler, because there may be no exception handler on the stack to handle another exception if one arrives immediately. If asynchronous exceptions are blocked on entering the handler, though, we have time to install a new exception handler before being interrupted. If this weren\'t the default, one would have to write something like > block ( > catch (unblock (...)) > (\e -> handler) > ) If you need to unblock asynchronous exceptions again in the exception handler, just use 'unblock' as normal. Note that 'try' and friends /do not/ have a similar default, because there is no exception handler in this case. If you want to use 'try' in an asynchronous-exception-safe way, you will need to use 'block'. -} {- $interruptible Some operations are /interruptible/, which means that they can receive asynchronous exceptions even in the scope of a 'block'. Any function which may itself block is defined as interruptible; this includes 'Control.Concurrent.MVar.takeMVar' (but not 'Control.Concurrent.MVar.tryTakeMVar'), and most operations which perform some I\/O with the outside world. The reason for having interruptible operations is so that we can write things like > block ( > a <- takeMVar m > catch (unblock (...)) > (\e -> ...) > ) if the 'Control.Concurrent.MVar.takeMVar' was not interruptible, then this particular combination could lead to deadlock, because the thread itself would be blocked in a state where it can\'t receive any asynchronous exceptions. With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be safe in the knowledge that the thread can receive exceptions right up until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds. Similar arguments apply for other interruptible operations like 'System.IO.openFile'. -} #ifndef __GLASGOW_HASKELL__ assert :: Bool -> a -> a assert True x = x assert False _ = throw (AssertionFailed "") #endif #ifdef __GLASGOW_HASKELL__ {-# NOINLINE uncaughtExceptionHandler #-} uncaughtExceptionHandler :: IORef (Exception -> IO ()) uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler) where defaultHandler :: Exception -> IO () defaultHandler ex = do (hFlush stdout) `catchException` (\ _ -> return ()) let msg = case ex of Deadlock -> "no threads to run: infinite loop or deadlock?" ErrorCall s -> s other -> showsPrec 0 other "\n" withCString "%s" $ \cfmt -> withCString msg $ \cmsg -> errorBelch cfmt cmsg foreign import ccall unsafe "RtsMessages.h errorBelch" errorBelch :: CString -> CString -> IO () setUncaughtExceptionHandler :: (Exception -> IO ()) -> IO () setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler getUncaughtExceptionHandler :: IO (Exception -> IO ()) getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler #endif
alekar/hugs
packages/base/Control/Exception.hs
bsd-3-clause
18,885
262
15
3,735
2,249
1,311
938
137
3
{-# LANGUAGE CPP #-} #if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703 {-# LANGUAGE Safe #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Data.Map.Lazy -- Copyright : (c) Daan Leijen 2002 -- (c) Andriy Palamarchuk 2008 -- License : BSD-style -- Maintainer : libraries@haskell.org -- Stability : provisional -- Portability : portable -- -- An efficient implementation of ordered maps from keys to values -- (dictionaries). -- -- API of this module is strict in the keys, but lazy in the values. -- If you need value-strict maps, use "Data.Map.Strict" instead. -- The 'Map' type itself is shared between the lazy and strict modules, -- meaning that the same 'Map' value can be passed to functions in -- both modules (although that is rarely needed). -- -- These modules are intended to be imported qualified, to avoid name -- clashes with Prelude functions, e.g. -- -- > import qualified Data.Map.Lazy as Map -- -- The implementation of 'Map' is based on /size balanced/ binary trees (or -- trees of /bounded balance/) as described by: -- -- * Stephen Adams, \"/Efficient sets: a balancing act/\", -- Journal of Functional Programming 3(4):553-562, October 1993, -- <http://www.swiss.ai.mit.edu/~adams/BB/>. -- -- * J. Nievergelt and E.M. Reingold, -- \"/Binary search trees of bounded balance/\", -- SIAM journal of computing 2(1), March 1973. -- -- Note that the implementation is /left-biased/ -- the elements of a -- first argument are always preferred to the second, for example in -- 'union' or 'insert'. -- -- Operation comments contain the operation time complexity in -- the Big-O notation (<http://en.wikipedia.org/wiki/Big_O_notation>). ----------------------------------------------------------------------------- module Data.Map.Lazy ( -- * Strictness properties -- $strictness -- * Map type #if !defined(TESTING) Map -- instance Eq,Show,Read #else Map(..) -- instance Eq,Show,Read #endif -- * Operators , (!), (\\) -- * Query , M.null , size , member , notMember , M.lookup , findWithDefault , lookupLT , lookupGT , lookupLE , lookupGE -- * Construction , empty , singleton -- ** Insertion , insert , insertWith , insertWithKey , insertLookupWithKey -- ** Delete\/Update , delete , adjust , adjustWithKey , update , updateWithKey , updateLookupWithKey , alter -- * Combine -- ** Union , union , unionWith , unionWithKey , unions , unionsWith -- ** Difference , difference , differenceWith , differenceWithKey -- ** Intersection , intersection , intersectionWith , intersectionWithKey -- ** Universal combining function , mergeWithKey -- * Traversal -- ** Map , M.map , mapWithKey , traverseWithKey , mapAccum , mapAccumWithKey , mapAccumRWithKey , mapKeys , mapKeysWith , mapKeysMonotonic -- * Folds , M.foldr , M.foldl , foldrWithKey , foldlWithKey , foldMapWithKey -- ** Strict folds , foldr' , foldl' , foldrWithKey' , foldlWithKey' -- * Conversion , elems , keys , assocs , keysSet , fromSet -- ** Lists , toList , fromList , fromListWith , fromListWithKey -- ** Ordered lists , toAscList , toDescList , fromAscList , fromAscListWith , fromAscListWithKey , fromDistinctAscList -- * Filter , M.filter , filterWithKey , partition , partitionWithKey , mapMaybe , mapMaybeWithKey , mapEither , mapEitherWithKey , split , splitLookup -- * Submap , isSubmapOf, isSubmapOfBy , isProperSubmapOf, isProperSubmapOfBy -- * Indexed , lookupIndex , findIndex , elemAt , updateAt , deleteAt -- * Min\/Max , findMin , findMax , deleteMin , deleteMax , deleteFindMin , deleteFindMax , updateMin , updateMax , updateMinWithKey , updateMaxWithKey , minView , maxView , minViewWithKey , maxViewWithKey -- * Debugging , showTree , showTreeWith , valid #if defined(TESTING) -- * Internals , bin , balanced , join , merge #endif ) where import Data.Map.Base as M -- $strictness -- -- This module satisfies the following strictness property: -- -- * Key arguments are evaluated to WHNF -- -- Here are some examples that illustrate the property: -- -- > insertWith (\ new old -> old) undefined v m == undefined -- > insertWith (\ new old -> old) k undefined m == OK -- > delete undefined m == undefined
ekmett/containers
Data/Map/Lazy.hs
bsd-3-clause
4,815
0
5
1,309
455
333
122
107
0
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} module Lib ( withLdap, Username(..), ProjectId(..), attrMatch, pluckAttr, getMemberUid, getSshPublicKey, listUsers, listUserData, Ldap, Host(..), PortNumber, Dn(..), LdapError, Attr(..), SearchEntry(..) ) where import Data.ByteString (ByteString) import Data.Hashable (Hashable (..)) 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 Ldap.Client newtype Username = Username Text deriving (Eq, Show, Hashable) newtype ProjectId = ProjectId ByteString deriving (Eq, Show, Hashable) -- attrs :: AttrList NonEmpty -- attrs = undefined attrMatch :: Attr -> (Attr, f AttrValue) -> Bool attrMatch a0 (a1, _) = a0 == a1 pluckAttr :: Attr -> [(Attr, [AttrValue])] -> [AttrValue] pluckAttr name attrlist = concat . map snd $ filter (attrMatch name) attrlist getMemberUid :: SearchEntry -> [Username] getMemberUid (SearchEntry _ attrlist) = map (Username . T.decodeUtf8) $ pluckAttr (Attr "memberUid") attrlist getSshPublicKey :: SearchEntry -> [ByteString] getSshPublicKey (SearchEntry _ vs) = pluckAttr (Attr "sshPublicKey") vs listUsers :: Ldap -> Dn -> ProjectId -> IO [Username] listUsers token dn (ProjectId project) = (concat . map getMemberUid) <$> search token dn mempty filters [] where filters = (Attr "cn") := project listUserData :: Ldap -> Dn -> (SearchEntry -> [a]) -> Username -> IO [a] listUserData token dn getter u@(Username uid) = do let filters = (Attr "cn") := T.encodeUtf8 uid (concat . map getter) <$> search token dn mempty filters [] withLdap :: Host -> PortNumber -> (Ldap -> IO a) -> IO (Either LdapError a) withLdap = with
futuresystems/ldapget
src/Lib.hs
bsd-3-clause
2,015
0
12
509
637
357
280
54
1
{-# LANGUAGE LambdaCase, ScopedTypeVariables #-} -- | Matrix datatype and operations. -- -- Every provided example has been tested. -- Run @cabal test@ for further tests. module Data.Matrix ( -- * Matrix type Matrix , prettyMatrix , nrows , ncols , forceMatrix -- * Builders , matrix , rowVector , colVector -- ** Special matrices , zero , identity , permMatrix -- * List conversions , fromList , fromLists , toList , toLists -- * Accessing , getElem , (!) , unsafeGet , safeGet , getRow , getCol , getDiag , getMatrixAsVector -- * Manipulating matrices , setElem , unsafeSet , transpose , setSize , extendTo , mapRow , mapCol -- * Submatrices -- ** Splitting blocks , submatrix , minorMatrix , splitBlocks -- ** Joining blocks , (<|>) , (<->) , joinBlocks -- * Matrix operations , elementwise, elementwiseUnsafe -- * Matrix multiplication -- ** About matrix multiplication -- $mult -- ** Functions , multStd , multStd2 , multStrassen , multStrassenMixed -- * Linear transformations , scaleMatrix , scaleRow , combineRows , switchRows , switchCols -- * Decompositions , luDecomp , luDecompUnsafe , luDecompWithMag , luDecomp', luDecompUnsafe' , luDecompWithMag' , cholDecomp -- * Properties , trace , diagProd -- ** Determinants , detLaplace , detLU , invertS , invert ) where -- Classes import Control.DeepSeq(NFData,deepseq,rnf) import Control.Monad (forM_, MonadPlus,mzero) import Control.Loop (numLoop,numLoopFold) import Data.Monoid((<>)) -- Data import Control.Monad.Primitive (PrimMonad, PrimState) import Data.List (maximumBy,foldl1',genericTake, genericLength) import Data.Ord (comparing) import qualified Data.Vector as V import qualified Data.Vector.Mutable as MV import Data.Foldable(Foldable,foldMap) import Data.Traversable(Traversable,sequenceA) import Control.Monad.Trans.State.Strict(State,execState) import qualified Control.Monad.Trans.State.Strict as State import Control.Monad.ST(runST); import Control.Monad.Trans(lift); import Control.Monad.Trans.Maybe(runMaybeT,MaybeT); type Index = Integer ------------------------------------------------------- ------------------------------------------------------- ---- MATRIX TYPE encode :: Index -> (Index,Index) -> Int {-# INLINE encode #-} encode m (i,j) = fromIntegral $ (i-1)*m + j - 1 decode :: Index -> Int -> (Index,Index) {-# INLINE decode #-} decode m k = (q+1,r+1) where (q,r) = quotRem (fromIntegral k) m -- | Type of matrices. -- -- Elements can be of any type. Rows and columns -- are indexed starting by 1. This means that, if @m :: Matrix a@ and -- @i,j :: Index@, then @m ! (i,j)@ is the element in the @i@-th row and -- @j@-th column of @m@. data Matrix a = M { nrows :: {-# UNPACK #-} !Index -- ^ Number of rows. , ncols :: {-# UNPACK #-} !Index -- ^ Number of columns. , rowOffset :: {-# UNPACK #-} !Index , colOffset :: {-# UNPACK #-} !Index , vcols :: {-# UNPACK #-} !Index -- ^ Number of columns of the matrix without offset , mvect :: V.Vector a -- ^ Content of the matrix as a plain vector. } instance Eq a => Eq (Matrix a) where m1 == m2 = let r = nrows m1 c = ncols m1 in and $ (r == nrows m2) : (c == ncols m2) : [ m1 ! (i,j) == m2 ! (i,j) | i <- [1 .. r] , j <- [1 .. c] ] -- | Just a cool way to output the size of a matrix. sizeStr :: Index -> Index -> String sizeStr n m = show n ++ "x" ++ show m -- | Display a matrix as a 'String' using the 'Show' instance of its elements. prettyMatrix :: Show a => Matrix a -> String prettyMatrix m@(M _ _ _ _ _ v) = unlines [ "( " <> unwords (fmap (\j -> fill mx $ show $ m ! (i,j)) [1..ncols m]) <> " )" | i <- [1..nrows m] ] where mx = V.maximum $ fmap (length . show) v fill k str = replicate (k - length str) ' ' ++ str instance Show a => Show (Matrix a) where show = prettyMatrix instance NFData a => NFData (Matrix a) where rnf = rnf . mvect -- | /O(rows*cols)/. Similar to 'V.force'. It copies the matrix content -- dropping any extra memory. -- -- Useful when using 'submatrix' from a big matrix. -- forceMatrix :: Matrix a -> Matrix a forceMatrix m = matrix (nrows m) (ncols m) $ \(i,j) -> unsafeGet i j m ------------------------------------------------------- ------------------------------------------------------- ---- FUNCTOR INSTANCE instance Functor Matrix where {-# INLINE fmap #-} fmap f (M n m ro co w v) = M n m ro co w $ V.map f v ------------------------------------------------------- ------------------------------------------------------- -- | /O(rows*cols)/. Map a function over a row. -- Example: -- -- > ( 1 2 3 ) ( 1 2 3 ) -- > ( 4 5 6 ) ( 5 6 7 ) -- > mapRow (\_ x -> x + 1) 2 ( 7 8 9 ) = ( 7 8 9 ) -- mapRow :: (Index -> a -> a) -- ^ Function takes the current column as additional argument. -> Index -- ^ Row to map. -> Matrix a -> Matrix a mapRow f r m = matrix (nrows m) (ncols m) $ \(i,j) -> let a = unsafeGet i j m in if i == r then f j a else a -- | /O(rows*cols)/. Map a function over a column. -- Example: -- -- > ( 1 2 3 ) ( 1 3 3 ) -- > ( 4 5 6 ) ( 4 6 6 ) -- > mapCol (\_ x -> x + 1) 2 ( 7 8 9 ) = ( 7 9 9 ) -- mapCol :: (Index -> a -> a) -- ^ Function takes the current row as additional argument. -> Index -- ^ Column to map. -> Matrix a -> Matrix a mapCol f c m = matrix (nrows m) (ncols m) $ \(i,j) -> let a = unsafeGet i j m in if j == c then f i a else a ------------------------------------------------------- ------------------------------------------------------- ---- FOLDABLE AND TRAVERSABLE INSTANCES instance Foldable Matrix where foldMap f = foldMap f . mvect . forceMatrix instance Traversable Matrix where sequenceA m = fmap (M (nrows m) (ncols m) 0 0 (ncols m)) . sequenceA . mvect $ forceMatrix m ------------------------------------------------------- ------------------------------------------------------- ---- BUILDERS -- | /O(rows*cols)/. The zero matrix of the given size. -- -- > zero n m = -- > n -- > 1 ( 0 0 ... 0 0 ) -- > 2 ( 0 0 ... 0 0 ) -- > ( ... ) -- > ( 0 0 ... 0 0 ) -- > n ( 0 0 ... 0 0 ) zero :: Num a => Index -- ^ Rows -> Index -- ^ Columns -> Matrix a {-# INLINE zero #-} zero n m = M n m 0 0 m $ V.replicate (fromIntegral $ n*m) 0 -- | /O(rows*cols)/. Generate a matrix from a generator function. -- Example of usage: -- -- > ( 1 0 -1 -2 ) -- > ( 3 2 1 0 ) -- > ( 5 4 3 2 ) -- > matrix 4 4 $ \(i,j) -> 2*i - j = ( 7 6 5 4 ) matrix :: Index -- ^ Rows -> Index -- ^ Columns -> ((Index,Index) -> a) -- ^ Generator function -> Matrix a {-# INLINE matrix #-} matrix n m f = M n m 0 0 m $ V.create $ do v <- MV.new $ fromIntegral $ n * m let en = encode m numLoop 1 n $ \i -> numLoop 1 m $ \j -> MV.unsafeWrite v (en (i,j)) (f (i,j)) return v -- | /O(rows*cols)/. Identity matrix of the given order. -- -- > identity n = -- > n -- > 1 ( 1 0 ... 0 0 ) -- > 2 ( 0 1 ... 0 0 ) -- > ( ... ) -- > ( 0 0 ... 1 0 ) -- > n ( 0 0 ... 0 1 ) -- identity :: Num a => Index -> Matrix a identity n = matrix n n $ \(i,j) -> if i == j then 1 else 0 -- | Create a matrix from a non-empty list given the desired size. -- The list must have at least /rows*cols/ elements. -- An example: -- -- > ( 1 2 3 ) -- > ( 4 5 6 ) -- > fromList 3 3 [1..] = ( 7 8 9 ) -- fromList :: Index -- ^ Rows -> Index -- ^ Columns -> [a] -- ^ List of elements -> Matrix a {-# INLINE fromList #-} fromList n m = M n m 0 0 m . V.fromListN (fromIntegral $ n*m) -- | Get the elements of a matrix stored in a list. -- -- > ( 1 2 3 ) -- > ( 4 5 6 ) -- > toList ( 7 8 9 ) = [1,2,3,4,5,6,7,8,9] -- toList :: Matrix a -> [a] toList m = [ unsafeGet i j m | i <- [1 .. nrows m] , j <- [1 .. ncols m] ] -- | Get the elements of a matrix stored in a list of lists, -- where each list contains the elements of a single row. -- -- > ( 1 2 3 ) [ [1,2,3] -- > ( 4 5 6 ) , [4,5,6] -- > toLists ( 7 8 9 ) = , [7,8,9] ] -- toLists :: Matrix a -> [[a]] toLists m = [ [ unsafeGet i j m | j <- [1 .. ncols m] ] | i <- [1 .. nrows m] ] -- | Create a matrix from a non-empty list of non-empty lists. -- /Each list must have at least as many elements as the first list/. -- Examples: -- -- > fromLists [ [1,2,3] ( 1 2 3 ) -- > , [4,5,6] ( 4 5 6 ) -- > , [7,8,9] ] = ( 7 8 9 ) -- -- > fromLists [ [1,2,3 ] ( 1 2 3 ) -- > , [4,5,6,7] ( 4 5 6 ) -- > , [8,9,0 ] ] = ( 8 9 0 ) -- fromLists :: [[a]] -> Matrix a {-# INLINE fromLists #-} fromLists [] = error "fromLists: empty list." fromLists (xs:xss) = fromList n m $ concat $ xs : fmap (genericTake m) xss where n = 1 + genericLength xss m = genericLength xs -- | /O(1)/. Represent a vector as a one row matrix. rowVector :: V.Vector a -> Matrix a rowVector v = M 1 m 0 0 m v where m = fromIntegral $ V.length v -- | /O(1)/. Represent a vector as a one column matrix. colVector :: V.Vector a -> Matrix a colVector v = M (fromIntegral $ V.length v) 1 0 0 1 v -- | /O(rows*cols)/. Permutation matrix. -- -- > permMatrix n i j = -- > i j n -- > 1 ( 1 0 ... 0 ... 0 ... 0 0 ) -- > 2 ( 0 1 ... 0 ... 0 ... 0 0 ) -- > ( ... ... ... ) -- > i ( 0 0 ... 0 ... 1 ... 0 0 ) -- > ( ... ... ... ) -- > j ( 0 0 ... 1 ... 0 ... 0 0 ) -- > ( ... ... ... ) -- > ( 0 0 ... 0 ... 0 ... 1 0 ) -- > n ( 0 0 ... 0 ... 0 ... 0 1 ) -- -- When @i == j@ it reduces to 'identity' @n@. -- permMatrix :: Num a => Index -- ^ Size of the matrix. -> Index -- ^ Permuted row 1. -> Index -- ^ Permuted row 2. -> Matrix a -- ^ Permutation matrix. permMatrix n r1 r2 | r1 == r2 = identity n permMatrix n r1 r2 = matrix n n f where f (i,j) | i == r1 = if j == r2 then 1 else 0 | i == r2 = if j == r1 then 1 else 0 | i == j = 1 | otherwise = 0 ------------------------------------------------------- ------------------------------------------------------- ---- ACCESSING -- | /O(1)/. Get an element of a matrix. Indices range from /(1,1)/ to /(n,m)/. -- It returns an 'error' if the requested element is outside of range. getElem :: Index -- ^ Row -> Index -- ^ Column -> Matrix a -- ^ Matrix -> a {-# INLINE getElem #-} getElem i j m = case safeGet i j m of Just x -> x Nothing -> error $ "getElem: Trying to get the " ++ show (i,j) ++ " element from a " ++ sizeStr (nrows m) (ncols m) ++ " matrix." -- | /O(1)/. Unsafe variant of 'getElem', without bounds checking. unsafeGet :: Index -- ^ Row -> Index -- ^ Column -> Matrix a -- ^ Matrix -> a {-# INLINE unsafeGet #-} unsafeGet i j (M _ _ ro co w v) = V.unsafeIndex v $ encode w (i+ro,j+co) -- | Short alias for 'getElem'. (!) :: Matrix a -> (Index,Index) -> a {-# INLINE (!) #-} m ! (i,j) = getElem i j m -- | Internal alias for 'unsafeGet'. (!.) :: Matrix a -> (Index,Index) -> a {-# INLINE (!.) #-} m !. (i,j) = unsafeGet i j m -- | Variant of 'getElem' that returns Maybe instead of an error. safeGet :: Index -> Index -> Matrix a -> Maybe a safeGet i j a@(M n m _ _ _ _) | i > n || j > m || i < 1 || j < 1 = Nothing | otherwise = Just $ unsafeGet i j a -- | /O(1)/. Get a row of a matrix as a vector. getRow :: Index -> Matrix a -> V.Vector a {-# INLINE getRow #-} getRow i (M _ m ro co w v) = V.slice (fromIntegral $ w*(i-1+ro) + co) (fromIntegral m) v -- | /O(rows)/. Get a column of a matrix as a vector. getCol :: Index -> Matrix a -> V.Vector a {-# INLINE getCol #-} getCol j (M n _ ro co w v) = V.generate (fromIntegral n) $ \i -> v V.! encode w (fromIntegral i+1+ro,j+co) -- | /O(min rows cols)/. Diagonal of a /not necessarily square/ matrix. getDiag :: Matrix a -> V.Vector a getDiag m = V.generate (fromIntegral k) $ \i -> m ! (fromIntegral i+1, fromIntegral i+1) where k = min (nrows m) (ncols m) -- | /O(rows*cols)/. Transform a 'Matrix' to a 'V.Vector' of size /rows*cols/. -- This is equivalent to get all the rows of the matrix using 'getRow' -- and then append them, but far more efficient. getMatrixAsVector :: Matrix a -> V.Vector a getMatrixAsVector = mvect . forceMatrix ------------------------------------------------------- ------------------------------------------------------- ---- MANIPULATING MATRICES msetElem :: PrimMonad m => a -- ^ New element -> Index -- ^ Number of columns of the matrix -> Index -- ^ Row offset -> Index -- ^ Column offset -> (Index,Index) -- ^ Position to set the new element -> MV.MVector (PrimState m) a -- ^ Mutable vector -> m () {-# INLINE msetElem #-} msetElem x w ro co (i,j) v = MV.write v (encode w (i+ro,j+co)) x unsafeMset :: PrimMonad m => a -- ^ New element -> Index -- ^ Number of columns of the matrix -> Index -- ^ Row offset -> Index -- ^ Column offset -> (Index,Index) -- ^ Position to set the new element -> MV.MVector (PrimState m) a -- ^ Mutable vector -> m () {-# INLINE unsafeMset #-} unsafeMset x w ro co (i,j) v = MV.unsafeWrite v (encode w (i+ro,j+co)) x -- | Replace the value of a cell in a matrix. setElem :: a -- ^ New value. -> (Index,Index) -- ^ Position to replace. -> Matrix a -- ^ Original matrix. -> Matrix a -- ^ Matrix with the given position replaced with the given value. {-# INLINE setElem #-} setElem x p (M n m ro co w v) = M n m ro co w $ V.modify (msetElem x w ro co p) v -- | Unsafe variant of 'setElem', without bounds checking. unsafeSet :: a -- ^ New value. -> (Index,Index) -- ^ Position to replace. -> Matrix a -- ^ Original matrix. -> Matrix a -- ^ Matrix with the given position replaced with the given value. {-# INLINE unsafeSet #-} unsafeSet x p (M n m ro co w v) = M n m ro co w $ V.modify (unsafeMset x w ro co p) v -- | /O(rows*cols)/. The transpose of a matrix. -- Example: -- -- > ( 1 2 3 ) ( 1 4 7 ) -- > ( 4 5 6 ) ( 2 5 8 ) -- > transpose ( 7 8 9 ) = ( 3 6 9 ) transpose :: Matrix a -> Matrix a transpose m = matrix (ncols m) (nrows m) $ \(i,j) -> m ! (j,i) -- | Extend a matrix to a given size adding a default element. -- If the matrix already has the required size, nothing happens. -- The matrix is /never/ reduced in size. -- Example: -- -- > ( 1 2 3 0 0 ) -- > ( 1 2 3 ) ( 4 5 6 0 0 ) -- > ( 4 5 6 ) ( 7 8 9 0 0 ) -- > extendTo 0 4 5 ( 7 8 9 ) = ( 0 0 0 0 0 ) -- -- The definition of 'extendTo' is based on 'setSize': -- -- > extendTo e n m a = setSize e (max n $ nrows a) (max m $ ncols a) a -- extendTo :: a -- ^ Element to add when extending. -> Index -- ^ Minimal number of rows. -> Index -- ^ Minimal number of columns. -> Matrix a -> Matrix a extendTo e n m a = setSize e (max n $ nrows a) (max m $ ncols a) a -- | Set the size of a matrix to given parameters. Use a default element -- for undefined entries if the matrix has been extended. setSize :: a -- ^ Default element. -> Index -- ^ Number of rows. -> Index -- ^ Number of columns. -> Matrix a -> Matrix a {-# INLINE setSize #-} setSize e n m a@(M n0 m0 _ _ _ _) = matrix n m $ \(i,j) -> if i <= n0 && j <= m0 then unsafeGet i j a else e ------------------------------------------------------- ------------------------------------------------------- ---- WORKING WITH BLOCKS -- | /O(1)/. Extract a submatrix given row and column limits. -- Example: -- -- > ( 1 2 3 ) -- > ( 4 5 6 ) ( 2 3 ) -- > submatrix 1 2 2 3 ( 7 8 9 ) = ( 5 6 ) submatrix :: Index -- ^ Starting row -> Index -- ^ Ending row -> Index -- ^ Starting column -> Index -- ^ Ending column -> Matrix a -> Matrix a {-# INLINE submatrix #-} submatrix r1 r2 c1 c2 (M n m ro co w v) | r1 < 1 || r1 > n = error $ "submatrix: starting row (" ++ show r1 ++ ") is out of range. Matrix has " ++ show n ++ " rows." | c1 < 1 || c1 > m = error $ "submatrix: starting column (" ++ show c1 ++ ") is out of range. Matrix has " ++ show m ++ " columns." | r2 < r1 || r2 > n = error $ "submatrix: ending row (" ++ show r2 ++ ") is out of range. Matrix has " ++ show n ++ " rows, and starting row is " ++ show r1 ++ "." | c2 < c1 || c2 > m = error $ "submatrix: ending column (" ++ show c2 ++ ") is out of range. Matrix has " ++ show m ++ " columns, and starting column is " ++ show c1 ++ "." | otherwise = M (r2-r1+1) (c2-c1+1) (ro+r1-1) (co+c1-1) w v -- | /O(rows*cols)/. Remove a row and a column from a matrix. -- Example: -- -- > ( 1 2 3 ) -- > ( 4 5 6 ) ( 1 3 ) -- > minorMatrix 2 2 ( 7 8 9 ) = ( 7 9 ) minorMatrix :: Index -- ^ Row @r@ to remove. -> Index -- ^ Column @c@ to remove. -> Matrix a -- ^ Original matrix. -> Matrix a -- ^ Matrix with row @r@ and column @c@ removed. minorMatrix r0 c0 (M n m ro co w v) = let r = r0 + ro c = c0 + co in M (n-1) (m-1) ro co (w-1) $ V.ifilter (\k _ -> let (i,j) = decode w k in i /= r && j /= c) v -- | /O(1)/. Make a block-partition of a matrix using a given element as reference. -- The element will stay in the bottom-right corner of the top-left corner matrix. -- -- > ( ) ( | ) -- > ( ) ( ... | ... ) -- > ( x ) ( x | ) -- > splitBlocks i j ( ) = (-------------) , where x = a_{i,j} -- > ( ) ( | ) -- > ( ) ( ... | ... ) -- > ( ) ( | ) -- -- Note that some blocks can end up empty. We use the following notation for these blocks: -- -- > ( TL | TR ) -- > (---------) -- > ( BL | BR ) -- -- Where T = Top, B = Bottom, L = Left, R = Right. -- splitBlocks :: Index -- ^ Row of the splitting element. -> Index -- ^ Column of the splitting element. -> Matrix a -- ^ Matrix to split. -> (Matrix a,Matrix a ,Matrix a,Matrix a) -- ^ (TL,TR,BL,BR) {-# INLINE[1] splitBlocks #-} splitBlocks i j a@(M n m _ _ _ _) = ( submatrix 1 i 1 j a , submatrix 1 i (j+1) m a , submatrix (i+1) n 1 j a , submatrix (i+1) n (j+1) m a ) -- | Join blocks of the form detailed in 'splitBlocks'. Precisely: -- -- > joinBlocks (tl,tr,bl,br) = -- > (tl <|> tr) -- > <-> -- > (bl <|> br) joinBlocks :: (Matrix a,Matrix a,Matrix a,Matrix a) -> Matrix a {-# INLINE[1] joinBlocks #-} joinBlocks (tl,tr,bl,br) = let n = nrows tl nb = nrows bl n' = n + nb m = ncols tl mr = ncols tr m' = m + mr en = encode m' in M n' m' 0 0 m' $ V.create $ do v <- MV.new $ fromIntegral (n'*m') let wr = MV.write v numLoop 1 n $ \i -> do numLoop 1 m $ \j -> wr (en (i ,j )) $ tl ! (i,j) numLoop 1 mr $ \j -> wr (en (i ,j+m)) $ tr ! (i,j) numLoop 1 nb $ \i -> do let i' = i+n numLoop 1 m $ \j -> wr (en (i',j )) $ bl ! (i,j) numLoop 1 mr $ \j -> wr (en (i',j+m)) $ br ! (i,j) return v {-# RULES "matrix/splitAndJoin" forall i j m. joinBlocks (splitBlocks i j m) = m #-} -- | Horizontally join two matrices. Visually: -- -- > ( A ) <|> ( B ) = ( A | B ) -- -- Where both matrices /A/ and /B/ have the same number of rows. -- /This condition is not checked/. (<|>) :: Matrix a -> Matrix a -> Matrix a {-# INLINE (<|>) #-} m <|> m' = let c = ncols m in matrix (nrows m) (c + ncols m') $ \(i,j) -> if j <= c then m ! (i,j) else m' ! (i,j-c) -- | Vertically join two matrices. Visually: -- -- > ( A ) -- > ( A ) <-> ( B ) = ( - ) -- > ( B ) -- -- Where both matrices /A/ and /B/ have the same number of columns. -- /This condition is not checked/. (<->) :: Matrix a -> Matrix a -> Matrix a {-# INLINE (<->) #-} m <-> m' = let r = nrows m in matrix (r + nrows m') (ncols m) $ \(i,j) -> if i <= r then m ! (i,j) else m' ! (i-r,j) ------------------------------------------------------- ------------------------------------------------------- ---- MATRIX OPERATIONS -- | Perform an operation element-wise. -- The second matrix must have at least as many rows -- and columns as the first matrix. If it's bigger, -- the leftover items will be ignored. -- If it's smaller, it will cause a run-time error. -- You may want to use 'elementwiseUnsafe' if you -- are definitely sure that a run-time error won't -- arise. elementwise :: (a -> b -> c) -> (Matrix a -> Matrix b -> Matrix c) elementwise f m m' = matrix (nrows m) (ncols m) $ \k -> f (m ! k) (m' ! k) -- | Unsafe version of 'elementwise', but faster. elementwiseUnsafe :: (a -> b -> c) -> (Matrix a -> Matrix b -> Matrix c) {-# INLINE elementwiseUnsafe #-} elementwiseUnsafe f m m' = matrix (nrows m) (ncols m) $ \(i,j) -> f (unsafeGet i j m) (unsafeGet i j m') infixl 6 +., -. -- | Internal unsafe addition. (+.) :: Num a => Matrix a -> Matrix a -> Matrix a {-# INLINE (+.) #-} (+.) = elementwiseUnsafe (+) -- | Internal unsafe substraction. (-.) :: Num a => Matrix a -> Matrix a -> Matrix a {-# INLINE (-.) #-} (-.) = elementwiseUnsafe (-) ------------------------------------------------------- ------------------------------------------------------- ---- MATRIX MULTIPLICATION {- $mult Four methods are provided for matrix multiplication. * 'multStd': Matrix multiplication following directly the definition. This is the best choice when you know for sure that your matrices are small. * 'multStd2': Matrix multiplication following directly the definition. However, using a different definition from 'multStd'. According to our benchmarks with this version, 'multStd2' is around 3 times faster than 'multStd'. * 'multStrassen': Matrix multiplication following the Strassen's algorithm. Complexity grows slower but also some work is added partitioning the matrix. Also, it only works on square matrices of order @2^n@, so if this condition is not met, it is zero-padded until this is accomplished. Therefore, its use is not recommended. * 'multStrassenMixed': This function mixes the previous methods. It provides a better performance in general. Method @(@'*'@)@ of the 'Num' class uses this function because it gives the best average performance. However, if you know for sure that your matrices are small (size less than 500x500), you should use 'multStd' or 'multStd2' instead, since 'multStrassenMixed' is going to switch to those functions anyway. We keep researching how to get better performance for matrix multiplication. If you want to be on the safe side, use ('*'). -} -- | Standard matrix multiplication by definition. multStd :: Num a => Matrix a -> Matrix a -> Matrix a {-# INLINE multStd #-} multStd a1@(M n m _ _ _ _) a2@(M n' m' _ _ _ _) -- Checking that sizes match... | m /= n' = error $ "Multiplication of " ++ sizeStr n m ++ " and " ++ sizeStr n' m' ++ " matrices." | otherwise = multStd_ a1 a2 -- | Standard matrix multiplication by definition. multStd2 :: Num a => Matrix a -> Matrix a -> Matrix a {-# INLINE multStd2 #-} multStd2 a1@(M n m _ _ _ _) a2@(M n' m' _ _ _ _) -- Checking that sizes match... | m /= n' = error $ "Multiplication of " ++ sizeStr n m ++ " and " ++ sizeStr n' m' ++ " matrices." | otherwise = multStd__ a1 a2 -- | Standard matrix multiplication by definition, without checking if sizes match. multStd_ :: Num a => Matrix a -> Matrix a -> Matrix a {-# INLINE multStd_ #-} multStd_ a@(M 1 1 _ _ _ _) b@(M 1 1 _ _ _ _) = M 1 1 0 0 1 $ V.singleton $ (a ! (1,1)) * (b ! (1,1)) multStd_ a@(M 2 2 _ _ _ _) b@(M 2 2 _ _ _ _) = M 2 2 0 0 2 $ let -- A a11 = a !. (1,1) ; a12 = a !. (1,2) a21 = a !. (2,1) ; a22 = a !. (2,2) -- B b11 = b !. (1,1) ; b12 = b !. (1,2) b21 = b !. (2,1) ; b22 = b !. (2,2) in V.fromList [ a11*b11 + a12*b21 , a11*b12 + a12*b22 , a21*b11 + a22*b21 , a21*b12 + a22*b22 ] multStd_ a@(M 3 3 _ _ _ _) b@(M 3 3 _ _ _ _) = M 3 3 0 0 3 $ let -- A a11 = a !. (1,1) ; a12 = a !. (1,2) ; a13 = a !. (1,3) a21 = a !. (2,1) ; a22 = a !. (2,2) ; a23 = a !. (2,3) a31 = a !. (3,1) ; a32 = a !. (3,2) ; a33 = a !. (3,3) -- B b11 = b !. (1,1) ; b12 = b !. (1,2) ; b13 = b !. (1,3) b21 = b !. (2,1) ; b22 = b !. (2,2) ; b23 = b !. (2,3) b31 = b !. (3,1) ; b32 = b !. (3,2) ; b33 = b !. (3,3) in V.fromList [ a11*b11 + a12*b21 + a13*b31 , a11*b12 + a12*b22 + a13*b32 , a11*b13 + a12*b23 + a13*b33 , a21*b11 + a22*b21 + a23*b31 , a21*b12 + a22*b22 + a23*b32 , a21*b13 + a22*b23 + a23*b33 , a31*b11 + a32*b21 + a33*b31 , a31*b12 + a32*b22 + a33*b32 , a31*b13 + a32*b23 + a33*b33 ] multStd_ a@(M n m _ _ _ _) b@(M _ m' _ _ _ _) = matrix n m' $ \(i,j) -> sum [ a !. (i,k) * b !. (k,j) | k <- [1 .. m] ] multStd__ :: Num a => Matrix a -> Matrix a -> Matrix a {-# INLINE multStd__ #-} multStd__ a b = matrix r c $ \(i,j) -> dotProduct (V.unsafeIndex avs $ fromIntegral $ i - 1) (V.unsafeIndex bvs $ fromIntegral $ j - 1) where r = nrows a avs = V.generate (fromIntegral r) $ \i -> getRow (fromIntegral i+1) a c = ncols b bvs = V.generate (fromIntegral c) $ \i -> getCol (fromIntegral i+1) b dotProduct :: Num a => V.Vector a -> V.Vector a -> a {-# INLINE dotProduct #-} dotProduct v1 v2 = numLoopFold 0 (V.length v1 - 1) 0 $ \r i -> V.unsafeIndex v1 i * V.unsafeIndex v2 i + r {- dotProduct v1 v2 = go (V.length v1 - 1) 0 where go (-1) a = a go i a = go (i-1) $ (V.unsafeIndex v1 i) * (V.unsafeIndex v2 i) + a -} first :: (a -> Bool) -> [a] -> a first f = go where go (x:xs) = if f x then x else go xs go _ = error "first: no element match the condition." -- | Strassen's algorithm over square matrices of order @2^n@. strassen :: Num a => Matrix a -> Matrix a -> Matrix a -- Trivial 1x1 multiplication. strassen a@(M 1 1 _ _ _ _) b@(M 1 1 _ _ _ _) = M 1 1 0 0 1 $ V.singleton $ (a ! (1,1)) * (b ! (1,1)) -- General case guesses that the input matrices are square matrices -- whose order is a power of two. strassen a b = joinBlocks (c11,c12,c21,c22) where -- Size of the subproblem is halved. n = div (nrows a) 2 -- Split of the original problem into smaller subproblems. (a11,a12,a21,a22) = splitBlocks n n a (b11,b12,b21,b22) = splitBlocks n n b -- The seven Strassen's products. p1 = strassen (a11 + a22) (b11 + b22) p2 = strassen (a21 + a22) b11 p3 = strassen a11 (b12 - b22) p4 = strassen a22 (b21 - b11) p5 = strassen (a11 + a12) b22 p6 = strassen (a21 - a11) (b11 + b12) p7 = strassen (a12 - a22) (b21 + b22) -- Merging blocks c11 = p1 + p4 - p5 + p7 c12 = p3 + p5 c21 = p2 + p4 c22 = p1 - p2 + p3 + p6 -- | Strassen's matrix multiplication. multStrassen :: Num a => Matrix a -> Matrix a -> Matrix a multStrassen a1@(M n m _ _ _ _) a2@(M n' m' _ _ _ _) | m /= n' = error $ "Multiplication of " ++ sizeStr n m ++ " and " ++ sizeStr n' m' ++ " matrices." | otherwise = let mx = maximum [n,m,n',m'] n2 = first (>= mx) $ fmap (2^) [(0 :: Int)..] b1 = setSize 0 n2 n2 a1 b2 = setSize 0 n2 n2 a2 in submatrix 1 n 1 m' $ strassen b1 b2 strmixFactor :: Index strmixFactor = 300 -- | Strassen's mixed algorithm. strassenMixed :: Num a => Matrix a -> Matrix a -> Matrix a {-# SPECIALIZE strassenMixed :: Matrix Double -> Matrix Double -> Matrix Double #-} {-# SPECIALIZE strassenMixed :: Matrix Int -> Matrix Int -> Matrix Int #-} {-# SPECIALIZE strassenMixed :: Matrix Rational -> Matrix Rational -> Matrix Rational #-} strassenMixed a b | r < strmixFactor = multStd__ a b | odd r = let r' = r + 1 a' = setSize 0 r' r' a b' = setSize 0 r' r' b in submatrix 1 r 1 r $ strassenMixed a' b' | otherwise = M r r 0 0 r $ V.create $ do v <- MV.unsafeNew $ fromIntegral (r*r) let en = encode r n' = n + 1 -- c11 = p1 + p4 - p5 + p7 sequence_ [ MV.write v k $ unsafeGet i j p1 + unsafeGet i j p4 - unsafeGet i j p5 + unsafeGet i j p7 | i <- [1..n] , j <- [1..n] , let k = en (i,j) ] -- c12 = p3 + p5 sequence_ [ MV.write v k $ unsafeGet i j' p3 + unsafeGet i j' p5 | i <- [1..n] , j <- [n'..r] , let k = en (i,j) , let j' = j - n ] -- c21 = p2 + p4 sequence_ [ MV.write v k $ unsafeGet i' j p2 + unsafeGet i' j p4 | i <- [n'..r] , j <- [1..n] , let k = en (i,j) , let i' = i - n ] -- c22 = p1 - p2 + p3 + p6 sequence_ [ MV.write v k $ unsafeGet i' j' p1 - unsafeGet i' j' p2 + unsafeGet i' j' p3 + unsafeGet i' j' p6 | i <- [n'..r] , j <- [n'..r] , let k = en (i,j) , let i' = i - n , let j' = j - n ] return v where r = nrows a -- Size of the subproblem is halved. n = quot r 2 -- Split of the original problem into smaller subproblems. (a11,a12,a21,a22) = splitBlocks n n a (b11,b12,b21,b22) = splitBlocks n n b -- The seven Strassen's products. p1 = strassenMixed (a11 +. a22) (b11 +. b22) p2 = strassenMixed (a21 +. a22) b11 p3 = strassenMixed a11 (b12 -. b22) p4 = strassenMixed a22 (b21 -. b11) p5 = strassenMixed (a11 +. a12) b22 p6 = strassenMixed (a21 -. a11) (b11 +. b12) p7 = strassenMixed (a12 -. a22) (b21 +. b22) -- | Mixed Strassen's matrix multiplication. multStrassenMixed :: Num a => Matrix a -> Matrix a -> Matrix a {-# INLINE multStrassenMixed #-} multStrassenMixed a1@(M n m _ _ _ _) a2@(M n' m' _ _ _ _) | m /= n' = error $ "Multiplication of " ++ sizeStr n m ++ " and " ++ sizeStr n' m' ++ " matrices." | n < strmixFactor = multStd__ a1 a2 | otherwise = let mx = maximum [n,m,n',m'] n2 = if even mx then mx else mx+1 b1 = setSize 0 n2 n2 a1 b2 = setSize 0 n2 n2 a2 in submatrix 1 n 1 m' $ strassenMixed b1 b2 ------------------------------------------------------- ------------------------------------------------------- ---- NUMERICAL INSTANCE instance Num a => Num (Matrix a) where fromInteger = M 1 1 0 0 1 . V.singleton . fromInteger negate = fmap negate abs = fmap abs signum = fmap signum -- Addition of matrices. {-# SPECIALIZE (+) :: Matrix Double -> Matrix Double -> Matrix Double #-} {-# SPECIALIZE (+) :: Matrix Int -> Matrix Int -> Matrix Int #-} {-# SPECIALIZE (+) :: Matrix Rational -> Matrix Rational -> Matrix Rational #-} (+) = elementwise (+) -- Substraction of matrices. {-# SPECIALIZE (-) :: Matrix Double -> Matrix Double -> Matrix Double #-} {-# SPECIALIZE (-) :: Matrix Int -> Matrix Int -> Matrix Int #-} {-# SPECIALIZE (-) :: Matrix Rational -> Matrix Rational -> Matrix Rational #-} (-) = elementwise (-) -- Multiplication of matrices. {-# INLINE (*) #-} (*) = multStrassenMixed ------------------------------------------------------- ------------------------------------------------------- ---- TRANSFORMATIONS -- | Scale a matrix by a given factor. -- Example: -- -- > ( 1 2 3 ) ( 2 4 6 ) -- > ( 4 5 6 ) ( 8 10 12 ) -- > scaleMatrix 2 ( 7 8 9 ) = ( 14 16 18 ) scaleMatrix :: Num a => a -> Matrix a -> Matrix a scaleMatrix = fmap . (*) -- | Scale a row by a given factor. -- Example: -- -- > ( 1 2 3 ) ( 1 2 3 ) -- > ( 4 5 6 ) ( 8 10 12 ) -- > scaleRow 2 2 ( 7 8 9 ) = ( 7 8 9 ) scaleRow :: Num a => a -> Index -> Matrix a -> Matrix a scaleRow = mapRow . const . (*) -- | Add to one row a scalar multiple of another row. -- Example: -- -- > ( 1 2 3 ) ( 1 2 3 ) -- > ( 4 5 6 ) ( 6 9 12 ) -- > combineRows 2 2 1 ( 7 8 9 ) = ( 7 8 9 ) combineRows :: Num a => Index -> a -> Index -> Matrix a -> Matrix a combineRows r1 l r2 m = mapRow (\j x -> x + l * getElem r2 j m) r1 m -- r1 = r1 + l * r2 -- | Switch two rows of a matrix. -- Example: -- -- > ( 1 2 3 ) ( 4 5 6 ) -- > ( 4 5 6 ) ( 1 2 3 ) -- > switchRows 1 2 ( 7 8 9 ) = ( 7 8 9 ) switchRows :: Index -- ^ Row 1. -> Index -- ^ Row 2. -> Matrix a -- ^ Original matrix. -> Matrix a -- ^ Matrix with rows 1 and 2 switched. switchRows r1 r2 (M n m ro co w vs) = M n m ro co w $ V.modify (\mv -> do numLoop 1 m $ \j -> MV.swap mv (encode w (r1+ro,j+co)) (encode w (r2+ro,j+co))) vs -- | Switch two coumns of a matrix. -- Example: -- -- > ( 1 2 3 ) ( 2 1 3 ) -- > ( 4 5 6 ) ( 5 4 6 ) -- > switchCols 1 2 ( 7 8 9 ) = ( 8 7 9 ) switchCols :: Index -- ^ Col 1. -> Index -- ^ Col 2. -> Matrix a -- ^ Original matrix. -> Matrix a -- ^ Matrix with cols 1 and 2 switched. switchCols c1 c2 (M n m ro co w vs) = M n m ro co w $ V.modify (\mv -> do numLoop 1 n $ \j -> MV.swap mv (encode m (j+ro,c1+co)) (encode m (j+ro,c2+co))) vs ------------------------------------------------------- ------------------------------------------------------- ---- DECOMPOSITIONS -- LU DECOMPOSITION -- | Matrix LU decomposition with /partial pivoting/. -- The result for a matrix /M/ is given in the format /(U,L,P,d)/ where: -- -- * /U/ is an upper triangular matrix. -- -- * /L/ is an /unit/ lower triangular matrix. -- -- * /P/ is a permutation matrix. -- -- * /d/ is the determinant of /P/. -- -- * /PM = LU/. -- -- These properties are only guaranteed when the input matrix is invertible. -- An additional property matches thanks to the strategy followed for pivoting: -- -- * /L_(i,j)/ <= 1, for all /i,j/. -- -- This follows from the maximal property of the selected pivots, which also -- leads to a better numerical stability of the algorithm. -- -- Example: -- -- > ( 1 2 0 ) ( 2 0 2 ) ( 1 0 0 ) ( 0 0 1 ) -- > ( 0 2 1 ) ( 0 2 -1 ) ( 1/2 1 0 ) ( 1 0 0 ) -- > luDecomp ( 2 0 2 ) = ( ( 0 0 2 ) , ( 0 1 1 ) , ( 0 1 0 ) , 1 ) -- -- 'Nothing' is returned if no LU decomposition exists. luDecomp :: (Ord a, Fractional a, NFData a) => Matrix a -> Maybe (Matrix a,Matrix a,Matrix a,a) luDecomp = luDecompWithMag abs luDecompWithMag :: (Ord m, Eq a, Fractional a, NFData a) => (a -> m) -> Matrix a -> Maybe (Matrix a,Matrix a,Matrix a,a) luDecompWithMag getMagnitude a = recLUDecomp getMagnitude a i i 1 1 n where i = identity $ nrows a n = min (nrows a) (ncols a) recLUDecomp :: (Ord m, Eq a, Fractional a, NFData a) => (a -> m) -- ^ getMagnitude -> Matrix a -- ^ U -> Matrix a -- ^ L -> Matrix a -- ^ P -> a -- ^ d -> Index -- ^ Current row -> Index -- ^ Total rows -> Maybe (Matrix a,Matrix a,Matrix a,a) recLUDecomp getMagnitude u l p d k n = if k > n then Just (u,l,p,d) else if ukk == 0 then Nothing else recLUDecomp getMagnitude u'' l'' p' d' (k+1) n where -- Pivot strategy: maximum value in absolute value below the current row. i = maximumBy (\x y -> compare (getMagnitude $ u ! (x,k)) (getMagnitude $ u ! (y,k))) [ k .. n ] -- Switching to place pivot in current row. u' = switchRows k i u l' = let lw = vcols l en = encode lw lro = rowOffset l lco = colOffset l in if i == k then l else M (nrows l) (ncols l) lro lco lw $ V.modify (\mv -> forM_ [1 .. k-1] $ \j -> MV.swap mv (en (i+lro,j+lco)) (en (k+lro,j+lco)) ) $ mvect l p' = switchRows k i p -- Permutation determinant d' = if i == k then d else negate d -- Cancel elements below the pivot. (u'',l'') = go u' l' (k+1) ukk = u' ! (k,k) go u_ l_ j = deepseq u_ $ deepseq l_ $ if j > nrows u_ then (u_,l_) else let x = (u_ ! (j,k)) / ukk in go (combineRows j (-x) k u_) (setElem x (j,k) l_) (j+1) -- | Unsafe version of 'luDecomp'. It fails when the input matrix is singular. luDecompUnsafe :: (Ord a, Fractional a, NFData a) => Matrix a -> (Matrix a, Matrix a, Matrix a, a) luDecompUnsafe m = case luDecomp m of Just x -> x _ -> error "luDecompUnsafe of singular matrix." -- | Matrix LU decomposition with /complete pivoting/. -- The result for a matrix /M/ is given in the format /(U,L,P,Q,d,e)/ where: -- -- * /U/ is an upper triangular matrix. -- -- * /L/ is an /unit/ lower triangular matrix. -- -- * /P,Q/ are permutation matrices. -- -- * /d,e/ are the determinants of /P/ and /Q/ respectively. -- -- * /PMQ = LU/. -- -- These properties are only guaranteed when the input matrix is invertible. -- An additional property matches thanks to the strategy followed for pivoting: -- -- * /L_(i,j)/ <= 1, for all /i,j/. -- -- This follows from the maximal property of the selected pivots, which also -- leads to a better numerical stability of the algorithm. -- -- Example: -- -- > ( 1 0 ) ( 2 1 ) ( 1 0 0 ) ( 0 0 1 ) -- > ( 0 2 ) ( 0 2 ) ( 0 1 0 ) ( 0 1 0 ) ( 1 0 ) -- > luDecomp' ( 2 1 ) = ( ( 0 0 ) , ( 1/2 -1/4 1 ) , ( 1 0 0 ) , ( 0 1 ) , -1 , 1 ) -- -- 'Nothing' is returned if no LU decomposition exists. luDecomp' :: (Ord a, Fractional a) => Matrix a -> Maybe (Matrix a,Matrix a,Matrix a,Matrix a,a,a) luDecomp' = luDecompWithMag' abs; luDecompWithMag' :: (Ord m, Eq a, Fractional a) => (a -> m) -> Matrix a -> Maybe (Matrix a,Matrix a,Matrix a,Matrix a,a,a) luDecompWithMag' getMagnitude a = recLUDecomp' getMagnitude a i i (identity $ ncols a) 1 1 1 n where i = identity $ nrows a n = min (nrows a) (ncols a) -- | Unsafe version of 'luDecomp''. It fails when the input matrix is singular. luDecompUnsafe' :: (Ord a, Fractional a) => Matrix a -> (Matrix a, Matrix a, Matrix a, Matrix a, a, a) luDecompUnsafe' m = case luDecomp' m of Just x -> x _ -> error "luDecompUnsafe' of singular matrix." recLUDecomp' :: (Ord m, Eq a, Fractional a) => (a -> m) -- ^ getMagnitude -> Matrix a -- ^ U -> Matrix a -- ^ L -> Matrix a -- ^ P -> Matrix a -- ^ Q -> a -- ^ d -> a -- ^ e -> Index -- ^ Current row -> Index -- ^ Total rows -> Maybe (Matrix a,Matrix a,Matrix a,Matrix a,a,a) recLUDecomp' getMagnitude u l p q d e k n = if k > n || u'' ! (k, k) == 0 then Just (u,l,p,q,d,e) else if ukk == 0 then Nothing else recLUDecomp' getMagnitude u'' l'' p' q' d' e' (k+1) n where -- Pivot strategy: maximum value in absolute value below the current row & col. (i, j) = maximumBy (comparing (\(i0, j0) -> getMagnitude $ u ! (i0,j0))) [ (i0, j0) | i0 <- [k .. nrows u], j0 <- [k .. ncols u] ] -- Switching to place pivot in current row. u' = switchCols k j $ switchRows k i u l'0 = switchRows k i l l' = switchCols k i l'0 p' = switchRows k i p q' = switchCols k j q -- Permutation determinant d' = if i == k then d else negate d e' = if j == k then e else negate e -- Cancel elements below the pivot. (u'',l'') = go u' l' (k+1) ukk = u' ! (k,k) go u_ l_ h = if h > nrows u_ then (u_,l_) else let x = (u_ ! (h,k)) / ukk in go (combineRows h (-x) k u_) (setElem x (h,k) l_) (h+1) -- CHOLESKY DECOMPOSITION -- | Simple Cholesky decomposition of a symmetric, positive definite matrix. -- The result for a matrix /M/ is a lower triangular matrix /L/ such that: -- -- * /M = LL^T/. -- -- Example: -- -- > ( 2 -1 0 ) ( 1.41 0 0 ) -- > ( -1 2 -1 ) ( -0.70 1.22 0 ) -- > cholDecomp ( 0 -1 2 ) = ( 0.00 -0.81 1.15 ) cholDecomp :: (Floating a) => Matrix a -> Matrix a cholDecomp a | (nrows a == 1) && (ncols a == 1) = fmap sqrt a | otherwise = joinBlocks (l11, l12, l21, l22) where (a11, a12, a21, a22) = splitBlocks 1 1 a l11' = sqrt (a11 ! (1,1)) l11 = fromList 1 1 [l11'] l12 = zero (nrows a12) (ncols a12) l21 = scaleMatrix (1/l11') a21 a22' = a22 - multStd l21 (transpose l21) l22 = cholDecomp a22' ------------------------------------------------------- ------------------------------------------------------- ---- PROPERTIES {-# RULES "matrix/traceOfSum" forall a b. trace (a + b) = trace a + trace b "matrix/traceOfScale" forall k a. trace (scaleMatrix k a) = k * trace a #-} -- | Sum of the elements in the diagonal. See also 'getDiag'. -- Example: -- -- > ( 1 2 3 ) -- > ( 4 5 6 ) -- > trace ( 7 8 9 ) = 15 trace :: Num a => Matrix a -> a {-# NOINLINE trace #-} trace = V.sum . getDiag -- | Product of the elements in the diagonal. See also 'getDiag'. -- Example: -- -- > ( 1 2 3 ) -- > ( 4 5 6 ) -- > diagProd ( 7 8 9 ) = 45 diagProd :: Num a => Matrix a -> a diagProd = V.product . getDiag -- DETERMINANT {-# RULES "matrix/detLaplaceProduct" forall a b. detLaplace (a*b) = detLaplace a * detLaplace b "matrix/detLUProduct" forall a b. detLU (a*b) = detLU a * detLU b #-} -- | Matrix determinant using Laplace expansion. -- If the elements of the 'Matrix' are instance of 'Ord' and 'Fractional' -- consider to use 'detLU' in order to obtain better performance. -- Function 'detLaplace' is /extremely/ slow. detLaplace :: Num a => Matrix a -> a {-# NOINLINE detLaplace #-} detLaplace m@(M 1 1 _ _ _ _) = m ! (1,1) detLaplace m = sum1 [ (-1)^(i-1) * m ! (i,1) * detLaplace (minorMatrix i 1 m) | i <- [1 .. nrows m] ] where sum1 = foldl1' (+) -- | Matrix determinant using LU decomposition. -- It works even when the input matrix is singular. detLU :: (Ord a, Fractional a, NFData a) => Matrix a -> a {-# NOINLINE detLU #-} detLU m = case luDecomp m of Just (u,_,_,d) -> d * diagProd u Nothing -> 0 invertS :: (MonadPlus maybe, Eq a, Num a, Fractional a, NFData a) => Matrix a -> maybe (Matrix a) invertS m = let size = nrows m augmented = m <|> identity size in if size /= ncols m then mzero else gauss_jordan 1 augmented >>= return . submatrix 1 size (size+1) (2*size) gauss_jordan :: (MonadPlus maybe, Eq a, Num a, Fractional a, NFData a) => Index -> Matrix a -> maybe (Matrix a) gauss_jordan start m = do pivot <- findPivotS start m [start .. nrows m] (if start < nrows m then gauss_jordan (start+1) else return . execState ( mapM_ do_jordanS $ reverse [1..nrows m]) ) $ execState (do_gaussS start pivot) m do_gaussS :: (Fractional a, Num a, NFData a) => Index -> Index -> State (Matrix a) () do_gaussS start pivot = do State.modify' $ switchRows start pivot m <- State.get State.modify' $ scaleRow (recip $ m ! (start,start)) start rows <- State.gets nrows mapM_ (one_rowopS start) [start+1 .. rows] -- forceMatrixState -- ^ LESSFREQUENTLY one_rowopS :: (Num a, Fractional a, NFData a) => Index -> Index -> State (Matrix a) () one_rowopS source target = do m <- State.get let lower = m ! (target,source) State.modify' $ combineRows target (negate lower) source forceMatrixState -- ^ this forces the entire matrix, which is seems than optimal, but -- actually seems faster than forcing less frequently (see annotations -- for LESSFREQUENTLY) , possibly because of less time spent on -- garbage collection -- | this is not enough -- mapM_ (\i -> deepseq (m ! (target,i)) $ return ()) [1.. ncols m] -- pivot strategy is to find the first nonzero entry. this is not -- numerically optimal, but if you care about numerical issues, you -- should not be inverting a matrix anyway: use luDecomp instead. -- This was originally written for exact Rational arithmetic. findPivotS :: (MonadPlus maybe, Eq a, Num a) => Index -> Matrix a -> [Index] -> maybe Index findPivotS _ _ [] = mzero findPivotS column m (h:t) = if m ! (h,column) /= 0 -- testing for equality with zero is the million dollar question then return h else findPivotS column m t -- the backwards part is easier because the diagonal should be all -- ones now. do_jordanS :: (Fractional a, Num a, NFData a) => Index -> State (Matrix a) () do_jordanS start = do mapM_ (one_rowopS start) [1.. pred start] -- forceMatrixState -- ^ LESSFREQUENTLY forceMatrixState :: (NFData a) => State (Matrix a) () forceMatrixState = do m <- State.get deepseq m $ return () invert :: (MonadPlus maybe, Eq a, Fractional a) => Matrix a -> maybe (Matrix a); -- gauss_jordan1 m = runST $ gauss_jordan m; -- a unusual case where (.) does not work invert m = let { size = nrows m } in if size /= ncols m then mzero else toMonadPlus $ runST $ runMaybeT $ gauss_jordan1 $ m <|> identity size; -- add to library toMonadPlus :: (MonadPlus m) => Maybe a -> m a; toMonadPlus = \case { Nothing -> mzero; Just x -> return x; }; gauss_jordan1 :: forall monad ty. (PrimMonad monad, Eq ty, Fractional ty) => Matrix ty -> MaybeT monad (Matrix ty); gauss_jordan1 original = do { let {size = nrows original} ; m :: Mutablematrix (PrimState monad) ty <- lift $ thaw_matrix original ; mapM_ (onegauss m) $ enumFromTo 1 size ; mapM_ (lift . do_jordan m) $ enumFromThenTo size (pred size) 1 ; lift $ freeze_matrix m >>= return . submatrix 1 size (size+1) (2*size) }; data Mutablematrix s a = Mutablematrix { mrows :: !Index , mcols :: !Index , muvect :: MV.MVector s a }; type Coord = (Index,Index); freeze_matrix :: (PrimMonad monad) => Mutablematrix (PrimState monad) a -> monad (Matrix a); freeze_matrix (Mutablematrix x y z) = V.freeze z >>= return . M x y 0 0 y; thaw_matrix :: forall monad a . (PrimMonad monad) => Matrix a -> monad (Mutablematrix (PrimState monad) a); thaw_matrix m = V.thaw (getMatrixAsVector m) >>= return . Mutablematrix (nrows m) (ncols m); onegauss :: (PrimMonad monad, Fractional ty, Eq ty) => Mutablematrix (PrimState monad) ty -> Index -> MaybeT monad (); onegauss a start = do { f <- lift $ freeze_matrix a; pivot <- findPivot start f [start .. nrows f]; lift $ do_gauss start pivot a; }; -- pivot strategy is to find the first nonzero entry. this is not -- numerically optimal, but if you care about numerical issues, you -- should not be inverting a matrix anyway: use luDecomp instead. -- This was originally written for exact Rational arithmetic. findPivot :: (MonadPlus maybe, Eq a, Num a) => Index -> Matrix a -> [Index] -> maybe Index; findPivot _ _ [] = mzero; findPivot column m (h:t) = if m ! (h,column) /= 0 -- testing for equality with zero is the million dollar question then return h else findPivot column m t; do_gauss :: (Fractional a, Num a, PrimMonad monad) => Index -> Index -> Mutablematrix (PrimState monad) a -> monad (); do_gauss start pivot m = do { switchRowsM start pivot m; pval <- getElemM m (start,start); scaleRowM (recip pval) start m; mapM_ (one_rowop start m) [start+1 .. (mrows m)]; }; one_rowop :: (Fractional a, Num a, PrimMonad monad) => Index -> Mutablematrix (PrimState monad) a -> Index -> monad (); one_rowop source m target = do { lower <- getElemM m (target,source); combineRowsM target (negate lower) source m; }; getElemM :: (PrimMonad monad) => Mutablematrix (PrimState monad) ty -> Coord -> monad ty; getElemM a i = MV.read (muvect a) $ encode (mcols a) i; write :: (PrimMonad monad) => Mutablematrix (PrimState monad) ty -> Coord -> ty -> monad (); write a i x = MV.write (muvect a) (encode (mcols a) i) x; swap :: (PrimMonad monad) => Mutablematrix (PrimState monad) ty -> Coord -> Coord -> monad (); swap a i j = MV.swap (muvect a) (encode (mcols a) i) (encode (mcols a) j); switchRowsM :: (PrimMonad monad) => Index -> Index -> Mutablematrix (PrimState monad) ty -> monad (); switchRowsM i j a = mapcols a $ \c -> swap a (i,c) (j,c); combineRowsM :: (PrimMonad monad, Num ty) => Index -> ty -> Index -> Mutablematrix (PrimState monad) ty -> monad (); -- r1 = r1 + l * r2 combineRowsM r1 l r2 a = mapcols a $ \c -> do { v1 <- getElemM a (r1,c) ; v2 <- getElemM a (r2,c) ; let { x = v1+l*v2; }; ; seq x $ write a (r1,c) x; -- avoid small space leak }; scaleRowM :: (PrimMonad monad, Num ty) => ty -> Index -> Mutablematrix (PrimState monad) ty -> monad (); scaleRowM multiplier r a = mapcols a $ \c -> do { v <- getElemM a (r,c) ; write a (r,c) $ multiplier * v }; mapcols :: (PrimMonad monad) => Mutablematrix (PrimState monad) ty -> (Index -> monad ()) -> monad (); mapcols m f = mapM_ f $ enumFromTo 1 $ mcols m; -- the backwards part is easier because the diagonal should be all -- ones now. do_jordan :: (PrimMonad monad, Fractional ty) => Mutablematrix (PrimState monad) ty -> Index -> monad (); do_jordan a start = mapM_ (one_rowop start a) [1.. pred start];
kenta2/matrix
Data/Matrix.hs
bsd-3-clause
50,551
1
22
14,959
14,850
7,950
6,900
-1
-1
module MBE.Store ( store ) where import Data.List import MDB.PHashMap import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as C import qualified Data.Word as W punctuation :: B.ByteString punctuation = C.pack ",.;!? " noPunctuation :: W.Word8 -> Bool noPunctuation = flip B.notElem punctuation groupByPunctuation :: B.ByteString -> [B.ByteString] groupByPunctuation = B.groupBy (\a b -> B.all noPunctuation $ B.pack [a,b]) delSpaces :: [B.ByteString] -> [B.ByteString] delSpaces l = l \\ replicate (length l) (C.singleton ' ') store :: FilePath -> B.ByteString -> IO () store path s = do db <- checkDB path writeDB path $ inFunc db splitList where splitList = map (delSpaces . groupByPunctuation) lineList lineList = C.lines s inFunc :: Database -> [[Word]] -> Database inFunc = foldl (\ db x -> wpMaker db (C.singleton '^':x)) wpMaker :: Database -> [Word] -> Database wpMaker db (x:y:xs) = wpMaker (updateDB (x,y) db) (y:xs) wpMaker db (x:[]) = updateDB (x,C.singleton '$') db wpMaker db [] = db
c-14/hmctg
src/MBE/Store.hs
bsd-3-clause
1,087
0
12
222
440
236
204
27
1
{-# LANGUAGE TemplateHaskell #-} -- | -- Lenses for several data types of the 'Distribution.Version' module. -- All lenses are named after their field names with a 'L' appended. module CabalLenses.Version where import Distribution.Version import Control.Lens versionBranchL :: Iso' Version [Int] versionBranchL = iso versionNumbers mkVersion intervals :: Iso' VersionRange [VersionInterval] intervals = iso asVersionIntervals toVersionRange where toVersionRange [] = anyVersion toVersionRange intervals = fromVersionIntervals . mkVersionIntervals $ intervals lowerBound :: Lens' VersionInterval LowerBound lowerBound = _1 version :: Lens' LowerBound Version version = lens getVersion setVersion where getVersion (LowerBound vers _) = vers setVersion (LowerBound _ bound) vers = LowerBound vers bound bound :: Lens' LowerBound Bound bound = lens getBound setBound where getBound (LowerBound _ bound) = bound setBound (LowerBound vers _) bound = LowerBound vers bound upperBound :: Lens' VersionInterval UpperBound upperBound = _2 noLowerBound :: LowerBound noLowerBound = LowerBound (mkVersion [0]) InclusiveBound
dan-t/cabal-lenses
lib/CabalLenses/Version.hs
bsd-3-clause
1,199
0
9
232
270
141
129
24
2
{-# OPTIONS_GHC -XBangPatterns #-} ----------------------------------------------------------------------------- -- Module : Math.Statistics -- Copyright : (c) 2008 Marshall Beddoe -- License : BSD3 -- -- Maintainer : mbeddoe@<nospam>gmail.com -- Stability : experimental -- Portability : portable -- -- Description : -- A collection of commonly used statistical functions. -- can't cabal install it since it's too old so a branch lives here ----------------------------------------------------------------------------- module Statistics where import Data.List import Data.Ord (comparing) {----------------------------------------------------------------------------- I. From original library ------------------------------------------------------------------------------} -- |Numerically stable mean mean :: Floating a => [a] -> a mean x = fst $ foldl' (\(!m, !n) x -> (m+(x-m)/(n+1),n+1)) (0,0) x -- |Harmonic mean harmean :: (Floating a) => [a] -> a harmean xs = fromIntegral (length xs) / (sum $ map (1/) xs) -- |Geometric mean geomean :: (Floating a) => [a] -> a geomean xs = (foldr1 (*) xs)**(1 / fromIntegral (length xs)) -- |Median median :: (Floating a, Ord a) => [a] -> a median x | odd n = head $ drop (n `div` 2) x' | even n = mean $ take 2 $ drop i x' where i = (length x' `div` 2) - 1 x' = sort x n = length x -- |Modes returns a sorted list of modes in descending order modes :: (Ord a) => [a] -> [(Int, a)] modes xs = sortBy (comparing $ negate.fst) $ map (\x->(length x, head x)) $ (group.sort) xs -- |Mode returns the mode of the list, otherwise Nothing mode :: (Ord a) => [a] -> Maybe a mode xs = case m of [] -> Nothing otherwise -> Just . snd $ head m where m = filter (\(a,b) -> a > 1) (modes xs) -- |Central moments centralMoment :: (Floating b, Integral t) => [b] -> t -> b centralMoment xs 1 = 0 centralMoment xs r = (sum (map (\x -> (x-m)^r) xs)) / n where m = mean xs n = fromIntegral $ length xs -- |Range range :: (Num a, Ord a) => [a] -> a range xs = maximum xs - minimum xs -- |Average deviation avgdev :: (Floating a) => [a] -> a avgdev xs = mean $ map (\x -> abs(x - m)) xs where m = mean xs -- |Standard deviation of sample stddev :: (Floating a) => [a] -> a stddev xs = sqrt $ var xs -- |Standard deviation of population stddevp :: (Floating a) => [a] -> a stddevp xs = sqrt $ pvar xs -- |Population variance pvar :: (Floating a) => [a] -> a pvar xs = centralMoment xs 2 -- |Sample variance var xs = (var' 0 0 0 xs) / (fromIntegral $ length xs - 1) where var' _ _ s [] = s var' m n s (x:xs) = var' nm (n + 1) (s + delta * (x - nm)) xs where delta = x - m nm = m + delta/(fromIntegral $ n + 1) -- |Interquartile range iqr xs = take (length xs - 2*q) $ drop q xs where q = ((length xs) + 1) `div` 4 -- Kurtosis kurt xs = ((centralMoment xs 4) / (centralMoment xs 2)^2)-3 -- |Arbitrary quantile q of an unsorted list. The quantile /q/ of /N/ -- |data points is the point whose (zero-based) index in the sorted -- |data set is closest to /q(N-1)/. quantile :: (Fractional b, Ord b) => Double -> [b] -> b quantile q = quantileAsc q . sort -- |As 'quantile' specialized for sorted data quantileAsc :: (Fractional b, Ord b) => Double -> [b] -> b quantileAsc _ [] = error "quantile on empty list" quantileAsc q xs | q < 0 || q > 1 = error "quantile out of range" | otherwise = xs !! (quantIndex (length xs) q) where quantIndex :: Int -> Double -> Int quantIndex len q = case round $ q * (fromIntegral len - 1) of idx | idx < 0 -> error "Quantile index too small" | idx >= len -> error "Quantile index too large" | otherwise -> idx -- |Calculate skew skew :: (Floating b) => [b] -> b skew xs = (centralMoment xs 3) / (centralMoment xs 2)**(3/2) -- |Calculates pearson skew pearsonSkew1 :: (Ord a, Floating a) => [a] -> a pearsonSkew1 xs = 3 * (mean xs - mo) / stddev xs where mo = snd $ head $ modes xs pearsonSkew2 :: (Ord a, Floating a) => [a] -> a pearsonSkew2 xs = 3 * (mean xs - median xs) / stddev xs -- |Sample Covariance covar :: (Floating a) => [a] -> [a] -> a covar xs ys = sum (zipWith (*) (map f1 xs) (map f2 ys)) / (n-1) where n = fromIntegral $ length $ xs m1 = mean xs m2 = mean ys f1 = \x -> (x - m1) f2 = \x -> (x - m2) -- |Covariance matrix covMatrix :: (Floating a) => [[a]] -> [[a]] covMatrix xs = split' (length xs) cs where cs = [ covar a b | a <- xs, b <- xs] split' n = unfoldr (\y -> if null y then Nothing else Just $ splitAt n y) -- |Pearson's product-moment correlation coefficient pearson :: (Floating a) => [a] -> [a] -> a pearson x y = covar x y / (stddev x * stddev y) -- |Same as 'pearson' correl :: (Floating a) => [a] -> [a] -> a correl = pearson -- |Least-squares linear regression of /y/ against /x/ for a -- |collection of (/x/, /y/) data, in the form of (/b0/, /b1/, /r/) -- |where the regression is /y/ = /b0/ + /b1/ * /x/ with Pearson -- |coefficient /r/ linreg :: (Floating b) => [(b, b)] -> (b, b, b) linreg xys = let !xs = map fst xys !ys = map snd xys !n = fromIntegral $ length xys !sX = sum xs !sY = sum ys !sXX = sum $ map (^ 2) xs !sXY = sum $ map (uncurry (*)) xys !sYY = sum $ map (^ 2) ys !alpha = (sY - beta * sX) / n !beta = (n * sXY - sX * sY) / (n * sXX - sX * sX) !r = (n * sXY - sX * sY) / (sqrt $ (n * sXX - sX^2) * (n * sYY - sY ^ 2)) in (alpha, beta, r) -- |Returns the sum of square deviations from their sample mean. devsq :: (Floating a) => [a] -> a devsq xs = sum $ map (\x->(x-m)**2) xs where m = mean xs {----------------------------------------------------------------------------- II. Added by me ------------------------------------------------------------------------------} -- * http://stackoverflow.com/questions/18723381/rounding-to-specific-number-of-digits-in-haskell -- * the better 'pure' method (not so much "fastest") would be to use decodeFloat -- * round the integer in the left component, and then encode the float again -- * instances of Num are things like Int, Integer, but also Float, Double -- * Num could be whole numbers, floats, doubles, decimals, complex, rationals, .. roundTo :: Double -> Int -> Double roundTo x n = (fromIntegral (floor (x * t))) / t where t = 10^n -- * source : http://stackoverflow.com/questions/2376981/haskell-types-frustrating-a-simple-average-function average :: (Integral b, Real a) => [a] -> b average xs = round $ realToFrac (sum xs) / genericLength xs
lingxiao/CIS700
src/Statistics.hs
bsd-3-clause
6,939
0
16
1,850
2,450
1,302
1,148
-1
-1
module TPMUtil where import TPM import Data.ByteString.Lazy hiding (putStrLn) import Data.Word import Data.Binary import Codec.Crypto.RSA hiding (sign, verify) tpm :: TPMSocket tpm = tpm_socket "/var/run/tpm/tpmd_socket:0" ownerPass :: String ownerPass = "adam" srkPass :: String srkPass = "" aikPass :: String aikPass = "i" takeInit :: IO TPM_PUBKEY takeInit = do tpm_forceclear tpm {-sOwner <- tpm_getcap_owner tpm when (hasOwner == False) $ do -} (pubkey, _) <- tpm_key_pubek tpm --putStrLn $ "Public EK: " ++ show pubkey tkShn <- tpm_session_oiap tpm tpm_takeownership tpm tkShn pubkey oPass sPass tpm_session_close tpm tkShn putStrLn "\n\nTPM OWNERSHIP TAKEN\n" return pubkey where oPass = tpm_digest_pass ownerPass sPass = tpm_digest_pass srkPass mkTPMRequest :: [Word8] -> TPM_PCR_SELECTION mkTPMRequest xs = do let max = 24 -- <- tpm_getcap_pcrs tpm --Maybe add this to assumptions?(24) let selection = tpm_pcr_selection max xs in selection makeAndLoadAIK :: IO (TPM_KEY_HANDLE, ByteString) makeAndLoadAIK = do sShn <- tpm_session_oiap tpm oShn <- tpm_session_osap tpm oPass oKty ownerHandle (identKey, iSig) <- tpm_makeidentity tpm sShn oShn key sPass iPass iPass {-pass CALabelDigest here instead of iPass eventually?-} tpm_session_close tpm sShn --Check True val here!!(use clo?) tpm_session_close tpm oShn loadShn <- tpm_session_oiap tpm iKeyHandle <- tpm_loadkey2 tpm loadShn tpm_kh_srk identKey sPass tpm_session_close tpm loadShn --putStrLn "identKey Loaded" return (iKeyHandle, iSig) where key = tpm_key_create_identity tpm_auth_never oKty = tpm_et_xor_owner kty = tpm_et_xor_keyhandle ownerHandle = (0x40000001 :: Word32) oPass = tpm_digest_pass ownerPass sPass = tpm_digest_pass srkPass iPass = tpm_digest_pass aikPass attGetPubKey :: TPM_KEY_HANDLE -> TPM_DIGEST -> IO TPM_PUBKEY attGetPubKey handle pass = do shn <- tpm_session_oiap tpm pubKey <- tpm_getpubkey tpm shn handle pass tpm_session_close tpm shn return pubKey mkQuote :: TPM_KEY_HANDLE -> TPM_DIGEST -> TPM_PCR_SELECTION -> ByteString -> IO (TPM_PCR_COMPOSITE, ByteString) mkQuote qKeyHandle qKeyPass pcrSelect exData = do quoteShn <- tpm_session_oiap tpm putStrLn "Before quote packed and generatedddddddddddddddddddddd" (pcrComp, sig) <- tpm_quote tpm quoteShn qKeyHandle (TPM_NONCE exData) pcrSelect qKeyPass tpm_session_close tpm quoteShn putStrLn $ "\nQuote generated:\n" return (pcrComp, sig) tpm_pcr_composite_hash :: TPM_PCR_COMPOSITE -> TPM_DIGEST tpm_pcr_composite_hash comp = tpm_digest (encode comp) tpm_get_rsa_PublicKey :: TPM_PUBKEY -> PublicKey tpm_get_rsa_PublicKey key = PublicKey size modl expn where size = fromIntegral $ (tpm_key_pubsize key) `div` 8 expn = bs2int $ tpm_key_pubexp key modl = bs2int $ tpm_key_pubmod key pcrModify :: String -> IO TPM_PCRVALUE pcrModify val = tpm_pcr_extend_with tpm (fromIntegral pcrNum) val pcrReset :: IO TPM_PCRVALUE pcrReset = do tot <- tpm_getcap_pcrs tpm tpm_pcr_reset tpm (fromIntegral tot) [fromIntegral pcrNum] val <- tpm_pcr_read tpm (fromIntegral 23) --putStrLn $ show val return val pcrNum = 23
armoredsoftware/protocol
tpm/mainline/protoMonad/TPMUtil.hs
bsd-3-clause
3,333
0
11
691
820
406
414
80
1
{-# LANGUAGE OverloadedStrings #-} module Analyzer where import Control.Comonad.Cofree import Control.Lens hiding (children) import Data.Data.Lens import Data.List (sort, group, nub) import Data.Maybe import Data.Monoid import qualified Data.Text as T import Types extractNamespaceAndRequires :: AST -> Maybe (Namespace, [(Namespace, Namespace)]) extractNamespaceAndRequires (_ :< List (nsform : _)) = case nsform of (_ :< List ( (_ :< Atom "ns") : (_ :< Atom ns) : rest)) -> Just (ns, extractRequires rest) _ -> Nothing extractNamespaceAndRequires _ = Nothing extractRequires :: [AST] -> [(Namespace, Namespace)] extractRequires = concatMap extract where extract (_ :< List ((_ :< Atom ":require") : rs)) = go [] rs extract _ = [] go accum [] = accum go accum (r:rest) = case r of _ :< Atom ns -> go ((ns, ns) : accum) rest _ :< Vec [_ :< Atom ns] -> go ((ns, ns) : accum) rest _ :< Vec atoms -> case atoms ^.. biplate of [ns, ":as", alias] -> go ((alias, ns) : accum) rest (parent : children) -> go ([ (parent <> "." <> child, parent <> "." <> child) | child <- children] <> accum) rest _ -> go accum rest extractDefns :: AST -> [Var] extractDefns (_ :< List sexps) = mapMaybe go sexps where go (_ :< List ( (_ :< Atom "defn") : atoms)) = atoms ^.. biplate & filter ((/= '^') . T.head) & listToMaybe go _ = Nothing extractDefns _ = [] extractExternalUsages :: [(Namespace, Namespace)] -> AST -> [(Namespace, Var)] extractExternalUsages requires sexps = sexps ^.. biplate & mapMaybe parseQualifiedName & over (mapped . _1) expandNs & filter (isJust . fst) & over (mapped . _1) fromJust & nub where expandNs = flip lookup requires extractInternalUsages :: [Var] -> AST -> [Var] extractInternalUsages defns sexps = sexps ^.. biplate & filter (`elem` defns) & sort & group & filter ((> 1) . length) & fmap head & nub parseQualifiedName :: T.Text -> Maybe (Namespace, Var) parseQualifiedName qname = let (ns, slashVar) = T.break (== '/') qname in if T.null slashVar then Nothing else Just (ns, T.drop 1 slashVar) extractRedundantRequires :: SourceFile -> [Namespace] extractRedundantRequires sf = [ns | ns <- fmap snd (sfRequires sf) , ns `notElem` fmap fst (sfExternalUsages sf)]
ethercrow/unused-defns
Analyzer.hs
bsd-3-clause
2,674
0
19
863
969
518
451
70
7
module Common ( module Test.QuickCheck , module Test.HUnit , module Arbitrary , module Text.Printf , module Test.Framework , module Test.Framework.TH , module Test.Framework.Providers.QuickCheck2 , module Test.Framework.Providers.HUnit , assertQuickCheck ) where import Text.Printf import Test.QuickCheck hiding (classify) import Test.HUnit hiding (Testable, Test) import Test.Framework import Test.Framework.TH import Test.Framework.Providers.QuickCheck2 import Test.Framework.Providers.HUnit import Arbitrary assertQuickCheck :: Property -> Assertion assertQuickCheck body = do result <- quickCheckResult body case result of Success _ _ _ -> return () otherwise -> assertFailure ""
frenetic-lang/netcore-1.0
testsuite/Common.hs
bsd-3-clause
718
0
11
112
179
108
71
24
2
{-| -} module Integrate where -- interval-coefficient polynomials: import Numeric.AERN.Poly.IntPoly (IntPoly, IntPolySizeLimits(..), IntPolyEffort(..), defaultIntPolySizeLimits) import Numeric.AERN.Poly.IntPoly.Interval () --import Numeric.AERN.Poly.IntPoly.Plot () -- intervals generic in the type of its endpoints: import Numeric.AERN.Basics.Interval (Interval) -- Doubles as interval endpoints: import Numeric.AERN.RealArithmetic.Basis.Double () -- abstract function processing operations: import Numeric.AERN.RmToRn (newProjection, primitiveFunctionOut, getDomainBox, evalAtPointOut, insertVar, lookupVar) --import qualified -- Numeric.AERN.RmToRn.Plot.FnView -- as FV -- abstract approximate real arithmetic operations: --import Numeric.AERN.RealArithmetic.RefinementOrderRounding -- (piOut, -- sqrtOut, sqrtOutEff, sqrtDefaultEffort, -- expOut, expOutEff, expDefaultEffort) --import Numeric.AERN.RealArithmetic.RefinementOrderRounding.Operators -- ((|<*>)) -- ability to control the effort for elementary operations: --import Numeric.AERN.RealArithmetic.Interval.ElementaryFromFieldOps -- (ExpThinEffortIndicator(..), SqrtThinEffortIndicator(..)) import Numeric.AERN.RealArithmetic.Measures (iterateUntilAccurate) -- abstract approximate order operations: import Numeric.AERN.RefinementOrder (getEndpointsOut) -- endpoints of an interval-like value import Numeric.AERN.RefinementOrder.Operators ((</\>)) -- hull of interval union -- ability to extract and change precision of numbers: import Numeric.AERN.Basics.SizeLimits (getSizeLimits, changeSizeLimitsOut) {----- type definitions -----} type DI = Interval Double type V = String -- names of variables type Poly = IntPoly V DI type PI = Interval Poly type R = DI type RI = DI {----- constructing basic functions -----} integrate :: PI -> R -> (PI -> PI) -> [(Int, R, R)] integrate x e computeF = iterateUntilAccurate 0 30 e $ \ maxdeg -> resultForMaxdeg maxdeg where resultForMaxdeg maxdeg = (evalAtPointOut (domWith domR) pfDeg) - (evalAtPointOut (domWith domL) pfDeg) where pfDeg = pf maxdeg domWith pt = insertVar "x" pt (getDomainBox x) (domL, domR) = getEndpointsOut dom dom = case lookupVar (getDomainBox x) "x" of Just d -> d; _ -> error "" pf maxdeg = primitiveFunctionOut (computeF xEff) "x" where xEff = changeSizeLimitsOut sizeLimit x sizeLimit = (getSizeLimits x) { ipolylimits_maxdeg = maxdeg, ipolylimits_maxsize = maxdeg + 1 } [test1, test2] = [ integrate x 0.01 (\ y -> y * y) , integrate x 0.0001 (\ y -> y * y) ] where x :: PI x = newProjection sizeLimits varDoms "x" varDoms = [("x", (0) </\> 1)] sizeLimits = limitsDefault { ipolylimits_maxdeg = 30, ipolylimits_maxsize = 100, ipolylimits_effort = (ipolylimits_effort limitsDefault) { ipolyeff_recipTauDegree = 6 } } where limitsDefault = defaultIntPolySizeLimits sampleCf effortCf arity sampleCf = 0 arity = 1 effortCf = () {- To make the following plotting code work, the file FnView.glade has to be available in the current directory. The master copy of this file is in the root folder of the aern-realfn-plot-gtk package. (https://aern.googlecode.com/hg/aern-realfn-plot-gtk/FnView.glade) -} --{-| Show a plot of exp(x) over [-1,1] -} --plotExp :: IO () --plotExp = -- FV.plotFns -- [("exp example", -- [(("(\\x:[-1,1].x)", FV.black, True), x), -- (("(\\x:[-1,1].exp(x))", FV.green, True), expXDeg 7), -- (("(\\x:[-1,1].exp(x))", FV.blue, True), expXDeg 10) -- ] -- ) -- ]
michalkonecny/aern
aern-poly-plot-gtk/demos/Integrate.hs
bsd-3-clause
4,018
0
12
1,044
650
391
259
59
2
module Doukaku.HukashigiTest (tests) where import Distribution.TestSuite import Doukaku.TestHelper import qualified Doukaku.Hukashigi as Hukashigi tests :: IO [Test] tests = createTests $ newDoukakuTest { tsvPath = "test/Doukaku/hukashigi.tsv" , solve = Hukashigi.solve }
hiratara/doukaku-past-questions-advent-2013
test/Doukaku/HukashigiTest.hs
bsd-3-clause
280
0
8
39
65
40
25
8
1
{-# OPTIONS_GHC -fdefer-typed-holes #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} module Api where import Backend import Control.Lens hiding (Context) import qualified Control.Monad.Catch as Ex import Control.Monad.Except import Data.Aeson (encode) import qualified Data.List as List import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe, maybeToList) import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Database.Persist.Sql import qualified NejlaCommon as NC import Network.Wai import Servant import qualified SignedAuth import Types import Logging hiding (token) import PasswordReset import qualified Persist.Schema as DB import Audit import AuthService.Api import Monad import SignedAuth.Headers (JWS(..)) -------------------------------------------------------------------------------- -- Api ------------------------------------------------------------------------- -------------------------------------------------------------------------------- showText :: Show a => a -> Text showText = Text.pack . show liftHandler :: IO a -> Handler a liftHandler = Ex.handle (\(e :: NC.PersistError) -> throwError (toError e)) . Handler . lift where toError e = ServerError{ errHTTPCode = NC.responseCode e , errReasonPhrase = "" , errBody = encode e , errHeaders = [] } type StatusApi = "status" :> GetNoContent serveStatus :: Server StatusApi serveStatus = return NoContent -- Will be transformed into X-Token header and token cookie by the nginx serveLogin :: ConnectionPool -> ApiState -> Server LoginAPI serveLogin pool st loginReq = loginHandler where loginHandler = do let conf = apiStateConfig st timeframe = configAttemptsTimeframe conf maxAttempts = fromInteger $ configMaxAttempts conf mbReturnLogin <- liftHandler . runAPI pool st $ login timeframe "" maxAttempts loginReq case mbReturnLogin of Right rl -> return (addHeader (returnLoginToken rl) rl) Left LoginErrorOTPRequired -> throwError ServerError{ errHTTPCode = 499 , errReasonPhrase = "OTP required" , errBody = "{\"error\":\"One time password required\"}" , errHeaders = [("Content-Type", "application/json")] } Left LoginErrorFailed -> throwError err403{ errBody = "{\"error\": \"Credentials not accepted\"}" , errHeaders = [("Content-Type", "application/json")] } Left LoginErrorRatelimit -> throwError err429{ errBody = "{\"error\": \"Too many attempts\"}" , errHeaders = [("Content-Type", "application/json")] } Left LoginErrorTwilioNotConfigured -> throwError err500 err429 = ServerError { errHTTPCode = 429 , errReasonPhrase = "Too Many Requests" , errBody = "" , errHeaders = [] } serveLogout :: ConnectionPool -> ApiState -> Server LogoutAPI serveLogout pool conf tok = logoutHandler >> return NoContent where logoutHandler = liftHandler . runAPI pool conf $ logOut tok serverDisableSessions :: ConnectionPool -> ApiState -> Server DisableSessionsAPI serverDisableSessions pool conf tok = disableSessionsHandler >> return NoContent where disableSessionsHandler = liftHandler . runAPI pool conf $ closeOtherSessions tok serveChangePassword :: ConnectionPool -> ApiState -> Server ChangePasswordAPI serveChangePassword pool conf tok chpass = chPassHandler >> return NoContent where chPassHandler = do mbError <- liftHandler . runAPI pool conf $ changePassword tok chpass case mbError of Right _ -> return () Left ChangePasswordLoginError{} -> throwError err403 Left ChangePasswordHashError{} -> throwError err500 Left ChangePasswordTokenError{} -> throwError err403 Left ChangePasswordUserDoesNotExistError{} -> throwError err403 instance ToHttpApiData (JWS a) where toUrlPiece (JWS bs) = Text.decodeUtf8 bs toHeader (JWS bs) = bs serveCheckToken :: ConnectionPool -> ApiState -> Secrets -> Server CheckTokenAPI serveCheckToken pool st secrets req (Just tok) (Just inst) = checkTokenHandler where checkTokenHandler = do res <- liftHandler . runAPI pool st $ do logDebug $ "Checking token " <> showText tok <> " for instance " <> showText inst mbUser <- checkTokenInstance (fromMaybe "" req) tok inst forM mbUser $ \(usrId, usrEmail, userName) -> do roles' <- getUserRoles usrId return (usrId, usrEmail, userName, roles') case res of Nothing -> throwError err403 Just (usr, userEmail, userName, roles') -> do let authHeader = AuthHeader { authHeaderUserID = usr , authHeaderEmail = userEmail , authHeaderName = userName , authHeaderRoles = roles' } signedAuthHeader <- liftIO $ SignedAuth.encodeHeaders (secrets ^. headerPrivateKey) (st ^. noncePool) authHeader return . addHeader signedAuthHeader $ ReturnUser { returnUserUser = usr , returnUserRoles = roles' } serveCheckToken _ _ _ _ _ _ = throwError err400 servePublicCheckToken :: ConnectionPool -> ApiState -> Server PublicCheckTokenAPI servePublicCheckToken pool conf tok = checkTokenHandler where checkTokenHandler = do res <- liftHandler . runAPI pool conf $ do logDebug $ "Checking token " <> showText tok checkToken tok case res of Nothing -> throwError err403 Just _usr -> return NoContent serveGetUserInstancesAPI :: ConnectionPool -> ApiState -> Server GetUserInstancesAPI serveGetUserInstancesAPI pool conf usr = liftHandler . runAPI pool conf $ getUserInstances usr serveGetUserInfoAPI :: ConnectionPool -> ApiState -> Server GetUserInfoAPI serveGetUserInfoAPI pool conf tok = do mbRUI <- liftHandler . runAPI pool conf $ getUserInfo tok case mbRUI of Nothing -> throwError err403 Just rui -> return rui -------------------------------------------------------------------------------- -- Admin interface -------------------------------------------------------------------------------- isAdmin :: Text -> ConnectionPool -> ApiState -> Maybe B64Token -> Handler IsAdmin isAdmin _ _ _ Nothing = throwError err403 isAdmin request pool conf (Just token) = liftHandler (runAPI pool conf $ checkAdmin request token) >>= \case Nothing -> throwError err403 Just isAdmin -> return isAdmin serveCreateUserAPI :: ConnectionPool -> ApiState -> Maybe B64Token -> Server CreateUserAPI serveCreateUserAPI pool conf tok addUser = do _ <- isAdmin desc pool conf tok res <- liftHandler . runAPI pool conf $ do createUser addUser case res of Nothing -> throwError err500 Just uid -> return $ ReturnUser{ returnUserUser = uid , returnUserRoles = addUser ^. roles } where desc = "create user " <> Text.pack (show addUser) serveGetUsersAPI :: ConnectionPool -> ApiState -> Maybe B64Token -> Server GetAllUsersAPI serveGetUsersAPI pool conf tok = do _ <- isAdmin desc pool conf tok liftHandler $ runAPI pool conf getUsers where desc = "get users" serveGetUsersByRoles :: ConnectionPool -> ApiState -> Maybe B64Token -> Server GetUsersByRolesAPI serveGetUsersByRoles pool conf tok role = do isAdmin "get users by role" pool conf tok liftHandler $ runAPI pool conf $ getUsersByRole role serveDeactivateUsersAPI :: ConnectionPool -> ApiState -> Maybe B64Token -> Server DeactivateUserAPI serveDeactivateUsersAPI pool conf tok uid body = do _ <- isAdmin desc pool conf tok liftHandler $ runAPI pool conf $ deactivateUser uid (body ^. deactivateAt) -- @TODO audit return NoContent where desc = "deactivateUser " <> Text.pack (show uid) <> " " <> Text.pack (show body) serveReactivateUsersAPI :: ConnectionPool -> ApiState -> Maybe B64Token -> Server ReactivateUserAPI serveReactivateUsersAPI pool conf tok uid = do _ <- isAdmin desc pool conf tok liftHandler $ runAPI pool conf $ reactivateUser uid return NoContent where desc = "reactivateUser" <> Text.pack (show uid) adminAPIPrx :: Proxy AdminAPI adminAPIPrx = Proxy serveAdminAPI :: ConnectionPool -> ApiState -> Server AdminAPI serveAdminAPI pool conf tok = serveCreateUserAPI pool conf tok :<|> serveGetUsersAPI pool conf tok :<|> serveGetUsersByRoles pool conf tok :<|> serveDeactivateUsersAPI pool conf tok :<|> serveReactivateUsersAPI pool conf tok -------------------------------------------------------------------------------- -- Interface -------------------------------------------------------------------------------- apiPrx :: Proxy (StatusApi :<|> Api) apiPrx = Proxy serveRequestPasswordResetAPI :: ConnectionPool -> ApiState -> Server RequestPasswordResetAPI serveRequestPasswordResetAPI pool conf req = case conf ^. config . email of Nothing -> do liftHandler . runAPI pool conf $ logError "Password reset: email not configured" throwError err404 Just _emailCfg -> do res <- Ex.try . liftHandler . runAPI pool conf $ passwordResetRequest (req ^. email) case res of Left EmailErrorNotConfigured -> throwError err400 Left EmailRenderError -> throwError err500 Left EmailAddressUnknownError -> throwError err403 Right False -> throwError err500 Right True -> return NoContent servePasswordResetAPI :: ConnectionPool -> ApiState -> Server PasswordResetAPI servePasswordResetAPI pool conf pwReset = do mbError <- liftHandler . runAPI pool conf $ resetPassword (pwReset ^. token) (pwReset ^. newPassword) (pwReset ^. Types.otp) case mbError of Left (ChangePasswordLoginError LoginErrorOTPRequired) -> throwError err403 Left _ -> throwError err403 Right () -> return NoContent servePasswordResetTokenInfo :: ConnectionPool -> ApiState -> Server PasswordResetInfoAPI servePasswordResetTokenInfo _pool _conf Nothing = throwError err400 servePasswordResetTokenInfo pool conf (Just token) = do mbInfo <- Ex.try . liftHandler . runAPI pool conf $ getUserByResetPwToken token case mbInfo of Right (Just r) -> return $ ResetTokenInfo (DB.userEmail r) Left ChangePasswordTokenError -> do liftHandler . runAPI pool conf $ logInfo $ "Tried to request token info with invalid Token " <> token throwError err403 _ -> throwError err403 serveCreateAccountApi :: ConnectionPool -> ApiState -> Server CreateAccountAPI serveCreateAccountApi pool conf xinstance createAccount = if accountCreationConfigEnabled . configAccountCreation $ apiStateConfig conf then liftHandler . runAPI pool conf $ do dis <- getConfig (accountCreation . defaultInstances) _ <- createUser AddUser { addUserUuid = Nothing , addUserEmail = createAccountEmail createAccount , addUserPassword = createAccountPassword createAccount , addUserName = createAccountName createAccount , addUserPhone = createAccountPhone createAccount , addUserInstances = List.nub $ maybeToList xinstance ++ dis , addUserRoles = [] } return NoContent else throwError err403 -------------------------------------------------------------------------------- -- Micro Service Interface ----------------------------------------------------- -------------------------------------------------------------------------------- serveGetUsers :: ConnectionPool -> ApiState -> (forall a. Handler a -> Handler a ) -> Server GetUsers serveGetUsers pool conf check uids = check $ do users <- liftHandler . runAPI pool conf $ getUsersByUuids uids let uMap = Map.fromList [(returnUserInfoId user, user) | user <- users] return [ FoundUserInfo { foundUserInfoId = uid , foundUserInfoInfo = Map.lookup uid uMap } | uid <- uids ] -------------------------------------------------------------------------------- -- Interface ------------------------------------------------------------------- -------------------------------------------------------------------------------- serveServiceAPI :: (HasServiceToken s Text) => ConnectionPool -> ApiState -> s -> Server ServiceAPI serveServiceAPI pool conf secrets token = do serveGetUsers pool conf checkServiceApi where checkServiceApi :: forall a. Handler a -> Handler a checkServiceApi f = if token == Just (secrets ^. serviceToken) then f else throwError err403 serveAPI :: ConnectionPool -> SignedAuth.NoncePool -> Config -> Secrets -> Application serveAPI pool noncePool conf secrets = Audit.withAuditHttp $ \auditHttp -> let ctx = ApiState { apiStateConfig = conf , apiStateAuditSource = auditHttp , apiStateNoncePool = noncePool } in serve apiPrx $ serveStatus :<|> serveLogin pool ctx :<|> serveCheckToken pool ctx secrets :<|> servePublicCheckToken pool ctx :<|> serveLogout pool ctx :<|> serverDisableSessions pool ctx :<|> serveChangePassword pool ctx :<|> serveGetUserInstancesAPI pool ctx :<|> serveGetUserInfoAPI pool ctx :<|> serveAdminAPI pool ctx :<|> serveRequestPasswordResetAPI pool ctx :<|> servePasswordResetAPI pool ctx :<|> servePasswordResetTokenInfo pool ctx :<|> serveCreateAccountApi pool ctx :<|> serveServiceAPI pool ctx secrets
nejla/auth-service
service/src/Api.hs
bsd-3-clause
15,654
0
26
4,816
3,393
1,697
1,696
-1
-1
---------------------------------------------------------------- -- Модуль приложения -- Графический интерфейс (UI) -- Виджет ГИП ---------------------------------------------------------------- module WebUI.Widgets.UIWidget ( UI (..) , AdaptableUI , UIColor (..) , UIPosition (..) , UIImage (..) , WidgetUI (..) , StructureTypeUI (..) , ElementUI (..) -- , MonadUI (..) , CArgumentableWidget , pack , (<#>) , (<~>) , (##) , liftUI , unsafePerformUI , packWidgetUI , expandWUI , makeBaseSTypeUI, makeAggregativeSTypeUI , generateUUID, generateUUID_ , toAttrVal , generateValueUUID , createWidgetUI , requare , absolute, fixed, relative, static, inherit , block, inline, inline_block, inline_table, list_item, none, run_in, tableD, table_caption, table_cell , table_column_group, table_column, table_footer_group, table_header_group, table_row, table_row_group , flexD , cursorAuto, cursorCrosshair, cursorDefault, cursorEResize, cursorHelp, cursorMove, cursorNResize, cursorNEResize, cursorNWResize , cursorPointer, cursorProgress, cursorSResize, cursorSEResize, cursorSWResize, cursorText, cursorWResize, cursorWait, cursorInherit , cursorImage , overflowAuto , overflowHidden , overflowScroll , overflowVisible , overflowInherit , overflowAutoX, overflowHiddenX, overflowScrollX, overflowVisibleX, overflowInheritX , overflowAutoY, overflowHiddenY, overflowScrollY, overflowVisibleY, overflowInheritY , BGRepeat (..), BGAttachment (..), BGSize (..) , background, backgroundColor, backgroundRepeat, backgroundAttachment, backgroundImage, backgroundSize , BorderStyle (..) , border, border_left, border_right, border_top, border_bottom , borderNone, border_leftNone, border_rightNone, border_topNone, border_bottomNone , borderRadius, borderRadiusNum, borderRadiusStr, borderRadiusExt , UI_StartingPoint (..), HSize (..) , bounds , boundsNum , boundsStr , boundsExt , boundsBRD , boundsBRDNum , boundsBRDStr , boundsBRDExt , margin, marginNum, marginStr, marginExt, marginAll, marginAllNum, marginAllStr, marginAllExt , marginLeft , marginLeftNum , marginLeftStr , marginLeftExt , marginRight , marginRightNum , marginRightStr , marginRightExt , marginTop , marginTopNum , marginTopStr , marginTopExt , marginBottom, marginBottomNum, marginBottomStr, marginBottomExt , padding, paddingNum, paddingStr, paddingExt, paddingAll, paddingAllNum, paddingAllStr, paddingAllExt , paddingLeft , paddingLeftNum , paddingLeftStr , paddingLeftExt , paddingRight , paddingRightNum , paddingRightStr , paddingRightExt , paddingTop , paddingTopNum , paddingTopStr , paddingTopExt , paddingBottom, paddingBottomNum, paddingBottomStr, paddingBottomExt , wwidth , widthNum , widthStr , widthExt , wwidthMin , widthMinNum , widthMinStr , widthMinExt , wwidthMax , widthMaxNum , widthMaxStr , widthMaxExt , wheight , heightNum , heightStr , heightExt , wheightMin, heightMinNum, heightMinStr, heightMinExt , wheightMax, heightMaxNum, heightMaxStr, heightMaxExt , wsize , sizeNum , sizeStr , sizeExt , left , leftNum , leftStr , leftExt , right , rightNum , rightStr , rightExt , top , topNum , topStr , topExt , bottom, bottomNum, bottomStr, bottomExt , foreground , fill , FFamily (..), FSize (..), FontStyle (..), FontWeight (..) , UIFont (..) , ffSerif, ffSansSerif, ffCursive, ffFantasy, ffMonospace , font, fontFamily, fontSize, fontStyle, fontWeight , zIndex , classToWidget , styleToWidget , tooltip , hover, hoverm , addWUI, addWUI_, addWUIs, addWUIs_, addWUIm, addWUImm, addWUIsm, addWUIms, addWUImms , addWUIcf, addWUIcfs , DecoratorUI (..) , forLoopUI , shellUI, shellExtUI , wuiElement, wuiElement_ , wuiHTML, wuiHTML_ , wuiScriptSrc , wuiStyleHref , wuiScriptJS, wuiScriptJSs , wuiScriptTextJS, wuiScriptTextJSs , wuiCSS, wuiCSSs ) where -- Импорт модулей --import Import import Prelude as PRL import Data.Maybe (fromJust) import System.IO import Control.Monad.IO.Class --import Control.Monad (MonadPlus(mzero, mplus), liftM, ap) import qualified Text.Blaze as TB import qualified Text.Blaze.Html5 as H import Text.Blaze.Html5 import qualified Text.Blaze.Html5.Attributes as HA import Text.Blaze.Html5.Attributes import Text.Blaze.Html.Renderer.String (renderHtml) import qualified Text.Blaze.Internal as TBI import System.IO.Unsafe (unsafePerformIO) import System.Process --import System.Exit import Data.UUID as UV import Data.UUID.V1 as UV1 import Data.UUID.V4 as UV4 import Data.UUID.V5 as UV5 import System.Random import Text.Hamlet import Text.Lucius import Text.Cassius import Text.Julius import WebUI.Themes.UITheme import WebUI.Themes.SolarizedUITheme --type WUI a = StateT s m a --type WUI a = StateT SettingsUI IO a --data UI a = UI { unUI :: a } -- deriving Functor --instance Applicative UI where -- pure = UI -- m *> k = m >>= \ _ -> k -- m <* k = m >>= \ _ -> m -- m <*> k = UI $ (unUI m) (unUI k) --instance Monad UI where -- m >> k = m >>= \ _ -> k -- m >>= k = k $ unUI m -- return = UI --data SettingsUI = SettingsUI { uiLocal :: String } --instance MonadIO UI where -- liftIO a = return $ memo $ unsafePerformIO a --bindUI :: UI a -> (a -> UI b) -> UI b --bindUI (UI m) k = UI (\ s -> case m s of (# new_s, a #) -> unUI (k a) new_s) -- | Тип UI type UI = IO -- | Общий класс всех типов адаптированных для работы в UI class AdaptableUI a where isAdapterUI :: a -> Bool --class (Monad m) => MonadUI m where -- -- | Lift a computation from the 'IO' monad. -- liftUI :: UI a -> m a --instance MonadUI UI where -- liftUI = PRL.id liftUI a = liftIO a --unsafePerformUI = unUI unsafePerformUI = unsafePerformIO {-# DEPRECATED unsafePerformUI "This is unsafe! It is not recommended to use this function!" #-} -- | Тип цвета type UIColor = String -- | Тип положения data UIPosition = UILeft | UIRight | UITop | UIBottom | UICenter | UIInherit instance Show UIPosition where show UILeft = "left" show UIRight = "right" show UITop = "top" show UIBottom = "bottom" show UICenter = "center" show UIInherit = "inherit" -- | Давнные изображения data UIImage = ImageEmpty | ImageURL String | ImageBase64 String String instance Show UIImage where show ImageEmpty = ""; show (ImageURL url) = "url('" ++ url ++ "')" show (ImageBase64 t b) = "url('data:image/" ++ t ++ ";base64," ++ b ++ "')" -- | Тип структуры UI data StructureTypeUI = BaseSTypeUI | AggregativeSTypeUI deriving Show -- | Элемент UI data ElementUI = EmptyElementUI | ElementUI H.Html | ContainerUI (H.Html -> H.Html) instance Show ElementUI where show EmptyElementUI = "EmptyElementUI" show (ElementUI a) = "EmptyUI (" ++ (show a) ++ ")" show _ = "ContainerUI (" ++ "H.Html -> H.Html" ++ ")" --show (ContainerUI (a -> b)) = "(" ++ (show a) ++ ")" instance Show (ElementUI -> ElementUI) where show _ = "Builder" -- | Данные виджета UI data WidgetUI = EmptyUI -- ^ Пустой UI | WidgetUI { wui_title :: H.Html -- ^ Заголовок страницы , wui_id :: String -- ^ ID виджета , wui_ui_name :: String -- ^ Наименование комопонента виджета , wui_attr_style :: String -- ^ Атрибут стилей , wui_attr_class :: String -- ^ Атрибут классов , wui_styles :: [H.Html] -- ^ Массив стилей для HEAD раздела страницы , wui_scripts :: [H.Html] -- ^ Массив скриптов для HEAD раздела страницы , wui_contents :: [H.Html] -- ^ Массив содержимого для BODY раздела страницы (глобальный) , wui_children :: [WidgetUI] -- ^ Дочерние виджеты , wui_strTypeUI :: StructureTypeUI -- ^ Тип структуры UI виджета , wui_element :: ElementUI -- ^ Элемент UI виджета , wui_preBuild :: (ElementUI -> ElementUI) -- ^ Предварительный строитель , wui_postBuild :: (ElementUI -> ElementUI) -- ^ Заключительный строитель } deriving Show instance Show H.Html where show = renderHtml instance Show AttributeValue where show _ = "AttributeValue" -- | Значение по умолчанию данных виджета UI defaultWidgetUI :: UI WidgetUI defaultWidgetUI = do uuid <- generateUUID return $ WidgetUI { wui_title = "" -- ^ Заголовок страницы , wui_id = uuid -- ^ ID виджета , wui_ui_name = "shell" -- ^ Наименование компонента виджета , wui_attr_style = "" -- ^ Атрибут стилей , wui_attr_class = "" -- ^ Атрибут классов , wui_styles = [] -- ^ Массив стилей для HEAD раздела страницы , wui_scripts = [] -- ^ Массив скриптов для HEAD раздела страницы , wui_contents = [] -- ^ Массив содержимого для BODY раздела страницы (глобальный) , wui_children = [] -- ^ Дочерние виджеты , wui_strTypeUI = BaseSTypeUI -- ^ Тип структуры UI виджета , wui_element = EmptyElementUI -- ^ Элемент UI виджета , wui_preBuild = (\x -> x) -- ^ Предварительный строитель , wui_postBuild = (\x -> x) -- ^ Заключительный строитель } -- | Создать данные виджета UI createWidgetUI :: ElementUI -> String -> String -> WidgetUI createWidgetUI element uuid ui_name = WidgetUI { wui_title = "" -- ^ Заголовок страницы , wui_id = uuid -- ^ ID виджета , wui_ui_name = ui_name -- ^ Наименование компонента виджета , wui_attr_style = "" -- ^ Атрибут стилей , wui_attr_class = "" -- ^ Атрибут классов , wui_styles = [] -- ^ Массив стилей для HEAD раздела страницы , wui_scripts = [] -- ^ Массив скриптов для HEAD раздела страницы , wui_contents = [] -- ^ Массив содержимого для BODY раздела страницы (глобальный) , wui_children = [] -- ^ Дочерние виджеты , wui_strTypeUI = BaseSTypeUI -- ^ Тип структуры UI виджета , wui_element = element -- ^ Элемент UI виджета , wui_preBuild = (\x -> x) -- ^ Предварительный строитель , wui_postBuild = (\x -> x) -- ^ Заключительный строитель } -- | Сделать структурный тип виджета Base makeBaseSTypeUI :: WidgetUI -> UI WidgetUI makeBaseSTypeUI widget = do return $ widget {wui_strTypeUI = BaseSTypeUI} -- | Сделать структурный тип виджета Aggregative makeAggregativeSTypeUI :: WidgetUI -> UI WidgetUI makeAggregativeSTypeUI widget = do return $ widget {wui_strTypeUI = AggregativeSTypeUI} -- | Сгенерировать UUID --generateUUID :: UI String --generateUUID = do -- muuid <- UV1.nextUUID -- case muuid of -- Just uuid -> do return $ UV.toString uuid -- Nothing -> do ruuid <- UV4.nextRandom -- return $ UV.toString ruuid --generateUUID :: IO String --generateUUID = UV.toString . fromJust <$> UV1.nextUUID generateUUID :: UI String generateUUID = do ruuid <- UV4.nextRandom -- ruuid <- liftIO $ UV4.nextRandom return $ UV.toString ruuid generateUUID_ = unsafePerformUI generateUUID {-# DEPRECATED generateUUID_ "This is unsafe! It is not recommended to use this function!" #-} -- | Перевести в значение AttributeValue toAttrVal = TB.toValue -- | Сгенерировать UUID как значение AttributeValue generateValueUUID :: AttributeValue generateValueUUID = TB.toValue generateValueUUID -- | Применить виджет к виджету appendUI :: WidgetUI -> WidgetUI -> UI WidgetUI appendUI w_1 w_2 = do return $ w_1 { wui_children = (wui_children w_1) ++ [w_2] } -- | Добавить виджет к виджету addWUI :: WidgetUI -> WidgetUI -> UI WidgetUI addWUI w_1 w_2 = do case (wui_strTypeUI w_1) of BaseSTypeUI -> return $ w_1 { wui_children = (wui_children w_1) ++ [w_2] } AggregativeSTypeUI -> addWUIcf w_1 w_2 addWUI_ w_1 w_2 = unsafePerformUI $ addWUI w_1 w_2 {-# DEPRECATED addWUI_ "This is unsafe! It is not recommended to use this function!" #-} -- | Добавить виджет к виджету (виджет в монаде UI) addWUIm :: WidgetUI -> UI WidgetUI -> UI WidgetUI addWUIm w_1 w_2 = do a2 <- w_2 addWUI w_1 a2 -- | Добавить виджет к виджету (виджеты в монаде UI) addWUImm :: UI WidgetUI -> UI WidgetUI -> UI WidgetUI addWUImm w_1 w_2 = do a1 <- w_1 a2 <- w_2 addWUI a1 a2 -- | Добавить виджеты к виджету addWUIs :: WidgetUI -> [WidgetUI] -> UI WidgetUI addWUIs p [] = do return p addWUIs p (x:xs) = do result <- addWUI p x addWUIs result xs addWUIs_ w_1 w_2 = unsafePerformUI $ addWUIs w_1 w_2 {-# DEPRECATED addWUIs_ "This is unsafe! It is not recommended to use this function!" #-} -- | Добавить виджеты к виджету (виджеты в монаде UI) addWUIsm :: UI WidgetUI -> UI [WidgetUI] -> UI WidgetUI addWUIsm w_1 w_2 = do a1 <- w_1 a2 <- w_2 addWUIs a1 a2 -- | Добавить виджеты к виджету (массив виджетов в монаде UI) addWUIms :: WidgetUI -> [UI WidgetUI] -> UI WidgetUI addWUIms w_1 [] = do return w_1 addWUIms w_1 (x:xs) = do a <- x r <- addWUI w_1 a addWUIms r xs -- | Добавить виджеты к виджету (виджет и массив виджетов в монаде UI) addWUImms :: UI WidgetUI -> [UI WidgetUI] -> UI WidgetUI addWUImms w_1 ws = do w <- w_1 addWUIms w ws -- | Добавить виджет к первому дочерниму виджету виджета addWUIcf :: WidgetUI -> WidgetUI -> UI WidgetUI addWUIcf w_1 w_2 = do chl <- return $ wui_children w_1 case chl of [] -> appendUI w_1 w_2 (x:xs) -> do cf <- x `addWUI` w_2 return w_1 { wui_children = [cf] ++ xs } -- | Добавить виджеты к первому дочерниму виджету виджета addWUIcfs :: WidgetUI -> [WidgetUI] -> UI WidgetUI addWUIcfs p [] = do return p addWUIcfs p (x:xs) = do result <- addWUIcf p x addWUIs result xs -- | Тип декоратора UI type DecoratorUI a = WidgetUI -> a -> UI WidgetUI -- | Цикл петли прохода по списку в UI forLoopUI :: WidgetUI -- ^ Родительский виджет -> [a] -- ^ Список -> DecoratorUI a -- ^ Декоратор -> UI WidgetUI -- ^ Результат forLoopUI parent [] _ = do return parent forLoopUI parent (x:xs) action = do parentNext <- action parent x forLoopUI parentNext xs action -- | Класс для реализации заполнения частично примененных атрибутов class CArgumentableWidget a where pack :: a -> UI WidgetUI instance CArgumentableWidget (UI WidgetUI) where pack a = a -- | Класс для реализации заполнения частично примененных атрибутов class CArgumentableAttr a where expressArgumentAttr :: a -> (WidgetUI -> UI WidgetUI) instance CArgumentableAttr (WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a -- | Применить атрибуты через адаптеры функции --(<#>) :: UI WidgetUI -> (WidgetUI -> UI WidgetUI) -> UI WidgetUI --(<#>) w wfn = do {a <- w; wfn a; } (<#>) :: CArgumentableAttr a => UI WidgetUI -> a -> UI WidgetUI (<#>) w wfn = do a <- w (expressArgumentAttr wfn) a infixl 9 <#> (<~>) :: CArgumentableAttr a => WidgetUI -> a -> WidgetUI {-# DEPRECATED (<~>) "This is unsafe! It is not recommended to use this function!" #-} (<~>) w wfn = do unsafePerformUI $ (expressArgumentAttr wfn) w infixl 9 <~> -- | Применить аттрибуты Blaze (##) :: UI WidgetUI -> Attribute -> UI WidgetUI (##) a atr = do w <- a element <- return $ wui_element w case element of ContainerUI f -> do return w { wui_element = ContainerUI (f ! atr) } ElementUI e -> do return w { wui_element = ElementUI (e ! atr) } EmptyElementUI -> do return w --otherwise -> do return w { wui_element = element ! atr } infixl 9 ## -- | Упаковать виджет для представления в Blaze -- с применением атрибутов packWidgetUI :: WidgetUI -> WidgetUI packWidgetUI widget = case (wui_element widget) of ContainerUI f -> widget { wui_element = a_postBuild . ContainerUI $ f ! HA.id a_uuid ! TBI.customAttribute "ui_widget" a_ui_name ! HA.style a_styles ! HA.class_ a_classes } ElementUI e -> widget { wui_element = a_postBuild . ElementUI $ e ! HA.id a_uuid ! TBI.customAttribute "ui_widget" a_ui_name ! HA.style a_styles ! HA.class_ a_classes } EmptyElementUI -> widget where a_uuid = toAttrVal . wui_id $ widget a_ui_name = toAttrVal . wui_ui_name $ widget a_styles = toAttrVal . wui_attr_style $ widget a_classes = toAttrVal . wui_attr_class $ widget a_preBuild = wui_preBuild $ widget a_postBuild = wui_postBuild $ widget -- | Разобрать элемент expandWUI :: UI WidgetUI -> UI (WidgetUI, String, String) expandWUI widget = do w <- widget return (w, (wui_id w), (wui_ui_name w)) -- | Подключение расширения requare :: WidgetUI -> (WidgetUI -> UI WidgetUI) -> UI WidgetUI requare shell extensionDo = do extensionDo shell ----------------------------------------------------------------------------------------------- -- Адаптеры атрибутов ----------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- -- | Способ позиционирования элемента absolute absolute :: WidgetUI -> UI WidgetUI absolute widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "position: absolute;" } -- | Способ позиционирования элемента fixed fixed :: WidgetUI -> UI WidgetUI fixed widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "position: fixed;" } -- | Способ позиционирования элемента relative relative :: WidgetUI -> UI WidgetUI relative widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "position: relative;" } -- | Способ позиционирования элемента static static :: WidgetUI -> UI WidgetUI static widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "position: static;" } -- | Способ позиционирования элемента inherit inherit :: WidgetUI -> UI WidgetUI inherit widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "position: inherit;" } -- | Способ отображения block block :: WidgetUI -> UI WidgetUI block widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: block;" } -- | Способ отображения inline inline :: WidgetUI -> UI WidgetUI inline widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: inline;" } -- | Способ отображения inline_block inline_block :: WidgetUI -> UI WidgetUI inline_block widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: inline-block;" } -- | Способ отображения inline_table inline_table :: WidgetUI -> UI WidgetUI inline_table widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: inline-table;" } -- | Способ отображения list_item list_item :: WidgetUI -> UI WidgetUI list_item widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: list-item;" } -- | Способ отображения none none :: WidgetUI -> UI WidgetUI none widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: none;" } -- | Способ отображения run_in run_in :: WidgetUI -> UI WidgetUI run_in widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: run-in;" } -- | Способ отображения table tableD :: WidgetUI -> UI WidgetUI tableD widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: table;" } -- | Способ отображения table_caption table_caption :: WidgetUI -> UI WidgetUI table_caption widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: table-caption;" } -- | Способ отображения table_cell table_cell :: WidgetUI -> UI WidgetUI table_cell widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: table-cell;" } -- | Способ отображения table_column_group :: WidgetUI -> UI WidgetUI table_column_group widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: table-column-group;" } -- | Способ отображения table_column table_column :: WidgetUI -> UI WidgetUI table_column widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: table-column;" } -- | Способ отображения table_footer_group table_footer_group :: WidgetUI -> UI WidgetUI table_footer_group widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: table-footer-group;" } -- | Способ отображения table_header_group table_header_group :: WidgetUI -> UI WidgetUI table_header_group widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: table-header-group;" } -- | Способ отображения table_row table_row :: WidgetUI -> UI WidgetUI table_row widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: table-row;" } -- | Способ отображения table_row_group table_row_group :: WidgetUI -> UI WidgetUI table_row_group widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: table-row-group;" } -- | Способ отображения flex flexD :: WidgetUI -> UI WidgetUI flexD widget = do return widget { wui_attr_style = (wui_attr_style widget) ++ "display: flex;" } -- | Курсор auto cursorAuto :: WidgetUI -> UI WidgetUI cursorAuto widget = applyStyleToWidget widget "cursor: auto;" -- | Курсор auto cursorCrosshair :: WidgetUI -> UI WidgetUI cursorCrosshair widget = applyStyleToWidget widget "cursor: crosshair;" -- | Курсор default cursorDefault :: WidgetUI -> UI WidgetUI cursorDefault widget = applyStyleToWidget widget "cursor: default;" -- | Курсор e-resize cursorEResize :: WidgetUI -> UI WidgetUI cursorEResize widget = applyStyleToWidget widget "cursor: e-resize;" -- | Курсор help cursorHelp :: WidgetUI -> UI WidgetUI cursorHelp widget = applyStyleToWidget widget "cursor: help;" -- | Курсор move cursorMove :: WidgetUI -> UI WidgetUI cursorMove widget = applyStyleToWidget widget "cursor: move;" -- | Курсор n-resize cursorNResize :: WidgetUI -> UI WidgetUI cursorNResize widget = applyStyleToWidget widget "cursor: n-resize;" -- | Курсор ne-resize cursorNEResize :: WidgetUI -> UI WidgetUI cursorNEResize widget = applyStyleToWidget widget "cursor: ne-resize;" -- | Курсор nw-resize cursorNWResize :: WidgetUI -> UI WidgetUI cursorNWResize widget = applyStyleToWidget widget "cursor: nw-resize;" -- | Курсор pointer cursorPointer :: WidgetUI -> UI WidgetUI cursorPointer widget = applyStyleToWidget widget "cursor: pointer;" -- | Курсор progress cursorProgress :: WidgetUI -> UI WidgetUI cursorProgress widget = applyStyleToWidget widget "cursor: progress;" -- | Курсор s-resize cursorSResize :: WidgetUI -> UI WidgetUI cursorSResize widget = applyStyleToWidget widget "cursor: s-resize;" -- | Курсор se-resize cursorSEResize :: WidgetUI -> UI WidgetUI cursorSEResize widget = applyStyleToWidget widget "cursor: se-resize;" -- | Курсор sw-resize cursorSWResize :: WidgetUI -> UI WidgetUI cursorSWResize widget = applyStyleToWidget widget "cursor: sw-resize;" -- | Курсор text cursorText :: WidgetUI -> UI WidgetUI cursorText widget = applyStyleToWidget widget "cursor: text;" -- | Курсор w-resize cursorWResize :: WidgetUI -> UI WidgetUI cursorWResize widget = applyStyleToWidget widget "cursor: w-resize;" -- | Курсор wait cursorWait :: WidgetUI -> UI WidgetUI cursorWait widget = applyStyleToWidget widget "cursor: wait;" -- | Курсор auto cursorInherit :: WidgetUI -> UI WidgetUI cursorInherit widget = applyStyleToWidget widget "cursor: inherit;" -- | Курсор по изображению cursorImage :: UIImage -> WidgetUI -> UI WidgetUI cursorImage image widget = applyStyleToWidget widget ("cursor: " ++ (show image) ++ ";") -- | Отображение содержимого auto overflowAuto :: WidgetUI -> UI WidgetUI overflowAuto widget = applyStyleToWidget widget "overflow: auto;" -- | Отображение содержимого hidden overflowHidden :: WidgetUI -> UI WidgetUI overflowHidden widget = applyStyleToWidget widget "overflow: hidden;" -- | Отображение содержимого scroll overflowScroll :: WidgetUI -> UI WidgetUI overflowScroll widget = applyStyleToWidget widget "overflow: scroll;" -- | Отображение содержимого visible overflowVisible :: WidgetUI -> UI WidgetUI overflowVisible widget = applyStyleToWidget widget "overflow: visible;" -- | Отображение содержимого inherit overflowInherit :: WidgetUI -> UI WidgetUI overflowInherit widget = applyStyleToWidget widget "overflow: inherit;" -- | Отображение содержимого X auto overflowAutoX :: WidgetUI -> UI WidgetUI overflowAutoX widget = applyStyleToWidget widget "overflow-x: auto;" -- | Отображение содержимого X hidden overflowHiddenX :: WidgetUI -> UI WidgetUI overflowHiddenX widget = applyStyleToWidget widget "overflow-x: hidden;" -- | Отображение содержимого X scroll overflowScrollX :: WidgetUI -> UI WidgetUI overflowScrollX widget = applyStyleToWidget widget "overflow-x: scroll;" -- | Отображение содержимого X visible overflowVisibleX :: WidgetUI -> UI WidgetUI overflowVisibleX widget = applyStyleToWidget widget "overflow-x: visible;" -- | Отображение содержимого X inherit overflowInheritX :: WidgetUI -> UI WidgetUI overflowInheritX widget = applyStyleToWidget widget "overflow-x: inherit;" -- | Отображение содержимого Y auto overflowAutoY :: WidgetUI -> UI WidgetUI overflowAutoY widget = applyStyleToWidget widget "overflow-y: auto;" -- | Отображение содержимого Y hidden overflowHiddenY :: WidgetUI -> UI WidgetUI overflowHiddenY widget = applyStyleToWidget widget "overflow-y: hidden;" -- | Отображение содержимого Y scroll overflowScrollY :: WidgetUI -> UI WidgetUI overflowScrollY widget = applyStyleToWidget widget "overflow-y: scroll;" -- | Отображение содержимого Y visible overflowVisibleY :: WidgetUI -> UI WidgetUI overflowVisibleY widget = applyStyleToWidget widget "overflow-y: visible;" -- | Отображение содержимого Y inherit overflowInheritY :: WidgetUI -> UI WidgetUI overflowInheritY widget = applyStyleToWidget widget "overflow-y: inherit;" -- | Данные повторения фона data BGRepeat = BGNoRepeat | BGRepeat | BGRepeatX | BGRepeatY | BGInherit | BGSpace | BGRound instance Show BGRepeat where show BGNoRepeat = "no-repeat" show BGRepeat = "repeat" show BGRepeatX = "repeat-x" show BGRepeatY = "repeat-y" show BGInherit = "inherit" show BGSpace = "space" show BGRound = "round" -- | Данные прокрутки фона data BGAttachment = BGAFixed | BGAScroll | BGAInherit | BGALocal instance Show BGAttachment where show BGAFixed = "fixed" show BGAScroll = "scroll" show BGAInherit = "inherit" show BGALocal = "local" data BGSize = BGSize HSize | BGAuto | BGCover | BGContain instance Show BGSize where show (BGSize s) = show s show BGAuto = "auto" show BGCover = "cover" show BGContain = "contain" -- | Дозаполняем атрибуты для background instance CArgumentableAttr (UIColor -> UIImage -> UIPosition -> BGRepeat -> BGAttachment -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a thC_Or ImageEmpty UIInherit BGNoRepeat BGAFixed instance CArgumentableAttr ( UIImage -> UIPosition -> BGRepeat -> BGAttachment -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a ImageEmpty UIInherit BGNoRepeat BGAFixed instance CArgumentableAttr ( UIPosition -> BGRepeat -> BGAttachment -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a UIInherit BGNoRepeat BGAFixed instance CArgumentableAttr ( BGRepeat -> BGAttachment -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a BGNoRepeat BGAFixed instance CArgumentableAttr ( BGAttachment -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a BGAFixed -- | Фон background :: UIColor -> UIImage -> UIPosition -> BGRepeat -> BGAttachment -> WidgetUI -> UI WidgetUI background color image position repeat attachment widget = do w1 <- backgroundColor color widget w2 <- backgroundImage image w1 w3 <- backgroundPosition position w2 w4 <- backgroundRepeat repeat w3 w5 <- backgroundAttachment attachment w4 return w5 -- | Цвет фона backgroundColor :: UIColor -> WidgetUI -> UI WidgetUI backgroundColor color widget = applyStyleToWidget widget ("background-color: " ++ color ++ ";") -- | Положение фона backgroundPosition :: UIPosition -> WidgetUI -> UI WidgetUI backgroundPosition position widget = applyStyleToWidget widget ("background-position: " ++ (show position) ++ ";") -- | Повторение фона backgroundRepeat :: BGRepeat -> WidgetUI -> UI WidgetUI backgroundRepeat repeat widget = applyStyleToWidget widget ("background-repeat: " ++ (show repeat) ++ ";") -- | Прокрутка фона backgroundAttachment :: BGAttachment -> WidgetUI -> UI WidgetUI backgroundAttachment attachment widget = applyStyleToWidget widget ("background-attachment: " ++ (show attachment) ++ ";") -- | Изображение фона по URL backgroundImage :: UIImage -> WidgetUI -> UI WidgetUI backgroundImage image widget = applyStyleToWidget widget ("background-image: " ++ (show image) ++ ";") -- | Масштабирует фоновое изображения backgroundSize :: BGSize -> WidgetUI -> UI WidgetUI backgroundSize bgSize widget = applyStyleToWidget widget ("background-size: " ++ (show bgSize) ++ ";") -- | Данные стиля рамки data BorderStyle = BSNotDefined | BSNone | BSHidden | BSDotted | BSDashed | BSSolid | BSDouble | BSGroove | BSRidge | BSInset | BSOutset | BSInherit instance Show BorderStyle where show BSNotDefined = "" show BSNone = "none" show BSHidden = "hidden" show BSDotted = "dotted" show BSDashed = "dashed" show BSSolid = "solid" show BSDouble = "double" show BSGroove = "groove" show BSRidge = "ridge" show BSInset = "inset" show BSOutset = "outset" show BSInherit = "inherit" -- | Дозаполняем атрибуты для border instance CArgumentableAttr (Int -> BorderStyle -> UIColor -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a 1 BSSolid thC_Or instance CArgumentableAttr ( BorderStyle -> UIColor -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a BSSolid thC_Or instance CArgumentableAttr ( UIColor -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a thC_Or -- | Рамка border border :: Int -> BorderStyle -> UIColor -> WidgetUI -> UI WidgetUI border = applyBorderToWidget "border" -- | Рамка border-left border_left :: Int -> BorderStyle -> UIColor -> WidgetUI -> UI WidgetUI border_left = applyBorderToWidget "border-left" -- | Рамка border-right border_right :: Int -> BorderStyle -> UIColor -> WidgetUI -> UI WidgetUI border_right = applyBorderToWidget "border-right" -- | Рамка border-top border_top :: Int -> BorderStyle -> UIColor -> WidgetUI -> UI WidgetUI border_top = applyBorderToWidget "border-top" -- | Рамка border-bottom border_bottom :: Int -> BorderStyle -> UIColor -> WidgetUI -> UI WidgetUI border_bottom = applyBorderToWidget "border-bottom" -- | Вспомогательный метод для применения рамки к элементу applyBorderToWidget :: String -> Int -> BorderStyle -> UIColor -> WidgetUI -> UI WidgetUI applyBorderToWidget preffix width borderStyle color widget = applyStyleToWidget widget (preffix ++ ": " ++ (show width) ++ "px " ++ (show borderStyle) ++ " " ++ color ++ ";") -- | Рамка borderNone borderNone :: WidgetUI -> UI WidgetUI borderNone = applyBorderNoneToWidget "border" -- | Рамка border-leftNone border_leftNone :: WidgetUI -> UI WidgetUI border_leftNone = applyBorderNoneToWidget "border-left" -- | Рамка border-rightNone border_rightNone :: WidgetUI -> UI WidgetUI border_rightNone = applyBorderNoneToWidget "border-right" -- | Рамка border-topNone border_topNone :: WidgetUI -> UI WidgetUI border_topNone = applyBorderNoneToWidget "border-top" -- | Рамка border-bottomNone border_bottomNone :: WidgetUI -> UI WidgetUI border_bottomNone = applyBorderNoneToWidget "border-bottom" -- | Вспомогательный метод для применения рамки None к элементу applyBorderNoneToWidget :: String -> WidgetUI -> UI WidgetUI applyBorderNoneToWidget preffix widget = applyStyleToWidget widget (preffix ++ ": " ++ (show 0) ++ "px " ++ (show BSNone) ++ ";") -- | Радиус рамки borderRadius :: CSizeable a => (a, a, a, a) -> WidgetUI -> UI WidgetUI borderRadius (r1, r2, r3, r4) widget = applyStyleToWidget widget ("border-radius:" ++ (showSize r1) ++ " " ++ (showSize r2) ++ " " ++ (showSize r3) ++ " " ++ (showSize r4) ++ ";") -- | Радиус рамки (Num) borderRadiusNum :: (Int, Int, Int, Int) -> WidgetUI -> UI WidgetUI borderRadiusNum (r1, r2, r3, r4) widget = applyStyleToWidget widget ("border-radius:" ++ (show r1) ++ "px " ++ (show r2) ++ "px " ++ (show r3) ++ "px " ++ (show r4) ++ "px;") -- | Радиус рамки (Str) borderRadiusStr :: (String, String, String, String) -> WidgetUI -> UI WidgetUI borderRadiusStr (r1, r2, r3, r4) widget = applyStyleToWidget widget ("border-radius:" ++ r1 ++ " " ++ r2 ++ " " ++ r3 ++ " " ++ r4 ++ ";") -- | Радиус рамки (Ext) borderRadiusExt ::(HSize, HSize, HSize, HSize) -> WidgetUI -> UI WidgetUI borderRadiusExt (r1, r2, r3, r4) widget = applyStyleToWidget widget ("border-radius:" ++ (showSize r1) ++ " " ++ (showSize r2) ++ " " ++ (showSize r3) ++ " " ++ (showSize r4) ++ ";") -- | Тип точки отчсета для систем координат data UI_StartingPoint = UI_Default | UI_LT | UI_RT | UI_RB | UI_LB | UI_Top | UI_Bottom deriving Show data HSize = HN Int | HP String | HJ Int | HD Double | HL String deriving Show class Show a => CSizeable a where showSize :: a -> String instance CSizeable HSize where showSize (HN a) = (show a) ++ "px" showSize (HP a) = if '%' `elem` a then a else (a ++ "%") showSize (HJ a) = (show a) ++ "%" showSize (HD a) = (show a) ++ "%" showSize (HL a) = a instance CSizeable Int where showSize a = (show a) ++ "px" instance CSizeable String where showSize a = if '%' `elem` a then a else (a ++ "%") {- type USize = forall a . Num a => a t1 :: USize t1 = 10 t2 :: USize t2 = "asasas" instance Num String where x + y = x ++ y x - y = x ++ y x * y = x ++ y negate x = x abs x = x signum x = x fromInteger x = show x instance Data.String.IsString USize where fromString _ = 0 -} -- | Дозаполняем атрибуты для bounds instance CArgumentableAttr ((Int , Int , Int , Int) -> UI_StartingPoint -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a (0 , 0 , 100 , 50 ) UI_LT instance CArgumentableAttr ((String, String, String, String) -> UI_StartingPoint -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a ("0%", "0%", "50%" , "50%") UI_LT instance CArgumentableAttr ((HSize , HSize , HSize , HSize) -> UI_StartingPoint -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a (HN 0, HN 0, HN 100, HN 50) UI_LT --instance (Num b, CSizeable b) => CArgumentableAttr ((b, b, b, b) -> UI_StartingPoint -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a (0, 0, 100, 50) UI_LT instance CArgumentableAttr ( UI_StartingPoint -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a UI_LT -- | Разместить виджет (Ext) bounds :: CSizeable a => (a, a, a, a) -> UI_StartingPoint -> WidgetUI -> UI WidgetUI bounds (x, y, width, height) startingPoint widget = case startingPoint of UI_LT -> applyStyleToWidget widget ("left:" ++ (showSize x) ++ ";top:" ++ (showSize y) ++ ";width:" ++ (showSize width) ++ ";height:" ++ (showSize height) ++ ";") UI_RT -> applyStyleToWidget widget ("right:" ++ (showSize x) ++ ";top:" ++ (showSize y) ++ ";width:" ++ (showSize width) ++ ";height:" ++ (showSize height) ++ ";") UI_RB -> applyStyleToWidget widget ("right:" ++ (showSize x) ++ ";bottom:" ++ (showSize y) ++ ";width:" ++ (showSize width) ++ ";height:" ++ (showSize height) ++ ";") UI_LB -> applyStyleToWidget widget ("left:" ++ (showSize x) ++ ";bottom:" ++ (showSize y) ++ ";width:" ++ (showSize width) ++ ";height:" ++ (showSize height) ++ ";") _ -> applyStyleToWidget widget ("left:" ++ (showSize x) ++ ";top:" ++ (showSize y) ++ ";width:" ++ (showSize width) ++ ";height:" ++ (showSize height) ++ ";") -- | Разместить виджет (Num) boundsNum :: (Int, Int, Int, Int) -> UI_StartingPoint -> WidgetUI -> UI WidgetUI boundsNum (x, y, width, height) startingPoint widget = case startingPoint of UI_LT -> applyStyleToWidget widget ("left:" ++ (show x) ++ "px;top:" ++ (show y) ++ "px;width:" ++ (show width) ++ "px;height:" ++ (show height) ++ "px;") UI_RT -> applyStyleToWidget widget ("right:" ++ (show x) ++ "px;top:" ++ (show y) ++ "px;width:" ++ (show width) ++ "px;height:" ++ (show height) ++ "px;") UI_RB -> applyStyleToWidget widget ("right:" ++ (show x) ++ "px;bottom:" ++ (show y) ++ "px;width:" ++ (show width) ++ "px;height:" ++ (show height) ++ "px;") UI_LB -> applyStyleToWidget widget ("left:" ++ (show x) ++ "px;bottom:" ++ (show y) ++ "px;width:" ++ (show width) ++ "px;height:" ++ (show height) ++ "px;") _ -> applyStyleToWidget widget ("left:" ++ (show x) ++ "px;top:" ++ (show y) ++ "px;width:" ++ (show width) ++ "px;height:" ++ (show height) ++ "px;") -- | Разместить виджет (Str) boundsStr :: (String, String, String, String) -> UI_StartingPoint -> WidgetUI -> UI WidgetUI boundsStr (x, y, width, height) startingPoint widget = case startingPoint of UI_LT -> applyStyleToWidget widget ("left:" ++ x ++ ";top:" ++ y ++ ";width:" ++ width ++ ";height:" ++ height ++ ";") UI_RT -> applyStyleToWidget widget ("right:" ++ x ++ ";top:" ++ y ++ ";width:" ++ width ++ ";height:" ++ height ++ ";") UI_RB -> applyStyleToWidget widget ("right:" ++ x ++ ";bottom:" ++ y ++ ";width:" ++ width ++ ";height:" ++ height ++ ";") UI_LB -> applyStyleToWidget widget ("left:" ++ x ++ ";bottom:" ++ y ++ ";width:" ++ width ++ ";height:" ++ height ++ ";") _ -> applyStyleToWidget widget ("left:" ++ x ++ ";top:" ++ y ++ ";width:" ++ width ++ ";height:" ++ height ++ ";") -- | Разместить виджет (Ext) boundsExt :: (HSize, HSize, HSize, HSize) -> UI_StartingPoint -> WidgetUI -> UI WidgetUI boundsExt (x, y, width, height) startingPoint widget = case startingPoint of UI_LT -> applyStyleToWidget widget ("left:" ++ (showSize x) ++ ";top:" ++ (showSize y) ++ ";width:" ++ (showSize width) ++ ";height:" ++ (showSize height) ++ ";") UI_RT -> applyStyleToWidget widget ("right:" ++ (showSize x) ++ ";top:" ++ (showSize y) ++ ";width:" ++ (showSize width) ++ ";height:" ++ (showSize height) ++ ";") UI_RB -> applyStyleToWidget widget ("right:" ++ (showSize x) ++ ";bottom:" ++ (showSize y) ++ ";width:" ++ (showSize width) ++ ";height:" ++ (showSize height) ++ ";") UI_LB -> applyStyleToWidget widget ("left:" ++ (showSize x) ++ ";bottom:" ++ (showSize y) ++ ";width:" ++ (showSize width) ++ ";height:" ++ (showSize height) ++ ";") _ -> applyStyleToWidget widget ("left:" ++ (showSize x) ++ ";top:" ++ (showSize y) ++ ";width:" ++ (showSize width) ++ ";height:" ++ (showSize height) ++ ";") -- | Разместить виджет по отступам от граней boundsBRD :: CSizeable a => (a, a, a, a) -> WidgetUI -> UI WidgetUI boundsBRD (top, right, bottom, left) widget = applyStyleToWidget widget ("top:" ++ (showSize top) ++ ";right:" ++ (showSize right) ++ ";bottom:" ++ (showSize bottom) ++ ";left:" ++ (showSize left) ++ ";") -- | Разместить виджет по отступам от граней boundsBRDNum :: (Int, Int, Int, Int) -> WidgetUI -> UI WidgetUI boundsBRDNum (top, right, bottom, left) widget = applyStyleToWidget widget ("top:" ++ (show top) ++ "px;right:" ++ (show right) ++ "px;bottom:" ++ (show bottom) ++ "px;left:" ++ (show left) ++ "px;") -- | Разместить виджет по отступам от граней (Str) boundsBRDStr :: (String, String, String, String) -> WidgetUI -> UI WidgetUI boundsBRDStr (top, right, bottom, left) widget = applyStyleToWidget widget ("top:" ++ top ++ ";right:" ++ right ++ ";bottom:" ++ bottom ++ ";left:" ++ left ++ ";") -- | Разместить виджет по отступам от граней (Ext) boundsBRDExt ::(HSize, HSize, HSize, HSize) -> WidgetUI -> UI WidgetUI boundsBRDExt (top, right, bottom, left) widget = applyStyleToWidget widget ("top:" ++ (showSize top) ++ ";right:" ++ (showSize right) ++ ";bottom:" ++ (showSize bottom) ++ ";left:" ++ (showSize left) ++ ";") -- | Ширина wwidth :: CSizeable a => a -> WidgetUI -> UI WidgetUI wwidth val widget = applyStyleToWidget widget ("width:" ++ (showSize val) ++ ";") -- | Ширина (Num) widthNum :: Int -> WidgetUI -> UI WidgetUI widthNum val widget = applyStyleToWidget widget ("width:" ++ (show val) ++ "px;") -- | Ширина (Str) widthStr :: String -> WidgetUI -> UI WidgetUI widthStr val widget = applyStyleToWidget widget ("width:" ++ val ++ ";") -- | Ширина (Ext) widthExt :: HSize -> WidgetUI -> UI WidgetUI widthExt val widget = applyStyleToWidget widget ("width:" ++ (showSize val) ++ ";") -- | Ширина Min wwidthMin :: CSizeable a => a -> WidgetUI -> UI WidgetUI wwidthMin val widget = applyStyleToWidget widget ("min-width:" ++ (showSize val) ++ ";") -- | Ширина Min (Num) widthMinNum :: Int -> WidgetUI -> UI WidgetUI widthMinNum val widget = applyStyleToWidget widget ("min-width:" ++ (show val) ++ "px;") -- | Ширина Min (Str) widthMinStr :: String -> WidgetUI -> UI WidgetUI widthMinStr val widget = applyStyleToWidget widget ("min-width:" ++ val ++ ";") -- | Ширина Min (Ext) widthMinExt :: HSize -> WidgetUI -> UI WidgetUI widthMinExt val widget = applyStyleToWidget widget ("min-width:" ++ (showSize val) ++ ";") -- | Ширина Max wwidthMax :: CSizeable a => a -> WidgetUI -> UI WidgetUI wwidthMax val widget = applyStyleToWidget widget ("max-width:" ++ (showSize val) ++ ";") -- | Ширина Max (Num) widthMaxNum :: Int -> WidgetUI -> UI WidgetUI widthMaxNum val widget = applyStyleToWidget widget ("max-width:" ++ (show val) ++ "px;") -- | Ширина Max (Str) widthMaxStr :: String -> WidgetUI -> UI WidgetUI widthMaxStr val widget = applyStyleToWidget widget ("max-width:" ++ val ++ ";") -- | Ширина Max (Ext) widthMaxExt :: HSize -> WidgetUI -> UI WidgetUI widthMaxExt val widget = applyStyleToWidget widget ("max-width:" ++ (showSize val) ++ ";") -- | Высота wheight :: CSizeable a => a -> WidgetUI -> UI WidgetUI wheight val widget = applyStyleToWidget widget ("height:" ++ (showSize val) ++ ";") -- | Высота (Num) heightNum :: Int -> WidgetUI -> UI WidgetUI heightNum val widget = applyStyleToWidget widget ("height:" ++ (show val) ++ "px;") -- | Высота (Str) heightStr :: String -> WidgetUI -> UI WidgetUI heightStr val widget = applyStyleToWidget widget ("height:" ++ val ++ ";") -- | Высота (Ext) heightExt :: HSize -> WidgetUI -> UI WidgetUI heightExt val widget = applyStyleToWidget widget ("height:" ++ (showSize val) ++ ";") -- | Высота Min wheightMin :: CSizeable a => a -> WidgetUI -> UI WidgetUI wheightMin val widget = applyStyleToWidget widget ("min-height:" ++ (showSize val) ++ ";") -- | Высота Min (Num) heightMinNum :: Int -> WidgetUI -> UI WidgetUI heightMinNum val widget = applyStyleToWidget widget ("min-height:" ++ (show val) ++ "px;") -- | Высота Min (Str) heightMinStr :: String -> WidgetUI -> UI WidgetUI heightMinStr val widget = applyStyleToWidget widget ("min-height:" ++ val ++ ";") -- | Высота Min (Ext) heightMinExt :: HSize -> WidgetUI -> UI WidgetUI heightMinExt val widget = applyStyleToWidget widget ("min-height:" ++ (showSize val) ++ ";") -- | Высота Max wheightMax :: CSizeable a => a -> WidgetUI -> UI WidgetUI wheightMax val widget = applyStyleToWidget widget ("max-height:" ++ (showSize val) ++ ";") -- | Высота Max (Num) heightMaxNum :: Int -> WidgetUI -> UI WidgetUI heightMaxNum val widget = applyStyleToWidget widget ("max-height:" ++ (show val) ++ "px;") -- | Высота Max (Str) heightMaxStr :: String -> WidgetUI -> UI WidgetUI heightMaxStr val widget = applyStyleToWidget widget ("max-height:" ++ val ++ ";") -- | Высота Max (Ext) heightMaxExt :: HSize -> WidgetUI -> UI WidgetUI heightMaxExt val widget = applyStyleToWidget widget ("max-height:" ++ (showSize val) ++ ";") -- | Дозаполняем атрибуты для size instance CArgumentableAttr ((Int , Int ) -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a (50 , 50 ) instance CArgumentableAttr ((String, String) -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a ("50%", "50%") instance CArgumentableAttr ((HSize , HSize ) -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a (HN 50, HN 50) -- | Размер виджета wsize :: CSizeable a => (a, a) -> WidgetUI -> UI WidgetUI wsize (width, height) widget = applyStyleToWidget widget ("width:" ++ (showSize width) ++ ";height:" ++ (showSize height) ++ ";") -- | Размер виджета (Num) sizeNum :: (Int, Int) -> WidgetUI -> UI WidgetUI sizeNum (width, height) widget = applyStyleToWidget widget ("width:" ++ (show width) ++ "px;height:" ++ (show height) ++ "px;") -- | Размер виджета (Str) sizeStr :: (String, String) -> WidgetUI -> UI WidgetUI sizeStr (width, height) widget = applyStyleToWidget widget ("width:" ++ width ++ ";height:" ++ height ++ ";") -- | Размер виджета (Ext) sizeExt :: (HSize, HSize) -> WidgetUI -> UI WidgetUI sizeExt (width, height) widget = applyStyleToWidget widget ("width:" ++ (showSize width) ++ ";height:" ++ (showSize height) ++ ";") -- | Дозаполняем атрибуты для margin instance CArgumentableAttr ((Int , Int , Int , Int) -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a (5 , 5 , 5 , 5 ) instance CArgumentableAttr ((String, String, String, String) -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a ("0%", "0%", "0%", "0%") instance CArgumentableAttr ((HSize , HSize , HSize , HSize) -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a (HN 5, HN 5, HN 5, HN 5) -- | Внешние отступы виджета margin :: CSizeable a => (a, a, a, a) -> WidgetUI -> UI WidgetUI margin (l, t, r, b) widget = applyStyleToWidget widget ("margin-left:" ++ (showSize l) ++ ";margin-top:" ++ (showSize t) ++ ";margin-right:" ++ (showSize r) ++ ";margin-bottom:" ++ (showSize b) ++ ";") -- | Внешние отступы виджета (Num) marginNum :: (Int, Int, Int, Int) -> WidgetUI -> UI WidgetUI marginNum (l, t, r, b) widget = applyStyleToWidget widget ("margin-left:" ++ (show l) ++ "px;margin-top:" ++ (show t) ++ "px;margin-right:" ++ (show r) ++ "px;margin-bottom:" ++ (show b) ++ "px;") -- | Внещние отступы виджета (Str) marginStr :: (String, String, String, String) -> WidgetUI -> UI WidgetUI marginStr (l, t, r, b) widget = applyStyleToWidget widget ("margin-left:" ++ l ++ ";margin-top:" ++ t ++ ";margin-right:" ++ r ++ ";margin-bottom:" ++ b ++ ";") -- | Внешние отступы виджета (Ext) marginExt :: (HSize, HSize, HSize, HSize) -> WidgetUI -> UI WidgetUI marginExt (l, t, r, b) widget = applyStyleToWidget widget ("margin-left:" ++ (showSize l) ++ ";margin-top:" ++ (showSize t) ++ ";margin-right:" ++ (showSize r) ++ ";margin-bottom:" ++ (showSize b) ++ ";") -- | Внешние отступы виджета Left marginLeft :: CSizeable a => a -> WidgetUI -> UI WidgetUI marginLeft l widget = applyStyleToWidget widget ("margin-left:" ++ (showSize l) ++ ";") -- | Внешние отступы виджета Left (Num) marginLeftNum :: Int -> WidgetUI -> UI WidgetUI marginLeftNum l widget = applyStyleToWidget widget ("margin-left:" ++ (show l) ++ "px;") -- | Внещние отступы виджета Left (Str) marginLeftStr :: String -> WidgetUI -> UI WidgetUI marginLeftStr l widget = applyStyleToWidget widget ("margin-left:" ++ l ++ ";") -- | Внешние отступы виджета Left (Ext) marginLeftExt :: HSize -> WidgetUI -> UI WidgetUI marginLeftExt l widget = applyStyleToWidget widget ("margin-left:" ++ (showSize l) ++ ";") -- | Внешние отступы виджета Right marginRight :: CSizeable a => a -> WidgetUI -> UI WidgetUI marginRight r widget = applyStyleToWidget widget ("margin-right:" ++ (showSize r) ++ ";") -- | Внешние отступы виджета Right (Num) marginRightNum :: Int -> WidgetUI -> UI WidgetUI marginRightNum r widget = applyStyleToWidget widget ("margin-right:" ++ (show r) ++ "px;") -- | Внещние отступы виджета Right (Str) marginRightStr :: String -> WidgetUI -> UI WidgetUI marginRightStr r widget = applyStyleToWidget widget ("margin-right:" ++ r ++ ";") -- | Внешние отступы виджета Right (Ext) marginRightExt :: HSize -> WidgetUI -> UI WidgetUI marginRightExt r widget = applyStyleToWidget widget ("margin-right:" ++ (showSize r) ++ ";") -- | Внешние отступы виджета Top marginTop :: CSizeable a => a -> WidgetUI -> UI WidgetUI marginTop t widget = applyStyleToWidget widget ("margin-top:" ++ (showSize t) ++ ";") -- | Внешние отступы виджета Top (Num) marginTopNum :: Int -> WidgetUI -> UI WidgetUI marginTopNum t widget = applyStyleToWidget widget ("margin-top:" ++ (show t) ++ "px;") -- | Внещние отступы виджета Top (Str) marginTopStr :: String -> WidgetUI -> UI WidgetUI marginTopStr t widget = applyStyleToWidget widget ("margin-top:" ++ t ++ ";") -- | Внешние отступы виджета Top (Ext) marginTopExt :: HSize -> WidgetUI -> UI WidgetUI marginTopExt t widget = applyStyleToWidget widget ("margin-top:" ++ (showSize t) ++ ";") -- | Внешние отступы виджета Bottom marginBottom :: CSizeable a => a -> WidgetUI -> UI WidgetUI marginBottom b widget = applyStyleToWidget widget ("margin-bottom:" ++ (showSize b) ++ ";") -- | Внешние отступы виджета Bottom (Num) marginBottomNum :: Int -> WidgetUI -> UI WidgetUI marginBottomNum b widget = applyStyleToWidget widget ("margin-bottom:" ++ (show b) ++ "px;") -- | Внещние отступы виджета Top (Str) marginBottomStr :: String -> WidgetUI -> UI WidgetUI marginBottomStr b widget = applyStyleToWidget widget ("margin-bottom:" ++ b ++ ";") -- | Внешние отступы виджета Top (Ext) marginBottomExt :: HSize -> WidgetUI -> UI WidgetUI marginBottomExt b widget = applyStyleToWidget widget ("margin-bottom:" ++ (showSize b) ++ ";") -- | Все внешние отступы виджета marginAll :: CSizeable a => a -> WidgetUI -> UI WidgetUI marginAll val = margin (val, val, val, val) -- | Все внешние отступы виджета (Num) marginAllNum :: Int -> WidgetUI -> UI WidgetUI marginAllNum val = marginNum (val, val, val, val) -- | Все внешние отступы виджета (Str) marginAllStr :: String -> WidgetUI -> UI WidgetUI marginAllStr val = marginStr (val, val, val, val) -- | Все внешние отступы виджета (Ext) marginAllExt :: HSize -> WidgetUI -> UI WidgetUI marginAllExt val = marginExt (val, val, val, val) -- | Внутренние отступы виджета padding :: CSizeable a => (a, a, a, a) -> WidgetUI -> UI WidgetUI padding (l, t, r, b) widget = applyStyleToWidget widget ("padding-left:" ++ (showSize l) ++ ";padding-top:" ++ (showSize t) ++ ";padding-right:" ++ (showSize r) ++ ";padding-bottom:" ++ (showSize b) ++ ";") -- | Внутренние отступы виджета (Num) paddingNum :: (Int, Int, Int, Int) -> WidgetUI -> UI WidgetUI paddingNum (l, t, r, b) widget = applyStyleToWidget widget ("padding-left:" ++ (show l) ++ "px;padding-top:" ++ (show t) ++ "px;padding-right:" ++ (show r) ++ "px;padding-bottom:" ++ (show b) ++ "px;") -- | Внутренние отступы виджета (Str) paddingStr :: (String, String, String, String) -> WidgetUI -> UI WidgetUI paddingStr (l, t, r, b) widget = applyStyleToWidget widget ("padding-left:" ++ l ++ ";padding-top:" ++ t ++ ";padding-right:" ++ r ++ ";padding-bottom:" ++ b ++ ";") -- | Внутренние отступы виджета (Ext) paddingExt :: (HSize, HSize, HSize, HSize) -> WidgetUI -> UI WidgetUI paddingExt (l, t, r, b) widget = applyStyleToWidget widget ("padding-left:" ++ (showSize l) ++ ";padding-top:" ++ (showSize t) ++ ";padding-right:" ++ (showSize r) ++ ";padding-bottom:" ++ (showSize b) ++ ";") -- | Внутренние отступы виджета Left paddingLeft :: CSizeable a => a -> WidgetUI -> UI WidgetUI paddingLeft l widget = applyStyleToWidget widget ("padding-left:" ++ (showSize l) ++ ";") -- | Внутренние отступы виджета Left (Num) paddingLeftNum :: Int -> WidgetUI -> UI WidgetUI paddingLeftNum l widget = applyStyleToWidget widget ("padding-left:" ++ (show l) ++ "px;") -- | Внутренние отступы виджета Left (Str) paddingLeftStr :: String -> WidgetUI -> UI WidgetUI paddingLeftStr l widget = applyStyleToWidget widget ("padding-left:" ++ l ++ ";") -- | Внутренние отступы виджета Left (Ext) paddingLeftExt :: HSize -> WidgetUI -> UI WidgetUI paddingLeftExt l widget = applyStyleToWidget widget ("padding-left:" ++ (showSize l) ++ ";") -- | Внутренние отступы виджета Right paddingRight :: CSizeable a => a -> WidgetUI -> UI WidgetUI paddingRight r widget = applyStyleToWidget widget ("padding-right:" ++ (showSize r) ++ ";") -- | Внутренние отступы виджета Right (Num) paddingRightNum :: Int -> WidgetUI -> UI WidgetUI paddingRightNum r widget = applyStyleToWidget widget ("padding-right:" ++ (show r) ++ "px;") -- | Внутренние отступы виджета Right (Str) paddingRightStr :: String -> WidgetUI -> UI WidgetUI paddingRightStr r widget = applyStyleToWidget widget ("padding-right:" ++ r ++ ";") -- | Внутренние отступы виджета Right (Ext) paddingRightExt :: HSize -> WidgetUI -> UI WidgetUI paddingRightExt r widget = applyStyleToWidget widget ("padding-right:" ++ (showSize r) ++ ";") -- | Внутренние отступы виджета Top paddingTop :: CSizeable a => a -> WidgetUI -> UI WidgetUI paddingTop t widget = applyStyleToWidget widget ("padding-top:" ++ (showSize t) ++ ";") -- | Внутренние отступы виджета Top (Num) paddingTopNum :: Int -> WidgetUI -> UI WidgetUI paddingTopNum t widget = applyStyleToWidget widget ("padding-top:" ++ (show t) ++ "px;") -- | Внутренние отступы виджета Top (Str) paddingTopStr :: String -> WidgetUI -> UI WidgetUI paddingTopStr t widget = applyStyleToWidget widget ("padding-top:" ++ t ++ ";") -- | Внутренние отступы виджета Top (Ext) paddingTopExt :: HSize -> WidgetUI -> UI WidgetUI paddingTopExt t widget = applyStyleToWidget widget ("padding-top:" ++ (showSize t) ++ ";") -- | Внутренние отступы виджета Bottom paddingBottom :: CSizeable a => a -> WidgetUI -> UI WidgetUI paddingBottom b widget = applyStyleToWidget widget ("padding-bottom:" ++ (showSize b) ++ ";") -- | Внутренние отступы виджета Bottom (Num) paddingBottomNum :: Int -> WidgetUI -> UI WidgetUI paddingBottomNum b widget = applyStyleToWidget widget ("padding-bottom:" ++ (show b) ++ "px;") -- | Внутренние отступы виджета Top (Str) paddingBottomStr :: String -> WidgetUI -> UI WidgetUI paddingBottomStr b widget = applyStyleToWidget widget ("padding-bottom:" ++ b ++ ";") -- | Внутренние отступы виджета Top (Ext) paddingBottomExt :: HSize -> WidgetUI -> UI WidgetUI paddingBottomExt b widget = applyStyleToWidget widget ("padding-bottom:" ++ (showSize b) ++ ";") -- | Все внутренние отступы виджета paddingAll :: CSizeable a => a -> WidgetUI -> UI WidgetUI paddingAll val = padding (val, val, val, val) -- | Все внутренние отступы виджета (Num) paddingAllNum :: Int -> WidgetUI -> UI WidgetUI paddingAllNum val = paddingNum (val, val, val, val) -- | Все внутренние отступы виджета (Str) paddingAllStr :: String -> WidgetUI -> UI WidgetUI paddingAllStr val = paddingStr (val, val, val, val) -- | Все внутренние отступы виджета (Ext) paddingAllExt :: HSize -> WidgetUI -> UI WidgetUI paddingAllExt val = paddingExt (val, val, val, val) -- | Дозаполняем атрибуты left --instance CArgumentableAttr ((CSizeable a => a) -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a 0 -- | Отступ слева left :: CSizeable a => a -> WidgetUI -> UI WidgetUI left val widget = applyStyleToWidget widget ("left:" ++ (showSize val) ++ ";") -- | Отступ слева (Num) leftNum :: Int -> WidgetUI -> UI WidgetUI leftNum val widget = applyStyleToWidget widget ("left:" ++ (show val) ++ "px;") -- | Отступ слева (Str) leftStr :: String -> WidgetUI -> UI WidgetUI leftStr val widget = applyStyleToWidget widget ("left:" ++ val ++ ";") -- | Отступ слева (Ext) leftExt :: HSize -> WidgetUI -> UI WidgetUI leftExt val widget = applyStyleToWidget widget ("left:" ++ (showSize val) ++ ";") -- | Отступ справа right :: CSizeable a => a -> WidgetUI -> UI WidgetUI right val widget = applyStyleToWidget widget ("right:" ++ (showSize val) ++ ";") -- | Отступ справа (Num) rightNum :: Int -> WidgetUI -> UI WidgetUI rightNum val widget = applyStyleToWidget widget ("right:" ++ (show val) ++ "px;") -- | Отступ справа (Str) rightStr :: String -> WidgetUI -> UI WidgetUI rightStr val widget = applyStyleToWidget widget ("right:" ++ val ++ ";") -- | Отступ справа (Ext) rightExt :: HSize -> WidgetUI -> UI WidgetUI rightExt val widget = applyStyleToWidget widget ("right:" ++ (showSize val) ++ ";") -- | Отступ сверху top :: CSizeable a => a -> WidgetUI -> UI WidgetUI top val widget = applyStyleToWidget widget ("top:" ++ (showSize val) ++ ";") -- | Отступ сверху (Num) topNum :: Int -> WidgetUI -> UI WidgetUI topNum val widget = applyStyleToWidget widget ("top:" ++ (show val) ++ "px;") -- | Отступ сверху (Str) topStr :: String -> WidgetUI -> UI WidgetUI topStr val widget = applyStyleToWidget widget ("top:" ++ val ++ ";") -- | Отступ сверху (Ext) topExt :: HSize -> WidgetUI -> UI WidgetUI topExt val widget = applyStyleToWidget widget ("top:" ++ (showSize val) ++ ";") -- | Отступ снизу bottom :: CSizeable a => a -> WidgetUI -> UI WidgetUI bottom val widget = applyStyleToWidget widget ("bottom:" ++ (showSize val) ++ ";") -- | Отступ снизу (Num) bottomNum :: Int -> WidgetUI -> UI WidgetUI bottomNum val widget = applyStyleToWidget widget ("bottom:" ++ (show val) ++ "px;") -- | Отступ снизу (Str) bottomStr :: String -> WidgetUI -> UI WidgetUI bottomStr val widget = applyStyleToWidget widget ("bottom:" ++ val ++ ";") -- | Отступ снизу (Ext) bottomExt :: HSize -> WidgetUI -> UI WidgetUI bottomExt val widget = applyStyleToWidget widget ("bottom:" ++ (showSize val) ++ ";") -- | Установка foreground (цвет текста) foreground :: UIColor -> WidgetUI -> UI WidgetUI foreground color widget = applyStyleToWidget widget ("color:" ++ color ++ ";") -- | Установка fill (цвет залтвки SVG) fill :: UIColor -> WidgetUI -> UI WidgetUI fill color widget = applyStyleToWidget widget ("fill:" ++ color ++ ";") -- | Тип семейства шрифта data FFamily = FFM String instance Show FFamily where show (FFM a) = a -- | Тип размера шрифта data FSize = FSizePt Double | FSizeEm Double | FSizeEx Double | HSize deriving Show instance CSizeable FSize where showSize (FSizePt a) = (show a) ++ "pt" showSize (FSizeEm a) = (show a) ++ "em" showSize (FSizeEx a) = (show a) ++ "ex" showSize a = showSize a -- | Тип стиля шрифта data FontStyle = FNormal | FItalic | FOblique | FInherit instance Show FontStyle where show FNormal = "normal" show FItalic = "italic" show FOblique = "oblique" show FInherit = "inherit" -- | Тип насыщенности шрифта data FontWeight = FWBold | FWBolder | FWLighter | FWNormal | FW100 | FW200 | FW300 | FW400 | FW500 | FW600 | FW700 | FW800 | FW900 instance Show FontWeight where show FWBold = "bold" show FWBolder = "bolder" show FWLighter = "lighter" show FWNormal = "normal" show FW100 = "100" show FW200 = "200" show FW300 = "300" show FW400 = "400" show FW500 = "500" show FW600 = "600" show FW700 = "700" show FW800 = "800" show FW900 = "900" -- | Тип шрифта data UIFont = UIFont FFamily FSize FontStyle FontWeight instance Show UIFont where show (UIFont family size style weight) = (show style ) ++ " " ++ (show weight) ++ " " ++ (showSize size ) ++ " " ++ (wrappInSingleQuotes . show $ family) ffSerif = FFM "serif" ffSansSerif = FFM "sans-serif" ffCursive = FFM "cursive" ffFantasy = FFM "fantasy" ffMonospace = FFM "monospace" -- | Дозаполняем атрибуты для font instance CArgumentableAttr (UIFont -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a (UIFont ffSansSerif (FSizeEm 1) FNormal FWNormal) instance CArgumentableAttr (FFamily -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a ffSansSerif instance CArgumentableAttr (FSize -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a (FSizeEm 1) instance CArgumentableAttr (FontStyle -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a FNormal instance CArgumentableAttr (FontWeight -> WidgetUI -> UI WidgetUI) where expressArgumentAttr a = a FWNormal -- | Установить шрифт font :: UIFont -> WidgetUI -> UI WidgetUI font f widget = applyStyleToWidget widget ("font:" ++ (show f) ++ ";") -- | Установить семейства шрифтов fontFamily :: FFamily -> WidgetUI -> UI WidgetUI fontFamily family widget = applyStyleToWidget widget ("font-family:" ++ (show family) ++ ";") -- | Установить семейства шрифтов fontSize :: FSize -> WidgetUI -> UI WidgetUI fontSize size widget = applyStyleToWidget widget ("font-size:" ++ (showSize size) ++ ";") -- | Установить семейства шрифтов fontStyle :: FontStyle -> WidgetUI -> UI WidgetUI fontStyle style widget = applyStyleToWidget widget ("font-style:" ++ (show style) ++ ";") -- | Установить насыщенность шрифтов fontWeight :: FontWeight -> WidgetUI -> UI WidgetUI fontWeight weight widget = applyStyleToWidget widget ("font-weight:" ++ (show weight) ++ ";") -- | Установка ZIndex zIndex :: Int -> WidgetUI -> UI WidgetUI zIndex val widget = applyStyleToWidget widget ("z-index:" ++ (show val) ++ ";") -- | Применить класс к виджету classToWidget :: String -> WidgetUI -> UI WidgetUI classToWidget text widget = applyClassToWidget widget (text ++ " ") -- | Применить стиля к виджету styleToWidget :: String -> WidgetUI -> UI WidgetUI styleToWidget text widget = applyStyleToWidget widget text -- | Всплывающая подсказка tooltip :: String -> WidgetUI -> UI WidgetUI tooltip text widget = do case wui_element widget of EmptyElementUI -> return widget ElementUI a -> return widget { wui_element = ElementUI (a ! HA.title (toAttrVal text)) } ContainerUI b -> return widget { wui_element = ContainerUI (b ! HA.title (toAttrVal text)) } -- | Действие в сценарии hover --hover :: CArgumentableAttr a => (UI WidgetUI -> a -> UI WidgetUI) -> WidgetUI -> UI WidgetUI hover :: WidgetUI -> WidgetUI -> UI WidgetUI hover sample widget = do className <- return $ "hfc_" ++ generateUUID_ return widget { wui_styles = (wui_styles widget) ++ [H.style $ toHtml ("." ++ className ++ ":hover {" ++ (wui_attr_style sample) ++ "}" )] , wui_attr_class = (wui_attr_class widget) ++ " " ++ className } -- | Действие в сценарии hover (в монаде UI) hoverm :: UI WidgetUI -> WidgetUI -> UI WidgetUI hoverm samplem widget = do sample <- samplem className <- return $ "hfc_" ++ generateUUID_ return widget { wui_styles = (wui_styles widget) ++ [H.style $ toHtml ("." ++ className ++ ":hover {" ++ (wui_attr_style sample) ++ "}" )] , wui_attr_class = (wui_attr_class widget) ++ " " ++ className } -- | Обернуть текст в одинарные кавычки wrappInSingleQuotes :: String -> String wrappInSingleQuotes text = "'" ++ text ++ "'" -- | Вспомогательный метод для применения класса к элементу applyClassToWidget :: WidgetUI -> String -> UI WidgetUI applyClassToWidget widget text = do return widget { wui_attr_class = (wui_attr_class widget) ++ " " ++ text } -- | Вспомогательный метод для применения стиля к элементу applyStyleToWidget :: WidgetUI -> String -> UI WidgetUI applyStyleToWidget widget text = do return widget { wui_attr_style = (wui_attr_style widget) ++ text } -- | Подготовка HTML из String --prepareHTML c = TB.string c -- | Подготовка CSS prepareCSS a = toHtml $ renderCssUrl undefined a -- | Подготовка JavaScript prepareJS b = toHtml $ renderJavascriptUrl undefined b ----------------------------------------------------------------------------------------------- -- Виджеты UI ------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- -- | Начало цепочки виджетов shellUI :: H.Html -> UI WidgetUI shellUI title = do widgetThis <- defaultWidgetUI return $ widgetThis { wui_title = title } -- | Начало цепочки виджетов с расширениями shellExtUI :: H.Html -> [(WidgetUI -> UI WidgetUI)] -> UI WidgetUI shellExtUI title exts = do shell <- shellUI title recExt shell exts where recExt :: WidgetUI -> [(WidgetUI -> UI WidgetUI)] -> UI WidgetUI recExt shell [] = do return shell recExt shell (x:xs) = do sh <- requare shell x recExt sh xs -- | Элемент (Element) wuiElement :: UI WidgetUI wuiElement = do uuid <- generateUUID return $ createWidgetUI elem uuid "element" where elem = ContainerUI $ H.div wuiElement_ = unsafePerformUI $ wuiElement {-# DEPRECATED wuiElement_ "This is unsafe! It is not recommended to use this function!" #-} -- | Виджет элемента из HTML wuiHTML :: H.Html -> UI WidgetUI wuiHTML v = do uuid <- generateUUID return $ createWidgetUI elem uuid "wui_html" where elem = ElementUI $ H.span $ do v wuiHTML_ = unsafePerformUI . wuiHTML {-# DEPRECATED wuiHTML_ "This is unsafe! It is not recommended to use this function!" #-} -- | Виджет скриптов Src wuiScriptSrc :: [String] -> UI WidgetUI wuiScriptSrc array = do uuid <- generateUUID widget <- return $ createWidgetUI elem uuid "script_src" recwsrc widget array where elem = EmptyElementUI recwsrc :: WidgetUI -> [String] -> UI WidgetUI recwsrc w [] = do return w recwsrc w (x:xs) = do wd <- return $ w { wui_scripts = (wui_scripts w) ++ [H.script ! src (toAttrVal x) $ ""] } recwsrc wd xs -- | Виджет скриптов Src wuiStyleHref :: [String] -> UI WidgetUI wuiStyleHref array = do uuid <- generateUUID widget <- return $ createWidgetUI elem uuid "style_href" recwstl widget array where elem = EmptyElementUI recwstl :: WidgetUI -> [String] -> UI WidgetUI recwstl w [] = do return w recwstl w (x:xs) = do wd <- return $ w { wui_styles = (wui_styles w) ++ [ H.link ! rel "stylesheet" ! type_ "text/css" ! href (toAttrVal x)] } recwstl wd xs -- | Виджет скрипта JS wuiScriptJS :: JavascriptUrl b -> UI WidgetUI wuiScriptJS js = do uuid <- generateUUID return $ createWidgetUI elem uuid "script" where elem = ElementUI $ H.script ! type_ "text/javascript" $ do prepareJS js -- | Виджет скриптов JS wuiScriptJSs :: [JavascriptUrl b] -> UI WidgetUI wuiScriptJSs jsArray = do uuid <- generateUUID return $ createWidgetUI elem uuid "script" where elem = ElementUI $ H.script ! type_ "text/javascript" $ do mapM_ prepareJS jsArray -- | Виджет скрипта JS wuiScriptTextJS :: String -> UI WidgetUI wuiScriptTextJS tjs = do uuid <- generateUUID return $ createWidgetUI elem uuid "script_text" where elem = ElementUI $ H.script ! type_ "text/javascript" $ toHtml tjs -- | Виджет скриптов JS wuiScriptTextJSs :: [String] -> UI WidgetUI wuiScriptTextJSs tjsArray = do uuid <- generateUUID return $ createWidgetUI elem uuid "script_text" where elem = ElementUI $ H.script ! type_ "text/javascript" $ do mapM_ (toHtml) tjsArray -- | Виджет каскадных таблиц стилей CSS wuiCSS :: CssUrl a -> UI WidgetUI wuiCSS css = do uuid <- generateUUID return $ createWidgetUI elem uuid "css" where elem = ElementUI $ H.style $ do prepareCSS css -- | Виджет каскадных таблиц стилей CSS wuiCSSs :: [CssUrl a] -> UI WidgetUI wuiCSSs cssArray = do uuid <- generateUUID return $ createWidgetUI elem uuid "css" where elem = ElementUI $ H.style $ do mapM_ prepareCSS cssArray
iqsf/HFitUI
src/WebUI/Widgets/UIWidget.hs
bsd-3-clause
78,005
0
19
17,707
18,173
9,588
8,585
1,090
5
module Download ( checkForNewDownloads , doDownload , starredDownloadLink ) where import Control.Monad (forM_, unless) import Control.Monad.IO.Class (liftIO) import Control.Monad.Reader (asks) import qualified Data.List as L import Data.Monoid ((<>)) import qualified Data.ByteString.Lazy.Char8 as BC import Data.Text (Text, pack, unpack) import qualified Data.Text.Lazy as LT import Database.Persist import Network.XmlRpc.Client (remote) import Network.XmlRpc.Internals import Types import Model import DB (runDB, runDB_) import Util (sleep) import Slack (slackA) starredDownloadLink :: Item -> Maybe Text starredDownloadLink item = afValue <$> L.find match fields where fields = concat . map atFields $ itAttachments item match a = afTitle a == "Download" doDownload :: BC.ByteString -> Z () doDownload link = do rurl <- asks rtorrentUrl resp <- liftIO $ remote (unpack rurl) "load_start" (BC.unpack link) :: Z Int slackA "#_robots" "New download" [ ( "Link", pack $ BC.unpack link ) , ( "Response", pack $ show resp ) ] -- TODO: fork? liftIO $ sleep $ Seconds 5 checkForNewDownloads return () -- TODO: this is almost certainly the wrong level of abstraction. See coupling with `remote` call below data RemoteDL = RemoteDL { dlHash :: LT.Text, dlName :: LT.Text, dlComplete :: Bool } deriving Show instance XmlRpcType RemoteDL where toValue _ = error "Not implemented: RemoteDL toValue" fromValue v = do fs <- fromValue v hash <- fromValue $ fs !! 0 name <- fromValue $ fs !! 1 complete <- fromValue $ fs !! 2 let complete' = (complete :: Int) == 1 return RemoteDL { dlHash = LT.pack hash, dlName = LT.pack name, dlComplete = complete' } getType _ = TStruct checkForNewDownloads :: Z () checkForNewDownloads = do rurl <- asks rtorrentUrl resp <- liftIO $ remote (unpack rurl) ("d.multicall"::String) ("main"::String) ("d.hash="::String) ("d.name="::String) ("d.complete="::String) forM_ (resp :: [RemoteDL]) recordAndNotify recordAndNotify :: RemoteDL -> Z () recordAndNotify RemoteDL{..} = do mold <- runDB . getBy . UniqueDownloadHash $ dlHash let new = Download { downloadHash = dlHash, downloadName = dlName, downloadComplete = dlComplete } notice = if dlComplete then "Download complete: " else "Download started: " msg = "*" <> notice <> "*\n```" <> LT.toStrict dlName <> "```" notify = slackA "#downloads" msg [] case mold of Nothing -> do notify runDB_ $ insert new Just (Entity _id old) -> unless (dlComplete == downloadComplete old) $ do notify runDB_ $ replace _id new
jamesdabbs/zorya
src/Download.hs
bsd-3-clause
2,818
0
14
714
856
456
400
-1
-1
{-# LANGUAGE MultiParamTypeClasses, FlexibleContexts, TypeFamilies #-} {-# LANGUAGE ConstraintKinds #-} {-# OPTIONS -Wall #-} module RegisterMachine.Models.CMA8 ( Lang(..), prog, mach, trans ) where import Basic.Types import Basic.MemoryImpl (ListMem, fillMem, Address(..), SingleLoc) import Basic.Features import RegisterMachine.State import RegisterMachine.Operations import RegisterMachine.Machine -- 4.0.8. 1961: Lambek abacus model: atomizing Melzak's model to X+, X- with test -- Original abacus model of Lambek 1962 ----------------------------------------- data Lang i = ADDJM i i | SUBJM i i i | HALT instance Language (Lang i) instance IsHalt (Lang i) where isHaltInstr HALT = True isHaltInstr _ = False trans :: (Ord (HContents c), Zero (HContents c), RWValue (Address v) (Heap c) (HContents c), Incr v, Incr (HContents c), Decr (HContents c), HasQ c, HasHeap c, Q c ~ Address v) => Lang v -> c -> c trans (ADDJM r a) = jjump (A a) . incrMem (A r) trans (SUBJM r a1 a2) = stateful_If (cmp0 (<=) heap (A r)) (jjump (A a2)) (jjump (A a1) . decrMem (A r)) trans HALT = id -------------------------------------------------------------------------- --------------------------specilized examples -------------------------------------------------------------------------- prog :: ListMem (Lang Int) prog = fillMem [ADDJM 0 1, SUBJM 0 1 2, HALT] mach :: RM1 (Lang Int) ListMem (CMAState Int SingleLoc ListMem (Address Int)) mach = RM prog initedCMA (compile trans)
davidzhulijun/TAM
RegisterMachine/Models/CMA8.hs
bsd-3-clause
1,512
0
10
252
499
265
234
27
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-| Module : Stack.Sig.Sign Description : Signing Packages Copyright : (c) FPComplete.com, 2015 License : BSD3 Maintainer : Tim Dysinger <tim@fpcomplete.com> Stability : experimental Portability : POSIX -} module Stack.Sig.Sign (sign, signTarBytes) where import qualified Codec.Archive.Tar as Tar import qualified Codec.Compression.GZip as GZip import Control.Monad (when) import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Trans.Control import qualified Data.ByteString.Lazy as BS import qualified Data.ByteString.Lazy as L import Data.Monoid ((<>)) import qualified Data.Text as T import Data.UUID (toString) import Data.UUID.V4 (nextRandom) import Network.HTTP.Conduit (Response(..), RequestBody(..), Request(..), httpLbs, newManager, tlsManagerSettings) import Network.HTTP.Download import Network.HTTP.Types (status200, methodPut) import Path import Path.IO import Stack.Package import qualified Stack.Sig.GPG as GPG import Stack.Types import qualified System.FilePath as FP -- | Sign a haskell package with the given url of the signature -- service and a path to a tarball. sign :: (MonadBaseControl IO m, MonadIO m, MonadMask m, MonadLogger m, MonadThrow m, MonadReader env m, HasConfig env) => Maybe (Path Abs Dir) -> String -> Path Abs File -> m () sign Nothing _ _ = throwM SigNoProjectRootException sign (Just projectRoot) url filePath = do withStackWorkTempDir projectRoot (\tempDir -> do bytes <- liftIO (fmap GZip.decompress (BS.readFile (toFilePath filePath))) maybePath <- extractCabalFile tempDir (Tar.read bytes) case maybePath of Nothing -> throwM SigInvalidSDistTarBall Just cabalPath -> do pkg <- cabalFilePackageId (tempDir </> cabalPath) signPackage url pkg filePath) where extractCabalFile tempDir (Tar.Next entry entries) = do case Tar.entryContent entry of (Tar.NormalFile lbs _) -> case FP.splitFileName (Tar.entryPath entry) of (folder,file) | length (FP.splitDirectories folder) == 1 && FP.takeExtension file == ".cabal" -> do cabalFile <- parseRelFile file liftIO (BS.writeFile (toFilePath (tempDir </> cabalFile)) lbs) return (Just cabalFile) (_,_) -> extractCabalFile tempDir entries _ -> extractCabalFile tempDir entries extractCabalFile _ _ = return Nothing -- | Sign a haskell package with the given url to the signature -- service, a package tarball path (package tarball name) and a lazy -- bytestring of bytes that represent the tarball bytestream. The -- function will write the bytes to the path in a temp dir and sign -- the tarball with GPG. signTarBytes :: (MonadBaseControl IO m, MonadIO m, MonadMask m, MonadLogger m, MonadThrow m, MonadReader env m, HasConfig env) => Maybe (Path Abs Dir) -> String -> Path Rel File -> L.ByteString -> m () signTarBytes Nothing _ _ _ = throwM SigNoProjectRootException signTarBytes (Just projectRoot) url tarPath bs = withStackWorkTempDir projectRoot (\tempDir -> do let tempTarBall = tempDir </> tarPath liftIO (L.writeFile (toFilePath tempTarBall) bs) sign (Just projectRoot) url tempTarBall) -- | Sign a haskell package given the url to the signature service, a -- @PackageIdentifier@ and a file path to the package on disk. signPackage :: (MonadBaseControl IO m, MonadIO m, MonadMask m, MonadLogger m, MonadThrow m) => String -> PackageIdentifier -> Path Abs File -> m () signPackage url pkg filePath = do $logInfo ("GPG signing " <> T.pack (toFilePath filePath)) sig@(Signature signature) <- GPG.signPackage filePath let (PackageIdentifier n v) = pkg name = show n version = show v verify <- GPG.verifyFile sig filePath fingerprint <- GPG.fullFingerprint verify req <- parseUrl (url <> "/upload/signature/" <> name <> "/" <> version <> "/" <> T.unpack (fingerprintSample fingerprint)) let put = req { method = methodPut , requestBody = RequestBodyBS signature } mgr <- liftIO (newManager tlsManagerSettings) res <- liftIO (httpLbs put mgr) when (responseStatus res /= status200) (throwM (GPGSignException "unable to sign & upload package")) withStackWorkTempDir :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env) => Path Abs Dir -> (Path Abs Dir -> m ()) -> m () withStackWorkTempDir projectRoot f = do uuid <- liftIO nextRandom uuidPath <- parseRelDir (toString uuid) workDir <- getWorkDir let tempDir = projectRoot </> workDir </> $(mkRelDir "tmp") </> uuidPath bracket (ensureDir tempDir) (const (removeDirRecur tempDir)) (const (f tempDir))
narrative/stack
src/Stack/Sig/Sign.hs
bsd-3-clause
5,626
0
24
1,720
1,380
711
669
111
5
{-# LANGUAGE OverloadedStrings #-} module Matching.Server.Views where import Control.Concurrent import Data.ByteString.Lazy (ByteString) import Data.String.Conv import Data.Text (Text) import Matching import Text.Blaze.Html.Renderer.Utf8 import Text.Blaze.Html5 as H import Text.Blaze.Html5.Attributes as A landingPage :: RegexResults -> ByteString landingPage results = renderHtml . H.docTypeHtml $ do H.head $ do H.title "Regular Expressions" H.meta ! A.name "viewport" ! A.content "width=device-width, initial-scale=1" (H.link ! rel "stylesheet") ! href "style/style.css" (H.link ! rel "stylesheet") ! href "style/mobile.css" ! media "screen and (max-device-width: 480px)" ! href "mobile.css" H.body $ do H.label ! A.for "q" $ "Generate random strings which match a regular expression" H.form ! A.method "GET" ! A.action "/" $ do H.input ! A.name "q" ! A.id "q" ! A.autofocus "" ! A.placeholder "[0-9a-f]{32}" H.button "\128269" case results of (RegexResults _) -> resultList _ -> examples H.script ! src "/js/bundle.js" $ "" where toResults :: RegexResults -> [Text] toResults (RegexResults candidates) = fmap toS candidates toResults RegexTimeout = ["Regular expression too complex to calculate"] toResults (RegexParseFailure _) = ["Could not parse regular expression"] examples = H.div ! A.class_ "examples" $ do H.span "e.g.: " H.ul $ do H.li $ H.a ! A.href "/?q=[0-9a-f]{32}" $ "[0-9a-f]{32}" H.li $ H.a ! A.href "/?q=[\128512-\128522]+" $ "[\128512-\128522]+" resultList = H.ul ! A.class_ "results" $ mapM_ (H.li . text) $ toResults results selectMatches :: Int -> ByteString -> IO RegexResults selectMatches n = matches n . toS quitAfter :: Int -> IO () quitAfter n = do threadDelay n return ()
lorcanmcdonald/regexicon
src/Matching/Server/Views.hs
mit
1,917
0
19
451
589
289
300
54
4
{- | Module : $Header$ Description : compute the normal forms of all nodes in development graphs Copyright : (c) Christian Maeder, DFKI GmbH 2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : non-portable(Logic) compute normal forms -} module Proofs.NormalForm ( normalFormLibEnv , normalForm , normalFormRule ) where import Logic.Logic import Logic.Grothendieck import Static.ComputeTheory import Static.GTheory import Static.DgUtils import Static.DevGraph import Static.History import Static.WACocone import Proofs.ComputeColimit import Common.Consistency import Common.Id import Common.LibName import Common.Result import Common.Lib.Graph import Common.Utils (nubOrd) import Data.Graph.Inductive.Graph as Graph import qualified Data.Map as Map import Control.Monad normalFormRule :: DGRule normalFormRule = DGRule "NormalForm" -- | compute normal form for a library and imported libs normalForm :: LibName -> LibEnv -> Result LibEnv normalForm ln le = normalFormLNS (dependentLibs ln le) le -- | compute norm form for all libraries normalFormLibEnv :: LibEnv -> Result LibEnv normalFormLibEnv le = normalFormLNS (getTopsortedLibs le) le normalFormLNS :: [LibName] -> LibEnv -> Result LibEnv normalFormLNS lns libEnv = foldM (\ le ln -> do let dg = lookupDGraph ln le newDg <- normalFormDG le dg return $ Map.insert ln (groupHistory dg normalFormRule newDg) le) libEnv lns normalFormDG :: LibEnv -> DGraph -> Result DGraph normalFormDG libEnv dgraph = foldM (\ dg (node, nodelab) -> if labelHasHiding nodelab then case dgn_nf nodelab of Just _ -> return dg -- already computed Nothing -> if isDGRef nodelab then do {- the normal form of the node is a reference to the normal form of the node it references careful: here not refNf, but a new Node which references refN -} let refLib = dgn_libname nodelab refNode = dgn_node nodelab refGraph' = lookupDGraph refLib libEnv refLabel = labDG refGraph' refNode case dgn_nf refLabel of Nothing -> warning dg (getDGNodeName refLabel ++ " (node " ++ show refNode ++ ") from '" ++ show (getLibId refLib) ++ "' without normal form") nullRange Just refNf -> do let refNodelab = labDG refGraph' refNf -- the label of the normal form ^ nfNode = getNewNodeDG dg -- the new reference node in the old graph ^ refLab = refNodelab { dgn_name = extName "NormalForm" $ dgn_name nodelab , dgn_nf = Just nfNode , dgn_sigma = Just $ ide $ dgn_sign refNodelab , nodeInfo = newRefInfo refLib refNf , dgn_lock = Nothing } newLab = nodelab { dgn_nf = Just nfNode, dgn_sigma = dgn_sigma refLabel } chLab = SetNodeLab nodelab (node, newLab) changes = [InsertNode (nfNode, refLab), chLab] newGraph = changesDGH dgraph changes return newGraph else do let gd = insNode (node, dgn_theory nodelab) empty g0 = Map.fromList [(node, node)] (diagram, g) = computeDiagram dg [node] (gd, g0) fsub = finalSubcateg diagram Result ds res = gWeaklyAmalgamableCocone fsub es = map (\ d -> if isErrorDiag d then d { diagKind = Warning } else d) ds appendDiags es case res of Nothing -> warning dg ("cocone failure for " ++ getDGNodeName nodelab ++ " (node " ++ shows node ")") nullRange Just (sign, mmap) -> do {- we don't know that node is in fsub if it's not, we have to find a tip accessible from node and dgn_sigma = edgeLabel(node, tip); mmap (g Map.! tip) -} morNode <- if node `elem` nodes fsub then let gn = Map.findWithDefault (error "gn") node g phi = Map.findWithDefault (error "mor") gn mmap in return phi else let leaves = filter (\ x -> outdeg fsub x == 0) $ nodes fsub paths = map (\ x -> (x, propagateErrors "normalFormDG" $ dijkstra diagram node x)) $ filter (\ x -> node `elem` subgraph diagram x) leaves in case paths of [] -> fail "node should reach a tip" (xn, xf) : _ -> comp xf $ mmap Map.! xn let nfNode = getNewNodeDG dg -- new node for normal form info = nodeInfo nodelab ConsStatus c cp pr = node_cons_status info nfLabel = newInfoNodeLab (extName "NormalForm" $ dgn_name nodelab) info { node_origin = DGNormalForm node , node_cons_status = mkConsStatus c } sign newLab = nodelab -- the new label for node { dgn_nf = Just nfNode , dgn_sigma = Just morNode , nodeInfo = info { node_cons_status = ConsStatus None cp pr } } -- add the nf to the label of node chLab = SetNodeLab nodelab (node, newLab) -- insert the new node and add edges from the predecessors insNNF = InsertNode (nfNode, nfLabel) makeEdge src tgt m = (src, tgt, globDefLink m DGLinkProof) insStrMor = map (\ (x, f) -> InsertEdge $ makeEdge x nfNode f) $ nubOrd $ map (\ (x, y) -> (g Map.! x, y)) $ (node, morNode) : Map.toList mmap allChanges = insNNF : chLab : insStrMor newDG = changesDGH dg allChanges return $ changeDGH newDG $ SetNodeLab nfLabel (nfNode, nfLabel { globalTheory = computeLabelTheory libEnv newDG (nfNode, nfLabel) }) else return dg) dgraph $ topsortedNodes dgraph -- only change relevant nodes {- | computes the diagram associated to a node N in a development graph, adding common origins for multiple occurences of nodes, whenever needed -} computeDiagram :: DGraph -> [Node] -> (GDiagram, Map.Map Node Node) -> (GDiagram, Map.Map Node Node) -- as described in the paper for now computeDiagram dgraph nodeList (gd, g) = case nodeList of [] -> (gd, g) _ -> let -- defInEdges is list of pairs (n, edges of target g(n)) defInEdges = map (\ n -> (n, filter (\ e@(s, t, _) -> s /= t && liftE (liftOr isGlobalDef isHidingDef) e) $ innDG dgraph $ g Map.! n)) nodeList {- TO DO: no local links, and why edges with s=t are removed add normal form nodes sources of each edge must be added as new nodes -} nodeIds = zip (newNodes (length $ concatMap snd defInEdges) gd) $ concatMap (\ (n, l) -> map (\ x -> (n, x)) l ) defInEdges newLNodes = zip (map fst nodeIds) $ map (\ (s, _, _) -> dgn_theory $ labDG dgraph s) $ concatMap snd defInEdges g0 = Map.fromList $ map (\ (newS, (_newT, (s, _t, _))) -> (newS, s)) nodeIds morphEdge (n1, (n2, (_, _, el))) = if isHidingDef $ dgl_type el then (n2, n1, (x, dgl_morphism el)) else (n1, n2, (x, dgl_morphism el)) where EdgeId x = dgl_id el newLEdges = map morphEdge nodeIds gd' = insEdges newLEdges $ insNodes newLNodes gd g' = Map.union g g0 in computeDiagram dgraph (map fst nodeIds) (gd', g') finalSubcateg :: GDiagram -> GDiagram finalSubcateg graph = let leaves = filter (\ (n, _) -> outdeg graph n == 0) $ labNodes graph in buildGraph graph (map fst leaves) leaves [] $ nodes graph subgraph :: Gr a b -> Node -> [Node] subgraph graph node = let descs nList descList = case nList of [] -> descList _ -> let newDescs = concatMap (pre graph) nList nList' = filter (`notElem` nList) newDescs descList' = nubOrd $ descList ++ newDescs in descs nList' descList' in descs [node] [] buildGraph :: GDiagram -> [Node] -> [LNode G_theory] -> [LEdge (Int, GMorphism)] -> [Node] -> GDiagram buildGraph oGraph leaves nList eList nodeList = case nodeList of [] -> mkGraph nList eList n : nodeList' -> case outdeg oGraph n of 1 -> buildGraph oGraph leaves nList eList nodeList' -- the node is simply removed 0 -> buildGraph oGraph leaves nList eList nodeList' -- the leaves have already been added to nList _ -> let Just l = lab oGraph n nList' = (n, l) : nList accesLeaves = filter (\ x -> n `elem` subgraph oGraph x) leaves eList' = map (\ x -> (n, x, (1 :: Int, propagateErrors "buildGraph" $ dijkstra oGraph n x))) accesLeaves in buildGraph oGraph leaves nList' (eList ++ eList') nodeList' -- branch, must add n to the nList and edges in eList
nevrenato/HetsAlloy
Proofs/NormalForm.hs
gpl-2.0
9,638
52
20
3,462
2,392
1,286
1,106
180
9
{-# 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.OpsWorks.AssignVolume -- 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) -- -- Assigns one of the stack\'s registered Amazon EBS volumes to a specified -- instance. The volume must first be registered with the stack by calling -- RegisterVolume. After you register the volume, you must call -- UpdateVolume to specify a mount point before calling 'AssignVolume'. For -- more information, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/resources.html Resource Management>. -- -- __Required Permissions__: To use this action, an IAM user must have a -- Manage permissions level for the stack, or an attached policy that -- explicitly grants permissions. For more information on user permissions, -- see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>. -- -- /See:/ <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_AssignVolume.html AWS API Reference> for AssignVolume. module Network.AWS.OpsWorks.AssignVolume ( -- * Creating a Request assignVolume , AssignVolume -- * Request Lenses , avInstanceId , avVolumeId -- * Destructuring the Response , assignVolumeResponse , AssignVolumeResponse ) where import Network.AWS.OpsWorks.Types import Network.AWS.OpsWorks.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'assignVolume' smart constructor. data AssignVolume = AssignVolume' { _avInstanceId :: !(Maybe Text) , _avVolumeId :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AssignVolume' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'avInstanceId' -- -- * 'avVolumeId' assignVolume :: Text -- ^ 'avVolumeId' -> AssignVolume assignVolume pVolumeId_ = AssignVolume' { _avInstanceId = Nothing , _avVolumeId = pVolumeId_ } -- | The instance ID. avInstanceId :: Lens' AssignVolume (Maybe Text) avInstanceId = lens _avInstanceId (\ s a -> s{_avInstanceId = a}); -- | The volume ID. avVolumeId :: Lens' AssignVolume Text avVolumeId = lens _avVolumeId (\ s a -> s{_avVolumeId = a}); instance AWSRequest AssignVolume where type Rs AssignVolume = AssignVolumeResponse request = postJSON opsWorks response = receiveNull AssignVolumeResponse' instance ToHeaders AssignVolume where toHeaders = const (mconcat ["X-Amz-Target" =# ("OpsWorks_20130218.AssignVolume" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON AssignVolume where toJSON AssignVolume'{..} = object (catMaybes [("InstanceId" .=) <$> _avInstanceId, Just ("VolumeId" .= _avVolumeId)]) instance ToPath AssignVolume where toPath = const "/" instance ToQuery AssignVolume where toQuery = const mempty -- | /See:/ 'assignVolumeResponse' smart constructor. data AssignVolumeResponse = AssignVolumeResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AssignVolumeResponse' with the minimum fields required to make a request. -- assignVolumeResponse :: AssignVolumeResponse assignVolumeResponse = AssignVolumeResponse'
olorin/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/AssignVolume.hs
mpl-2.0
4,075
0
12
861
492
298
194
68
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.CognitoIdentity.UnlinkDeveloperIdentity -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Unlinks a 'DeveloperUserIdentifier' from an existing identity. Unlinked -- developer users will be considered new identities next time they are seen. -- If, for a given Cognito identity, you remove all federated identities as well -- as the developer user identifier, the Cognito identity becomes inaccessible. -- -- <http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_UnlinkDeveloperIdentity.html> module Network.AWS.CognitoIdentity.UnlinkDeveloperIdentity ( -- * Request UnlinkDeveloperIdentity -- ** Request constructor , unlinkDeveloperIdentity -- ** Request lenses , udiDeveloperProviderName , udiDeveloperUserIdentifier , udiIdentityId , udiIdentityPoolId -- * Response , UnlinkDeveloperIdentityResponse -- ** Response constructor , unlinkDeveloperIdentityResponse ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.CognitoIdentity.Types import qualified GHC.Exts data UnlinkDeveloperIdentity = UnlinkDeveloperIdentity { _udiDeveloperProviderName :: Text , _udiDeveloperUserIdentifier :: Text , _udiIdentityId :: Text , _udiIdentityPoolId :: Text } deriving (Eq, Ord, Read, Show) -- | 'UnlinkDeveloperIdentity' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'udiDeveloperProviderName' @::@ 'Text' -- -- * 'udiDeveloperUserIdentifier' @::@ 'Text' -- -- * 'udiIdentityId' @::@ 'Text' -- -- * 'udiIdentityPoolId' @::@ 'Text' -- unlinkDeveloperIdentity :: Text -- ^ 'udiIdentityId' -> Text -- ^ 'udiIdentityPoolId' -> Text -- ^ 'udiDeveloperProviderName' -> Text -- ^ 'udiDeveloperUserIdentifier' -> UnlinkDeveloperIdentity unlinkDeveloperIdentity p1 p2 p3 p4 = UnlinkDeveloperIdentity { _udiIdentityId = p1 , _udiIdentityPoolId = p2 , _udiDeveloperProviderName = p3 , _udiDeveloperUserIdentifier = p4 } -- | The "domain" by which Cognito will refer to your users. udiDeveloperProviderName :: Lens' UnlinkDeveloperIdentity Text udiDeveloperProviderName = lens _udiDeveloperProviderName (\s a -> s { _udiDeveloperProviderName = a }) -- | A unique ID used by your backend authentication process to identify a user. udiDeveloperUserIdentifier :: Lens' UnlinkDeveloperIdentity Text udiDeveloperUserIdentifier = lens _udiDeveloperUserIdentifier (\s a -> s { _udiDeveloperUserIdentifier = a }) -- | A unique identifier in the format REGION:GUID. udiIdentityId :: Lens' UnlinkDeveloperIdentity Text udiIdentityId = lens _udiIdentityId (\s a -> s { _udiIdentityId = a }) -- | An identity pool ID in the format REGION:GUID. udiIdentityPoolId :: Lens' UnlinkDeveloperIdentity Text udiIdentityPoolId = lens _udiIdentityPoolId (\s a -> s { _udiIdentityPoolId = a }) data UnlinkDeveloperIdentityResponse = UnlinkDeveloperIdentityResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'UnlinkDeveloperIdentityResponse' constructor. unlinkDeveloperIdentityResponse :: UnlinkDeveloperIdentityResponse unlinkDeveloperIdentityResponse = UnlinkDeveloperIdentityResponse instance ToPath UnlinkDeveloperIdentity where toPath = const "/" instance ToQuery UnlinkDeveloperIdentity where toQuery = const mempty instance ToHeaders UnlinkDeveloperIdentity instance ToJSON UnlinkDeveloperIdentity where toJSON UnlinkDeveloperIdentity{..} = object [ "IdentityId" .= _udiIdentityId , "IdentityPoolId" .= _udiIdentityPoolId , "DeveloperProviderName" .= _udiDeveloperProviderName , "DeveloperUserIdentifier" .= _udiDeveloperUserIdentifier ] instance AWSRequest UnlinkDeveloperIdentity where type Sv UnlinkDeveloperIdentity = CognitoIdentity type Rs UnlinkDeveloperIdentity = UnlinkDeveloperIdentityResponse request = post "UnlinkDeveloperIdentity" response = nullResponse UnlinkDeveloperIdentityResponse
kim/amazonka
amazonka-cognito-identity/gen/Network/AWS/CognitoIdentity/UnlinkDeveloperIdentity.hs
mpl-2.0
5,137
0
9
1,089
563
342
221
74
1
module Handler.Privacy where import Import import Widgets.Doc getPrivacyR :: Handler Html getPrivacyR = defaultLayout $ do snowdriftTitle "Privacy Policy" renderDoc "Privacy Policy"
chreekat/snowdrift
Handler/Privacy.hs
agpl-3.0
193
0
8
33
43
22
21
7
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Ambiata.Cli.Incoming ( processDir , scanIncoming , hashOfFile , processFile , hashFileOf , cleanUpArchived , cleanUpHashfiles , prepareDir , visible ) where import Ambiata.Cli.Data import Ambiata.Cli.Files import Control.Exception import Control.Monad.IO.Class (liftIO) import Crypto.Hash.MD5 (hashlazy) import qualified Data.ByteString as Strict import qualified Data.ByteString.Lazy as Lazy import Data.Either import qualified Data.Text as T import qualified Data.Text.IO as TIO import Data.Time.Clock import Data.Time.Clock.POSIX import Foreign.C.Types (CTime (..)) import P import System.Directory (getDirectoryContents, doesFileExist, removeFile) import System.Directory (createDirectoryIfMissing, getModificationTime, renameFile) import System.FilePath import System.IO import System.IO.Error import System.Posix.Files import Text.Printf import X.Control.Monad.Trans.Either -- -- INCOMING FOR HANDLING FILES COMING INTO AMBIATA -- /dropbox, /dropbox/.processing, /dropbox/.hashfiles, /dropbox/archive -- hoistIOError :: Either IOException a -> EitherT AmbiataError IO a hoistIOError = either (left . AmbiataFilesystemError . UnknownFilesystemError) right -- | -- Scan for files that have had no "recent" changes, and move them -- to processing dir if ready. Hashfiles may be created. Tears and laughter. -- processDir :: IncomingDir -> NoChangeAfter -> EitherT AmbiataError IO ([IncomingFile], [ProcessingFile], [BadFileState]) processDir dir age = do (badIncoming, incomingFiles) <- partitionEithers <$> scanIncoming dir (badOld, old) <- partitionEithers <$> scanProcessing dir -- find files left over from previous upload attempts fs <- liftIO $ mapM (flip (processFile dir) age) incomingFiles liftIO $ cleanUpHashfiles dir right $ (incomingFiles, catMaybes fs <> old, badIncoming <> badOld) -- | -- prepare the incoming dir with working directories. -- prepareDir :: IncomingDir -> EitherT AmbiataError IO () prepareDir dir = hoistIOError =<< liftIO (try prepareDir') where prepareDir' = do mkdir $ unDir dir mkdir $ toWorkingPath dir Processing mkdir $ toWorkingPath dir Hashfiles mkdir $ toWorkingPath dir Archive mkdir = createDirectoryIfMissing True -- | -- Look for leftover files in .processing (from crashes during upload, etc.). scanProcessing :: IncomingDir -> EitherT AmbiataError IO [Either BadFileState ProcessingFile] scanProcessing d = do fs <- scanDir wd pure $ (bimap id ProcessingFile) <$> fs where wd = toWorkingPath d Processing -- | -- Look for candidate files in the current directory only. Non recursive. -- Don't change anything. scanIncoming :: IncomingDir -> EitherT AmbiataError IO [Either BadFileState IncomingFile] scanIncoming d = do fs <- scanDir $ unDir d pure $ (second IncomingFile) <$> fs scanDir :: FilePath -> EitherT AmbiataError IO [Either BadFileState Text] scanDir dir = do candidates <- liftIO $ filter ignores <$> (getDirectoryContents $ dir) fs <- mapM checkGoodness candidates right fs where ignores f = case f of ('.':_) -> False "archive" -> False -- Don't generate a warning for archive. (_:_) -> True _ -> False checkGoodness :: FilePath -> EitherT AmbiataError IO (Either BadFileState Text) checkGoodness fp = getFileState (dir </> fp) >>= \case GoodFile -> pure . Right $ T.pack fp BadFile badness -> pure $ Left badness getFileState :: FilePath -> EitherT AmbiataError IO FileState getFileState f = do t <- liftIO $ catch ((Right . typeFromStat) <$> getSymbolicLinkStatus f) handleIOError either (left . AmbiataFilesystemError) right t where typeFromStat :: FileStatus -> FileState typeFromStat st | isRegularFile st = GoodFile | isDirectory st = BadFile (Irregular f) | isSymbolicLink st = BadFile (Irregular f) | isSocket st = BadFile (Irregular f) | isNamedPipe st = BadFile (Irregular f) | isCharacterDevice st = BadFile (Irregular f) | isBlockDevice st = BadFile (Irregular f) | otherwise = BadFile (FileStateUnknown f) handleIOError :: IOError -> IO (Either FilesystemError FileState) handleIOError e | isPermissionError e = pure . Right $ BadFile (StatPermissionDenied f) | isDoesNotExistError e = pure . Right $ BadFile (Disappeared f) -- The above two should cover all the error cases, so catch fire -- if we get here. | otherwise = pure . Left $ UnknownFilesystemError e -- | -- Files that have stable hashes and are old enough. -- these are the files are are ready to go. isFileReady :: IncomingDir -> IncomingFile -> NoChangeAfter -> IO FileReady isFileReady dir f (NoChangeAfter noChangeAfter) = do let hashFile = hashFileOf dir f hashed <- doesFileExist hashFile source <- doesFileExist $ toFilePath dir f if hashed && source then do lastMod <- getModificationTime hashFile if (lastMod < noChangeAfter) then do previous <- recordedHashOfFile dir f latest <- hashOfFile dir f pure $ if hashIsConsistent previous latest then Ready else HashChanged latest else pure HashNotOldEnough else pure NotHashed moveToProcessing :: IncomingDir -> IncomingFile -> IO ProcessingFile moveToProcessing dir f = do ignoreNoFile $ removeFile $ hashFileOf dir f let filename = unIncomingFile f ignoreNoFile $ renameFile (toFilePath dir f) $ (toWorkingPath dir Processing) </> T.unpack filename pure $ ProcessingFile filename updateHashFile :: IncomingDir -> IncomingFile -> LatestHash -> IO () updateHashFile dir f (LatestHash hash) = do TIO.writeFile (hashFileOf dir f) hash processFile :: IncomingDir -> IncomingFile -> NoChangeAfter -> IO (Maybe ProcessingFile) processFile dir f age = isFileReady dir f age >>= \fileState -> case fileState of Ready -> Just <$> moveToProcessing dir f NotHashed -> ignoreNoFile (hashOfFile dir f >>= updateHashFile dir f) >> pure Nothing HashNotOldEnough -> pure Nothing HashChanged h -> Nothing <$ updateHashFile dir f h hashFileOf :: IncomingDir -> IncomingFile -> FilePath hashFileOf dir f = (toWorkingPath dir Hashfiles) </> (T.unpack $ unIncomingFile f) hashIsConsistent :: RecordedHash -> LatestHash -> Bool hashIsConsistent r l = unRecordedHash r == unHash l recordedHashOfFile :: IncomingDir -> IncomingFile -> IO RecordedHash recordedHashOfFile d f = fmap RecordedHash . TIO.readFile $ hashFileOf d f hashOfFile :: IncomingDir -> IncomingFile -> IO LatestHash hashOfFile d f = do bytes <- fmap hashlazy . Lazy.readFile $ toFilePath d f pure $ LatestHash $ T.pack $ Strict.unpack bytes >>= printf "%02x" cleanUpArchived :: IncomingDir -> Retention -> UTCTime -> EitherT AmbiataError IO ([ArchivedFile]) cleanUpArchived inc retention utcNow = do candidates <- (fmap (adir </>) . filter visible) <$> (liftIO $ getDirectoryContents adir) deletes <- filterM deletable candidates mapM_ cleanup deletes pure ((ArchivedFile . T.pack . takeFileName) <$> deletes) where adir = toWorkingPath inc Archive deletable fp = do st <- hoistIOError =<< (liftIO $ try (getFileStatus fp)) pure $ oldEnough (statusChangeTime st) oldEnough (CTime ct) = posixSecondsToUTCTime (fromIntegral ct) < daysAgo utcNow retention cleanup fp = hoistIOError =<< (liftIO $ try (removeLink fp)) visible :: FilePath -> Bool visible ('.':_) = False visible (_:_) = True visible _ = False daysAgo :: UTCTime -> Retention -> UTCTime daysAgo now (Retention d) = addUTCTime epochDays now where epochDays = (- (posixDayLength * (fromIntegral d))) -- | -- could accumulate little hashfiles due to crashes, -- so why not clean them up if they have no content file. cleanUpHashfiles :: IncomingDir -> IO () cleanUpHashfiles dir = do let d = (toWorkingPath dir Hashfiles) hashfiles <- (getDirectoryContents d) >>= filterM (doesFileExist . (</>) d) mapM_ (maybeRemoveHashfile dir) $ (IncomingFile . T.pack) <$> hashfiles maybeRemoveHashfile :: IncomingDir -> IncomingFile -> IO Bool maybeRemoveHashfile dir f = do ifM (doesFileExist $ toFilePath dir f) (pure False) (do ignoreNoFile $ removeFile (hashFileOf dir f) pure True)
ambiata/tatooine-cli
src/Ambiata/Cli/Incoming.hs
apache-2.0
8,974
0
15
2,202
2,445
1,226
1,219
176
5
module Main (main) where import Language.Haskell.HLint (hlint) import System.Exit (exitFailure, exitSuccess) arguments :: [String] arguments = [ "lib" , "src" , "test" ] main :: IO () main = do hints <- hlint arguments if null hints then exitSuccess else exitFailure
thsutton/aeson-diff
test/hlint-check.hs
bsd-2-clause
313
0
8
87
94
54
40
14
2
{-# LANGUAGE Rank2Types, ImpredicativeTypes #-} -- | Program entry point & coordination of compilation process module Main where -- Note: for the time being I converted most of this to explicit exports -- to get a better overview what is where /jens import Language.Java.Paragon.Syntax (CompilationUnit) import Language.Java.Paragon.Parser (compilationUnit, parser, ParseError) import Language.Java.Paragon.Pretty (prettyPrint) import Language.Java.Paragon.NameResolution (resolveNames) import Language.Java.Paragon.TypeCheck (T, typeCheck) import Language.Java.Paragon.Compile (compileTransform) import Language.Java.Paragon.PiGeneration (piTransform) import Language.Java.Paragon.Interaction import Language.Java.Paragon.SourcePos (parSecToSourcePos) import Language.Java.Paragon.Error import Language.Java.Paragon.ErrorTxt (errorTxt, errorTxtOld) import Language.Java.Paragon.ErrorEclipse (errorEclipse) import Language.Java.Paragon.Monad.Base import System.FilePath import System.Directory (createDirectoryIfMissing) import System.Environment (getArgs, getEnv) import System.IO.Error (isDoesNotExistError) import System.Exit import Control.Exception (tryJust) import Control.Monad import Control.Monad.Trans.State () import Text.ParserCombinators.Parsec as PS (errorPos) import Text.ParserCombinators.Parsec.Error (messageString, errorMessages) import System.Console.GetOpt -- | Main method, invokes the compiler main :: IO () main = do (flags, files) <- compilerOpts =<< getArgs -- Parse verbosity flags and set using 'setVerbosity'. mapM_ setVerbosity $ [ k | Verbose k <- flags ] setCheckNull (not $ NoNullCheck `elem` flags) when (Version `elem` flags) -- When the flag Version is set $ normalPrint paracVersionString -- Print the version string (the -- function is defined in -- Interaction.hs -- When the flag help is set or no flags nor files were provided: when (Help `elem` flags || null flags && null files) $ normalPrint $ usageInfo usageHeader options -- When files are specified, try to compile them when (not (null files)) $ -- Case distinction only done to not break test suite: -- It expects explicit fail signaling if length files == 1 then do res <- compile flags (head files) hasErrors <- handleErrors flags [res] if hasErrors then (exitWith $ ExitFailure (-1)) else return () else do res <- multiCompile flags files _ <- handleErrors flags res return () -- | All different flags that can be provided to the Paragon compiler data Flag = Verbose Int | Version | Help | PiPath String | Eclipse | OldSkool | OutputPath String | SourcePath String | NoNullCheck deriving (Show, Eq) -- | Two strings describing the version and the usage of the compiler paracVersionString, usageHeader :: String paracVersionString = "Paragon Compiler version: " ++ versionString usageHeader = "Usage: parac [OPTION...] files..." -- | List of available flags (-v -V -h -p) options :: [OptDescr Flag] options = -- Option and OptArg not defined, but assume they come from -- System.Console.GetOpt [ Option ['v'] ["verbose"] (OptArg (Verbose . maybe 3 read) "n") -- default verbosity is 3 "Control verbosity (n is 0--4, normal verbosity level is 1, -v alone is equivalent to -v3)" , Option ['V'] ["version"] (NoArg Version) "Show version number" , Option ['h','?'] ["help"] (NoArg Help) "Show this help" , Option ['p'] ["pipath"] (ReqArg PiPath "<path>") -- required argument "Path to the root directory for Paragon interface (.pi) files (default is . )" , Option ['e'] ["eclipse"] (NoArg Eclipse) "Report output for eclipse (partly implemented)" , Option [] ["oldskool"] (NoArg OldSkool) "Report error messages in old school style" , Option ['o'] ["output"] (ReqArg OutputPath "<path>") "Output directory for generated .java and .pi files (default is same as source, i.e. -s should be provided)" , Option ['s'] ["source"] (ReqArg SourcePath "<path>") "Source directory for .para files (default is .)" , Option ['n'] ["nonull"] (NoArg NoNullCheck) "Do not check for flows via unchecked nullpointer exceptions" ] -- |Converts the list of arguments to a pair of two lists of equal length. -- The first lists the flags used, the second a list of files -- that need to be compiled compilerOpts :: [String] -- ^ The list of arguments -> IO ([Flag], [String]) -- ^ Pair of flags + file names list compilerOpts argv = -- RequireOrder --> no option processing after first non-option case getOpt RequireOrder options argv of (o,n,[]) -> return (o,n) -- in case of errors: show errors parsing arguments + usage info (_,_,errs) -> ioError (userError (concat errs ++ usageInfo usageHeader options)) ------------------------------------------------------------------------------------- -- | Handles the potential errors generated for each file. -- Returns true iff there was at least one error handleErrors :: [Flag] -> [(String, [Error])] -> IO Bool handleErrors flags errors = do mapM_ (if (OldSkool `elem` flags) then errorTxtOld else if (Eclipse `elem` flags) then errorEclipse else errorTxt) errors -- TODO should be different function for XML ofc. return . not . null $ concat $ map snd errors -- | Collect paths to interface files from options and environment buildPiPath :: [Flag] -> String -> IO [String] buildPiPath flags filePath = do -- Using import System.FilePath, split path into directory and filename let (directoryRaw,_fileName) = splitFileName filePath -- Workaround for old and buggy 'filepath' versions -- Default is in this direcory _directory = if null directoryRaw then "./" else directoryRaw pp <- getPIPATH -- Read the PIPATH environment variable -- Concatenate two lists of directories where to look for pi files: -- ~ the explicitly defined ones with the -p flag -- ~ the ones coming from the environment variables -- If this set is empty, use the current directory. let pDirsSpec = concat [ splitSearchPath dir | PiPath dir <- flags ] ++ pp pDirs = if null pDirsSpec then ["./"] else pDirsSpec debugPrint $ show pDirs return pDirs -- | Compile several files at once, return a list files and the errors -- found in them (if any) multiCompile :: [Flag] -> [String] -> IO [(String, [Error])] multiCompile flags = mapM ( \f -> do normalPrint $ "Compiling " ++ f compile flags f) -- | Actual compiler function compile :: [Flag] -- ^ The flags specified as arguments to the compiler -> String -- ^ Path to the .para file to compile (relative or absolute) -> IO (String, [Error]) -- ^ Name of compiled file and found errors compile flags filePath = do -- Initialization: Set up environment and read file debugPrint $ "Filepath: " ++ filePath pDirs <- buildPiPath flags filePath fc <- readFile filePath -- Compilation res <- runBaseM . withDefaultErrCtxt $ compilationStages pDirs fc return $ (filePath, either id (\_ -> []) res) -- Return possibly empty list of errors where withDefaultErrCtxt = withErrCtxt EmptyContext compilationStages pDirs fc = do -- Converting to abstract syntax tree ast <- liftEitherMB . convertParseToErr $ parser compilationUnit fc raiseErrors detailPrint "Parsing complete!" -- Name resolution ast1 <- resolveNames pDirs ast raiseErrors detailPrint "Name resolution complete!" debugPrint $ prettyPrint ast1 -- Type check ast2 <- typeCheck pDirs (takeBaseName filePath) ast1 raiseErrors detailPrint "Type checking complete!" -- Generate .java and .pi files liftIO $ genFiles flags filePath ast2 detailPrint "File generation complete!" convertParseToErr :: Either ParseError a -> Either Error a convertParseToErr (Left x) = Left $ mkError (ParsingError $ messageString (head $ errorMessages x)) (parSecToSourcePos $ PS.errorPos x) convertParseToErr (Right x) = Right x -- | Converts the environment variable PIPATH to a list of FilePaths getPIPATH :: IO [FilePath] getPIPATH = do -- guard indicates that the only expected exception is isDoesNotExistError -- returns an Either type, left exception, right path ePpStr <- tryJust (guard . isDoesNotExistError) $ getEnv "PIPATH" -- splitSearchPath comes from System.FilePath, splitting String into filepaths -- In case the PIPATH variable did not exist, the empty list is used. -- (either takes two functions, const makes a function ignoring the other -- argument, i.e. the exception is ignored). return $ splitSearchPath $ either (const []) id ePpStr -- | Generate .pi and .java files genFiles :: [Flag] -> FilePath -> CompilationUnit T -> IO () genFiles flags filePath ast = let -- create .java ast astC = compileTransform ast -- create .pi ast astPi = piTransform (fmap (const ()) ast) -- output to right files baseName = takeBaseName filePath directory = takeDirectory filePath outdir = getOutdir flags </> makeRelative (getIndir flags) directory javaPath = outdir </> baseName <.> "java" piPath = outdir </> baseName <.> "pi" java,pifile :: String java = prettyPrint astC pifile = prettyPrint astPi in do createDirectoryIfMissing True outdir writeFile javaPath java >> writeFile piPath pifile where getOutdir [] = "." getOutdir (OutputPath p:_) = p getOutdir (_:xs) = getOutdir xs getIndir [] = "." getIndir (SourcePath p:_) = p getIndir (_:xs) = getIndir xs
bvdelft/parac2
src/Language/Java/Paragon.hs
bsd-3-clause
10,461
0
16
2,763
2,047
1,109
938
150
5
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} -- | Prettyprinting STG elements in various formats. module Stg.Language.Prettyprint ( PrettyStgi(..), StgiAnn(..), StateAnn(..), AstAnn(..), renderRich, renderPlain, ) where import Data.Text (Text) import Data.Text.Prettyprint.Doc import Data.Text.Prettyprint.Doc.Render.Terminal as PrettyAnsi import Data.Text.Prettyprint.Doc.Render.Text as PrettyPlain import Prelude hiding ((<$>)) renderRich :: Doc StgiAnn -> Text renderRich = PrettyAnsi.renderStrict . alterAnnotationsS (Just . terminalStyle) . layoutPretty layoutOptions where terminalStyle :: StgiAnn -> AnsiStyle terminalStyle = \case StateAnn x -> case x of Headline -> colorDull Blue Address -> colorDull Cyan AddressCore -> underlined ClosureType -> bold StackFrameType -> bold AstAnn x -> case x of Keyword -> colorDull White Prim -> colorDull Green Variable -> colorDull Yellow Constructor -> colorDull Magenta Semicolon -> colorDull White renderPlain :: Doc ann -> Text renderPlain = PrettyPlain.renderStrict . layoutPretty layoutOptions layoutOptions :: LayoutOptions layoutOptions = defaultLayoutOptions { layoutPageWidth = Unbounded } class PrettyStgi a where prettyStgi :: a -> Doc StgiAnn data StgiAnn = StateAnn StateAnn | AstAnn AstAnn -- | Semantic annotations for rendering. data StateAnn = Headline -- ^ Style of headlines in the state overview, such as \"Heap" and -- "Frame i". | Address -- ^ Style of memory addresses, including @0x@ prefix. | AddressCore -- ^ Style of memory addresses; applied only to the actual address -- number, such as @ff@ in @0xff@. | ClosureType -- ^ Style of the type of a closure, such as BLACKHOLE or FUN. | StackFrameType -- ^ Style of the stack frame annotation, such as UPD or ARG. -- | The different semantic annotations an STG AST element can have. data AstAnn = Keyword | Prim | Variable | Constructor | Semicolon instance PrettyStgi Bool where prettyStgi = pretty instance PrettyStgi Int where prettyStgi = pretty instance PrettyStgi Integer where prettyStgi = pretty instance (PrettyStgi a, PrettyStgi b) => PrettyStgi (a,b) where prettyStgi (a,b) = tupled [prettyStgi a, prettyStgi b] instance PrettyStgi a => PrettyStgi [a] where prettyStgi = list . map prettyStgi
quchen/stg
src/Stg/Language/Prettyprint.hs
bsd-3-clause
2,755
0
13
799
516
293
223
57
10
import Development.Shake main :: IO () main = shake $ do "a" *> \x -> do need ["b"] "b" *> \x -> do need ["a"] -- Because we "want" the two files simultaneously, they will each get -- built on a different thread. This causes the current (simpleminded) cycle -- detector to not detect a cycle. want ["a", "b"]
beni55/openshake
tests/cyclic-harder/Shakefile.hs
bsd-3-clause
351
0
13
101
82
42
40
8
1
-- {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} {-# LANGUAGE ImplicitParams, RankNTypes #-} -- This program failed to typecheck in an early version of -- GHC with impredicative polymorphism, but it was fixed by -- doing pre-subsumption in the subsumption check. -- Trac bug #821 module ShouldCompile where type PPDoc = (?env :: Int) => Char f :: Char -> PPDoc f = succ
rahulmutt/ghcvm
tests/suite/typecheck/compile/tc208.hs
bsd-3-clause
381
0
6
66
39
27
12
5
1