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
----------------------------------------------------------------------------- -- | -- Module : Network.Transport.Memory -- Copyright : (c) Phil Hargett 2013 -- License : MIT (see LICENSE file) -- -- Maintainer : phil@haphazardhouse.net -- Stability : experimental -- Portability : non-portable (requires STM) -- -- Memory transports deliver messages to other 'Network.Endpoints.Endpoint's within the same shared -- address space, or operating system process. -- Internally memory transports use a set of 'TQueue's to deliver messages to 'Network.Endpoint.Endpoint's. -- Memory transports are not global in nature: 'Network.Endpoint.Endpoint's can only communicate with -- one another if each has added the same memory 'Transport' and each invoked 'bind' on that shared -- transport. -- ----------------------------------------------------------------------------- module Network.Transport.Memory ( newMemoryTransport, module Network.Transport ) where -- local imports import Control.Concurrent.Mailbox import Network.Endpoints import Network.Transport -- external imports import Control.Concurrent.Async import Control.Concurrent.STM import Control.Exception import qualified Data.Map as M -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- {-| Create a new memory 'Transport' for use by 'Network.Endpoint.Endpoint's. -} newMemoryTransport :: IO Transport newMemoryTransport = do vBindings <- atomically $ newTVar M.empty return Transport { bind = memoryBind vBindings, dispatch = memoryDispatcher vBindings, connect = memoryConnect, shutdown = return () } memoryDispatcher :: TBindings -> Endpoint -> IO Dispatcher memoryDispatcher vBindings endpoint = do d <- async disp return Dispatcher { stop = do cancel d memoryFlushMessages vBindings endpoint } where disp = do atomically $ do bindings <- readTVar vBindings env <- selectMailbox (endpointOutbound endpoint) $ \envelope -> case M.lookup (messageDestination envelope) bindings of Just _ -> Just envelope _ -> Nothing memoryDispatchEnvelope bindings env disp memoryDispatchEnvelope :: Bindings -> Envelope -> STM () memoryDispatchEnvelope bindings env = case M.lookup (messageDestination env) bindings of Nothing -> return () Just destination -> postMessage destination (envelopeMessage env) memoryBind :: TBindings -> Endpoint -> Name -> IO Binding memoryBind vBindings endpoint name = atomically $ do bindings <- readTVar vBindings case M.lookup name bindings of Nothing -> do modifyTVar vBindings $ M.insert name endpoint return Binding { bindingName = name, unbind = memoryUnbind vBindings endpoint name } Just _ -> throw $ BindingExists name memoryUnbind :: TBindings -> Endpoint -> Name -> IO () memoryUnbind vBindings _ name = atomically $ modifyTVar vBindings $ M.delete name type TBindings = TVar Bindings type Bindings = M.Map Name Endpoint memoryConnect :: Endpoint -> Name -> IO Connection memoryConnect _ _ = return Connection { disconnect = return () } memoryFlushMessages :: TBindings -> Endpoint -> IO () memoryFlushMessages vBindings endpoint = atomically flush where flush = do bindings <- readTVar vBindings maybeEnv <- tryReadMailbox $ endpointOutbound endpoint case maybeEnv of Just env -> do memoryDispatchEnvelope bindings env flush Nothing -> return ()
hargettp/courier
src/Network/Transport/Memory.hs
mit
3,646
0
18
731
729
368
361
69
2
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.Geolocation (js_getCurrentPosition, getCurrentPosition, js_watchPosition, watchPosition, js_clearWatch, clearWatch, Geolocation, castToGeolocation, gTypeGeolocation) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"getCurrentPosition\"]($2, $3,\n$4)" js_getCurrentPosition :: JSRef Geolocation -> JSRef PositionCallback -> JSRef PositionErrorCallback -> JSRef PositionOptions -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Geolocation.getCurrentPosition Mozilla Geolocation.getCurrentPosition documentation> getCurrentPosition :: (MonadIO m, IsPositionOptions options) => Geolocation -> Maybe PositionCallback -> Maybe PositionErrorCallback -> Maybe options -> m () getCurrentPosition self successCallback errorCallback options = liftIO (js_getCurrentPosition (unGeolocation self) (maybe jsNull pToJSRef successCallback) (maybe jsNull pToJSRef errorCallback) (maybe jsNull (unPositionOptions . toPositionOptions) options)) foreign import javascript unsafe "$1[\"watchPosition\"]($2, $3, $4)" js_watchPosition :: JSRef Geolocation -> JSRef PositionCallback -> JSRef PositionErrorCallback -> JSRef PositionOptions -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/Geolocation.watchPosition Mozilla Geolocation.watchPosition documentation> watchPosition :: (MonadIO m, IsPositionOptions options) => Geolocation -> Maybe PositionCallback -> Maybe PositionErrorCallback -> Maybe options -> m Int watchPosition self successCallback errorCallback options = liftIO (js_watchPosition (unGeolocation self) (maybe jsNull pToJSRef successCallback) (maybe jsNull pToJSRef errorCallback) (maybe jsNull (unPositionOptions . toPositionOptions) options)) foreign import javascript unsafe "$1[\"clearWatch\"]($2)" js_clearWatch :: JSRef Geolocation -> Int -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Geolocation.clearWatch Mozilla Geolocation.clearWatch documentation> clearWatch :: (MonadIO m) => Geolocation -> Int -> m () clearWatch self watchID = liftIO (js_clearWatch (unGeolocation self) watchID)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/Geolocation.hs
mit
3,234
32
11
625
710
408
302
56
1
-- Problems/Problem025Spec.hs module Problems.Problem025Spec (main, spec) where import Test.Hspec import Problems.Problem025 main :: IO() main = hspec spec spec :: Spec spec = describe "Problem 25" $ it "Should evaluate to 4782" $ p25 `shouldBe` 4782
Sgoettschkes/learning
haskell/ProjectEuler/tests/Problems/Problem025Spec.hs
mit
266
0
8
51
73
41
32
9
1
module Dataset.Backend.Histogram ( dataset ) where import Dataset.Internal.Types -- | The dataset for a histogram is not terribly interesting, it's basically -- just a list. dataset :: Dataset Point dataset = Dataset { _insert = (:) , _removeEnd = id , _dataset = [] , _toList = id , _xbounds = const Nothing , _ybounds = const Nothing }
SilverSylvester/cplot
src/Dataset/Backend/Histogram.hs
mit
383
0
7
104
81
51
30
11
1
{-# LANGUAGE RecordWildCards #-} module UART.FIFO (fifo) where import CLaSH.Prelude hiding (empty) --import CLaSH.Signal.Bundle --import CLaSH.Signal.Internal import Control.Lens import Control.Monad import Control.Monad.Trans.State import Data.Tuple import Types type FifoAddr = Unsigned 8 -- this has to match the size of fifoRam data FifoState = FifoState { _r_ptr :: FifoAddr , _w_ptr :: FifoAddr , _empty :: Bool , _full :: Bool } makeLenses ''FifoState -- use 'get' as the last statement in fifoRun results in Verilog with combinatorial loop --instance Bundle FifoState where -- type Unbundled' t FifoState = -- ( Signal' t FifoAddr, Signal' t FifoAddr -- , Signal' t Bool, Signal' t Bool , Signal' t Bool ) -- -- bundle' _ (a,b,c,d,e) = FifoState <$> a <*> b <*> c <*> d <*> e -- -- unbundle' _ fifo_state = ( f _r_ptr, f _w_ptr, f _w_en, f _empty, f _full ) -- where -- f a = a <$> fifo_state fifoInit :: FifoState fifoInit = FifoState 0 0 True False fifoVec :: Vec (2 ^ 8) Byte fifoVec = replicate SNat 0 fifoRam :: Signal FifoAddr -> Signal (Maybe (FifoAddr, Byte)) -> Signal Byte --fifoRam = readNew $ blockRamPow2 fifoVec fifoRam = asyncRamPow2 fifoRun :: FifoState -> (Bool, Bool) -> (FifoState, (FifoAddr, Byte -> Maybe (FifoAddr, Byte), Bool, Bool)) fifoRun s@(FifoState {..}) input@(rd, wr) = swap $ flip runState s $ do case input of (True, False) -> -- read when (not _empty) $ do r_ptr += 1 -- next state, equivalent to `r_ptr_next = r_ptr_succ` in verilog full .= False when (_w_ptr == _r_ptr + 1) $ empty .= True (False, True) -> -- write when (not _full) $ do w_ptr += 1 empty .= False when (_r_ptr == _w_ptr + 1) $ full .= True (True, True) -> do r_ptr += 1 w_ptr += 1 _ -> return () let w_f = if wr && not _full then \a -> Just (_w_ptr, a) else const Nothing return (_r_ptr, w_f, _empty, _full) -- TODO: better way? fifo :: Signal Bool -> Signal Bool -> Signal Byte -> (Signal Bool, Signal Bool, Signal Byte) fifo rd wr w_data = (empty, full, r_data) where (r_ptr, w_f, empty, full) = mealyB fifoRun fifoInit (rd, wr) r_data = fifoRam r_ptr (w_f <*> w_data) {-# ANN topEntity (defTop { t_name = "fifo" , t_inputs = ["btnL", "btnR", "sw"] , t_outputs = ["led_empty", "led_full", "led"] , t_extraIn = [("clk", 1), ("btnCpuReset", 1)] , t_extraOut = [] , t_clocks = [] }) #-} topEntity = fifo
aufheben/Y86
SEQ/UART/FIFO.hs
mit
2,531
0
19
630
648
356
292
-1
-1
-- | -- Module: Hakyll.Web.Sass -- Copyright: (C) 2015 Braden Walters -- License: MIT (see LICENSE file) -- Maintainer: Braden Walters <vc@braden-walters.info> -- Stability: experimental -- Portability: ghc module Hakyll.Web.Sass (sassCompiler) where import Data.Default.Class import Data.Functor import Hakyll.Core.Compiler import Hakyll.Core.Item import System.IO.Unsafe import Text.Sass.Compilation import Text.Sass.Options -- | Compiles a SASS file into CSS. sassCompiler :: Compiler (Item String) sassCompiler = do bodyStr <- itemBody <$> getResourceBody extension <- getUnderlyingExtension let mayOptions = selectFileType def extension case mayOptions of Just options -> do resultOrErr <- unsafeCompiler (compileString bodyStr options) case resultOrErr of Left sassError -> fail (unsafePerformIO $ errorMessage sassError) Right result -> makeItem result Nothing -> fail "File type must be .scss or .sass." -- | Use the file extension to determine whether to use indented syntax. selectFileType :: SassOptions -> String -> Maybe SassOptions selectFileType options ".scss" = Just $ options { sassIsIndentedSyntax = False } selectFileType options ".sass" = Just $ options { sassIsIndentedSyntax = True } selectFileType _ _ = Nothing
relrod/hakyll-sass
src/Hakyll/Web/Sass.hs
mit
1,284
0
18
213
267
142
125
24
3
-- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings where import Prelude import Text.Shakespeare.Text (st) import Language.Haskell.TH.Syntax import Database.Persist.Postgresql (PostgresConf) import Yesod.Default.Config import Yesod.Default.Util import Data.Text (Text) import Data.Yaml import Control.Applicative import Settings.Development import Data.Default (def) import Text.Hamlet import Yesod.Fay -- | Which Persistent backend this site is using. type PersistConf = PostgresConf -- Static setting below. Changing these requires a recompile -- | The location of static files on your system. This is a file system -- path. The default value works properly with your scaffolded site. staticDir :: FilePath staticDir = "static" -- | The base URL for your static files. As you can see by the default -- value, this can simply be "static" appended to your application root. -- A powerful optimization can be serving static files from a separate -- domain name. This allows you to use a web server optimized for static -- files, more easily set expires and cache values, and avoid possibly -- costly transference of cookies on static files. For more information, -- please see: -- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain -- -- If you change the resource pattern for StaticR in Foundation.hs, you will -- have to make a corresponding change here. -- -- To see how this value is used, see urlRenderOverride in Foundation.hs staticRoot :: AppConfig DefaultEnv x -> Text staticRoot conf = [st|#{appRoot conf}/static|] -- | Settings for 'widgetFile', such as which template languages to support and -- default Hamlet settings. -- -- For more information on modifying behavior, see: -- -- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile widgetFileSettings :: WidgetFileSettings widgetFileSettings = def { wfsHamletSettings = defaultHamletSettings { hamletNewlines = AlwaysNewlines } } -- The rest of this file contains settings which rarely need changing by a -- user. widgetFile :: String -> Q Exp widgetFile = (if development then widgetFileReload else widgetFileNoReload) widgetFileSettings fayFile' :: Exp -> FayFile fayFile' staticR moduleName | development = fayFileReload settings | otherwise = fayFileProd settings where settings = (yesodFaySettings moduleName) { yfsSeparateRuntime = Just ("static", staticR) -- , yfsPostProcess = readProcess "java" ["-jar", "closure-compiler.jar"] , yfsExternal = Just ("static", staticR) , yfsTypecheckDevel = True , yfsPackages = ["fay-base", "fay-text", "fay-dom"] } data Extra = Extra { extraCopyright :: Text , extraAnalytics :: Maybe Text -- ^ Google Analytics } deriving Show parseExtra :: DefaultEnv -> Object -> Parser Extra parseExtra _ o = Extra <$> o .: "copyright" <*> o .:? "analytics"
mostalive/yesod-splittest
Settings.hs
mit
3,244
0
10
604
399
244
155
-1
-1
-- Dieses Modul stellt Funktionen zur Verfügung die beim erstellen von Beispielen nützlich sind. module System.ArrowVHDL.Circuit.Tools where -- Eingebunden werden für die Demo-Funktionen aus den -- Systembibliotheken die folgenden Module: import System.IO (writeFile) import System.Cmd (system) -- Daneben wird noch der \begriff{except}-Operator (\hsSource{(\\)}) -- aus dem Listen-Modul benötigt: import Data.List ((\\)) -- Schließlich werden eine ganze Reihe von Modulen aus der -- \hsSource{Circuit}-Reihe verwendet: import System.ArrowVHDL.Circuit.Descriptor import System.ArrowVHDL.Circuit.Show import System.ArrowVHDL.Circuit.Graphs import System.ArrowVHDL.Circuit.Auxillary import System.ArrowVHDL.Circuit.Show.DOT import System.ArrowVHDL.Circuit.Workers (mergeEdges) import System.ArrowVHDL.Circuit.Tests -- \subsection{Demo Funktionen} Mit \hsSource{write} und -- \hsSource{genPicture} werden zwei Funktionen definiert, die auf das -- Dateisystem zugreifen, und letztliche dazu verwendet werden, eine -- Grafik einer Schaltung zu erstellen. Dazu wird mittels -- \hsSource{show} die \begriff{.dot}-Darstellung des übergebenen -- Schaltkreises erzeugt und im \hsSource{/tmp}-Folder abgespeichert. -- \hsSource{genPicture} greift dann auf die soeben erzeugte Datei zu, -- und erzeugt aus dem \begriff{.dot}-File ein Bild mit der -- Grafik. Hierbei wird vorausgesetzt, das auf dem System die -- \begriff{graphviz}-Umgebung vorinstalliert ist. write x = writeFile "/tmp/test.dot" (Circuit.Show.DOT.showCircuit x) genPicture = system "dot /tmp/test.dot -Tjpg -o /tmp/test.jpg" -- Mit der Funktion \hsSource{toCircuit} lässt sich aus einer minimal -- Definition ein gültiger Schaltkreis erzeugen. Die minimale -- Definition muss dabei wenigstens einen Namen, sowie die Anzahl der -- eingehenden und Ausgehenden Pins enthalten. toCircuit :: (String, Int, Int) -> CircuitDescriptor toCircuit (name, inPins, outPins) = emptyCircuit { nodeDesc = nodedesc } where nodedesc = MkNode { label = name , nodeId = 0 , sinks = [0..(inPins -1)] , sources = [0..(outPins -1)] } -- Die Funktion \hsSource{filterByName} ist ein Beispiel für die -- Mächtigkeit des neuartigen Ansatzes. \hsSource{filterByName} geht -- hier über eine Schaltung hinweg, und nimmt alle Vorkommenden -- Bausteinen mit einem gewissen Namen heraus. So lassen sich zum -- Testen sehr leicht von den enthaltenen Schaltungen, gewisse selbige -- durch eine andere Version ersetzen. filterByName :: CircuitDescriptor -> String -> CircuitDescriptor filterByName s n = if ((label . nodeDesc) s == n) && (length (nodes s) < 1) then NoDescriptor else s { nodes = (map (flip filterByName n) $ nodes s) } -- Zur Anwendung wird \hsSource{filterByName} in der nächsten -- Funktion, nämlich in \hsSource{replace} gebracht. Hier übergibt man -- die Schaltung in der man ändern möchte. Außerdem übergibt man ein -- Tupel bestehenden aus einem \hsSource{from}-Baustein und einem -- \hsSource{to}-Baustein, wobei nach dem \hsSource{from}-Baustein -- gesucht wird, und dieser dann mit dem \hsSource{to}-Baustein -- ersetzt wird. Als Ergebnis erhält man eine veränderte Schaltung replace :: CircuitDescriptor -> (CircuitDescriptor, CircuitDescriptor) -> CircuitDescriptor replace s ft@(from, to) | not $ isAtomic s = s { nodes = map (flip replace $ ft) (nodes s) } | (label . nodeDesc) s == (label . nodeDesc) from && length (sinks . nodeDesc $ s) == length (sinks . nodeDesc $ from) && length (sources . nodeDesc $ s) == length (sources . nodeDesc $ from) && length (sinks . nodeDesc $ s) == length (sinks . nodeDesc $ to) && length (sources . nodeDesc $ s) == length (sources . nodeDesc $ to) = to { nodeDesc = (nodeDesc to) { nodeId = (nodeId . nodeDesc) s } } | otherwise = s -- %% TODO : Programmiere: mark / cut / trim -- Die Funktion \hsSource{bypass} ermöglicht eine ähnlich -- Funktionalität, wie auch schon \hsSource{filterByName} oder -- \hsSource{replace}. Allerdings nimmt \hsSource{bypass} nur die -- gefundenen Bausteine aus der Schaltung heraus. -- -- %%% TODO : Erklären was rebuildIf macht, und warum ;) -- %%% TODO : grep wires usw. ist teil von rebuildIf bypass :: CircuitDescriptor -> CircuitDescriptor -> CircuitDescriptor bypass s item = s { nodes = ns , edges = es } where (es, ns) = foldl (rebuildIf (\x -> label (nodeDesc x) == label (nodeDesc item))) (edges s, []) $ nodes s rebuildIf :: (CircuitDescriptor -> Bool) -> ([Edge], [CircuitDescriptor]) -> CircuitDescriptor -> ([Edge], [CircuitDescriptor]) rebuildIf isIt (super_es, new_ns) NoDescriptor = (super_es, new_ns) rebuildIf isIt (super_es, new_ns) n | isIt n && length (sinks . nodeDesc $ n) == length (sources . nodeDesc $ n) = (new_es , new_ns) | otherwise = (super_es, new_ns ++ [n']) where new_es = (super_es \\ (lws ++ rws)) ++ nws lws = leftWires super_es (nodeId . nodeDesc $ n) rws = rightWires super_es (nodeId . nodeDesc $ n) nws = zipWith MkEdge (map sourceInfo lws) (map sinkInfo rws) (es,ns) = foldl (rebuildIf isIt) (edges n, []) $ nodes n n' = n { nodes = ns , edges = es } grepWires :: (Edge -> Anchor) -> [Edge] -> CompID -> [Edge] grepWires f es cid = filter (\e -> fst (f e) == Just cid) es leftWires :: [Edge] -> CompID -> [Edge] leftWires = grepWires sinkInfo rightWires :: [Edge] -> CompID -> [Edge] rightWires = grepWires sourceInfo solderWires :: ([Edge], [Edge]) -> [Edge] solderWires = mergeEdges
frosch03/arrowVHDL
src/System/ArrowVHDL/Circuit/Tools.hs
cc0-1.0
5,831
0
19
1,253
1,245
703
542
63
2
import System.Environment import System.IO import Data.Matrix import qualified Data.Vector import qualified Debug.Trace import qualified Data.Vector.Generic main = do putStrLn "Please type file name with board data:" filename <- getLine putStrLn ("Opening: " ++ filename) handle <- openFile filename ReadMode rowList <- hGetLine handle colList <- hGetLine handle let rows = read rowList::[Int] let cols = read colList::[Int] putStrLn ("Rows: " ++ rowList) putStrLn ("Columns: " ++ colList) print (findAllHash rows cols) -- Funkcja inicująca metodę znajdująca wszystkie zamalowane punkty findAllHash ys xs = findAllHash' ys xs (matrix (length ys) (length xs) $ \(_,_) -> 0) findAllHash' :: [Int] -> [Int] -> Matrix Int -> Matrix Int findAllHash' ys xs result | isAllBoardFilled result = result | otherwise = (Debug.Trace.trace (prettyMatrix result) (findAllHash' ys xs (fillPossibilities ys 1 xs 1 (fill2IfMaxVals ys 1 xs 1 (fillIntersections ys 1 (length ys) xs 1 (length xs) (fillAllCols 1 xs (fillAllRows 1 ys result))))))) fillPossibilities :: [Int] -> Int -> [Int] -> Int -> Matrix Int -> Matrix Int fillPossibilities [] _ [] _ result = result fillPossibilities [] rowIndex (x:xs) colIndex result | countZeroVals (Data.Vector.Generic.toList (getCol colIndex result)) == x && countOneVals (Data.Vector.Generic.toList (getCol colIndex result)) == 0 = fillOnesInZerosInCol (Data.Vector.Generic.toList (getCol colIndex result)) 1 colIndex result | countZeroValsAndNear1s (Data.Vector.Generic.toList (getCol colIndex result)) 0 == x = fillOnesInZerosInCol (Data.Vector.Generic.toList (getCol colIndex result)) 1 colIndex result | otherwise = fillPossibilities [] rowIndex xs (colIndex+1) result fillPossibilities (y:ys) rowIndex xs colIndex result | countZeroVals (Data.Vector.Generic.toList (getRow rowIndex result)) == y && countOneVals (Data.Vector.Generic.toList (getRow rowIndex result)) == 0 = fillOnesInZerosInRow (Data.Vector.Generic.toList (getRow rowIndex result)) 1 rowIndex result | countZeroValsAndNear1s (Data.Vector.Generic.toList (getRow rowIndex result)) 0 == y = fillOnesInZerosInRow (Data.Vector.Generic.toList (getRow rowIndex result)) 1 rowIndex result | otherwise = fillPossibilities ys (rowIndex+1) xs colIndex result fillOnesInZerosInCol :: [Int] -> Int -> Int -> Matrix Int -> Matrix Int fillOnesInZerosInCol [] _ _ result = result fillOnesInZerosInCol (x:xs) colIndex counter result | x == 0 = fillOnesInZerosInCol xs colIndex (counter+1) (setElem 1 (counter, colIndex) result) | otherwise = fillOnesInZerosInCol xs colIndex (counter+1) result fillOnesInZerosInRow :: [Int] -> Int -> Int -> Matrix Int -> Matrix Int fillOnesInZerosInRow [] _ _ result = result fillOnesInZerosInRow (x:xs) rowIndex counter result | x == 0 = fillOnesInZerosInRow xs rowIndex (counter+1) (setElem 1 (rowIndex, counter) result) | otherwise = fillOnesInZerosInRow xs rowIndex (counter+1) result fill2IfMaxVals :: [Int] -> Int -> [Int] -> Int -> Matrix Int -> Matrix Int fill2IfMaxVals [] _ [] _ result = result fill2IfMaxVals [] rowIndex (x:xs) colIndex result = fill2IfMaxVals [] rowIndex xs (colIndex+1) (fill2InCol (countOneVals (Data.Vector.Generic.toList (getCol colIndex result))) (Data.Vector.Generic.toList (getCol colIndex result)) x colIndex 1 result) fill2IfMaxVals (y:ys) rowIndex xs colIndex result = fill2IfMaxVals ys (rowIndex+1) xs colIndex (fill2InRow (countOneVals (Data.Vector.Generic.toList (getRow rowIndex result))) (Data.Vector.Generic.toList (getRow rowIndex result)) y rowIndex 1 result) -- zwraca liczbe '1' w liscie countOneVals :: [Int] -> Int countOneVals as = length (filter (==1) as) countZeroVals :: [Int] -> Int countZeroVals as = length (filter (==0) as) -- zlicza liczbę ze w sąsiedztwie włącznie z liczbą najbliższych wystapien 1 countZeroValsAndNear1s :: [Int] -> Int -> Int countZeroValsAndNear1s [] startVal = startVal countZeroValsAndNear1s (a:as) startVal | a == 1 || a == 0 = countZeroValsAndNear1s as (startVal+1) | otherwise = countZeroValsAndNear1s as 0 -- wstawia 2 jesli w wierszu jest juz konieczna ilosc jedynek fill2InCol :: Int -> [Int] -> Int -> Int -> Int -> Matrix Int -> Matrix Int fill2InCol _ [] _ _ _ result = result fill2InCol oneCount (a:as) val colIndex rowIndex result | (oneCount == val) && (a == 0) = fill2InCol oneCount as val colIndex (rowIndex+1) (setElem 2 (rowIndex, colIndex) result) | otherwise = fill2InCol oneCount as val colIndex (rowIndex+1) result -- wstawia 2 jesli w wierszu jest juz konieczna ilosc jedynek -- analogicznie jak fill2InRow, pewnie da się jakoś ładnie przekazać funkcje i zrobić z tych funkcji zrobić jedną fill2InRow :: Int -> [Int] -> Int -> Int -> Int -> Matrix Int -> Matrix Int fill2InRow _ [] _ _ _ result = result fill2InRow oneCount (a:as) val rowIndex colIndex result | (oneCount == val) && (a == 0) = fill2InRow oneCount as val rowIndex (colIndex+1) (setElem 2 (rowIndex, colIndex) result) | otherwise = fill2InRow oneCount as val rowIndex (colIndex+1) result -- funkcja sprawdzająca czy cała plansza jest wypełniona -- jeśli na każdej pozycji jest wartość większa niż 0 to KONIEC isAllBoardFilled :: Matrix Int -> Bool isAllBoardFilled result = all (>0) (toList result) -- funkcja wypelniajaca linie w calosci w przypadku gdy liczba pozycji do zamalowania rowna -- jest dlugosci wiersza -- mapRow (Map a function over a row) -- uwaga! indeksowanie wierszy macierzy rozpoczyna się od 1 fillAllRows :: Int -> [Int] -> Matrix Int -> Matrix Int fillAllRows _ [] result = result fillAllRows rowIndex (y:ys) result | y == (Data.Vector.length (getRow rowIndex result)) = fillAllRows (rowIndex+1) ys (mapRow (\_ a -> 1) rowIndex result) | otherwise = fillAllRows (rowIndex+1) ys result -- analogicznie jak fillAllRows -- indeksowanie kolumn zaczyna się od 1 fillAllCols :: Int -> [Int] -> Matrix Int -> Matrix Int fillAllCols _ [] result = result fillAllCols colIndex (x:xs) result | x == (Data.Vector.length (getCol colIndex result)) = fillAllCols (colIndex+1) xs (mapCol (\_ a -> 1) colIndex result) | otherwise = fillAllCols (colIndex+1) xs result -- zamalowuje przecięcia, zgodnie z metodą Zamalowanych Kratek na Przecięciach fillIntersections :: [Int] -> Int -> Int -> [Int] -> Int -> Int -> Matrix Int -> Matrix Int fillIntersections [] _ _ [] _ _ result = result fillIntersections [] rowIndex rowLength (x:xs) colIndex colLength result = -- potem po kolumnach fillIntersections [] rowIndex rowLength xs (colIndex+1) colLength (fillElementsInCol colIndex (getListsDuplicates (getSelectedFromLeft x colLength) (getSelectedFromRight x colLength)) result) fillIntersections (y:ys) rowIndex rowLength xs colIndex colLength result = -- najpierw po wierszach fillIntersections ys (rowIndex+1) rowLength xs colIndex colLength (fillElementsInRow rowIndex (getListsDuplicates (getSelectedFromLeft y rowLength) (getSelectedFromRight y rowLength)) result) -- wypelnia elementy w wierszu o podanym indeksie fillElementsInRow :: Int -> [Int] -> Matrix Int -> Matrix Int fillElementsInRow _ [] result = result fillElementsInRow rowIndex (y:ys) result = fillElementsInRow rowIndex ys (setElem 1 (rowIndex, y) result) -- wypelnia elementy w kolumnie o podanym indeksie fillElementsInCol :: Int -> [Int] -> Matrix Int -> Matrix Int fillElementsInCol _ [] result = result fillElementsInCol colIndex (x:xs) result = fillElementsInCol colIndex xs (setElem 1 (x, colIndex) result) -- zwraca listę pozycji, które mogą być zaznaczone od strony lewej w wierszu, -- pobiera liczbe pozycji, które na pewno muszą być zaznaczone w wierszu oraz długość wiersza -- zwraca listę pozycji gdzie potencjalnie mogę być zaznaczone pozycje -- na podstawie Metody Zamalowanych Kratek na Przecięciach -- uwaga! zakładam indeksowanie od 1 getSelectedFromLeft :: Int -> Int -> [Int] getSelectedFromLeft numberOfPositions rowLength | numberOfPositions == 0 = [] | otherwise = [numberOfPositions] ++ getSelectedFromLeft (numberOfPositions - 1) rowLength -- analogicznie jak getSelectedFromLeft tylko tutaj sprawdzenie możliwych -- do zaznaczenia pozycji następuje od prawej strony -- uwaga! zakładam indeksowanie od 1 getSelectedFromRight :: Int -> Int -> [Int] getSelectedFromRight numberOfPositions rowLength | numberOfPositions == 0 = [] | otherwise = [rowLength] ++ getSelectedFromRight (numberOfPositions - 1) (rowLength - 1) getListsDuplicates :: [Int] -> [Int] -> [Int] getListsDuplicates [] _ = [] getListsDuplicates _ [] = [] getListsDuplicates (x:xs) y | x `elem` y = [x] ++ getListsDuplicates xs y | otherwise = getListsDuplicates xs y
lgadawski/spop-logical-pics
logical-pics.hs
epl-1.0
9,068
118
19
1,720
2,994
1,531
1,463
145
1
{-| Unittests for 'Ganeti.JQueue.Objects'. -} {- Copyright (C) 2012, 2013 Google Inc. 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Test.Ganeti.JQueue.Objects ( justNoTs , genQueuedOpCode , emptyJob , genJobId ) where import Control.Applicative import Test.QuickCheck as QuickCheck import Text.JSON import Test.Ganeti.Types () import Test.Ganeti.OpCodes () import qualified Ganeti.Constants as C import Ganeti.JQueue import Ganeti.Types as Types -- | noTimestamp in Just form. justNoTs :: Maybe Timestamp justNoTs = Just noTimestamp -- | Generates a simple queued opcode. genQueuedOpCode :: Gen QueuedOpCode genQueuedOpCode = QueuedOpCode <$> (ValidOpCode <$> arbitrary) <*> arbitrary <*> pure JSNull <*> pure [] <*> choose (C.opPrioLowest, C.opPrioHighest) <*> pure justNoTs <*> pure justNoTs <*> pure justNoTs -- | Generates an static, empty job. emptyJob :: (Monad m) => m QueuedJob emptyJob = do jid0 <- makeJobId 0 return $ QueuedJob jid0 [] justNoTs justNoTs justNoTs Nothing Nothing -- | Generates a job ID. genJobId :: Gen JobId genJobId = do p <- arbitrary::Gen (Types.NonNegative Int) makeJobId $ fromNonNegative p
ribag/ganeti-experiments
test/hs/Test/Ganeti/JQueue/Objects.hs
gpl-2.0
1,815
0
14
317
281
154
127
29
1
{-# LANGUAGE DeriveDataTypeable #-} module Operate.Login where import Gateway.CGI import Control.Types ( VNr, toString, TimeStatus (..) ) import Control.Monad ( when, mzero ) import qualified Control.Vorlesung as V import qualified Control.Semester import qualified Control.Schule as U import qualified Control.Vorlesung import qualified Control.Student.CGI import qualified Control.Student.Type as S import qualified Control.Admin.CGI import qualified Control.Direktor.CGI -- import qualified Text.XHtml import Autolib.Util.Sort import Data.Typeable data Status = Student | Tutor | Direktor | Minister deriving ( Show, Eq, Ord, Typeable ) -- | returns ( s, v, ist_tutor, ist_eingeschrieben ) -- unterschiede: tutor darf "alles", -- student darf keine aufgaben ändern und nur aktuelle aufgaben sehen form :: Maybe U.Schule -> Form IO ( S.Student, V.Vorlesung, Status , Bool ) form mschool = do -- open btable stud <- Control.Student.CGI.login mschool -- close -- btable Control.Admin.CGI.main stud Control.Direktor.CGI.main stud aule stud aule stud = do sems0 <- io $ Control.Semester.get_at_school $ S.unr stud let sems = sortBy ( \ s -> Control.Semester.status s /= Current ) $ sems0 if null sems then do plain "Für diese Schule wurden noch keine Semester definiert." mzero else continue stud sems continue stud sems = do let snr = S.snr stud open btable sem <- click_choice_with_default 0 "Semester" $ do sem <- sems return ( toString $ Control.Semester.name sem, sem ) -- alle vorlesungen an dieser Schule vors0 <- io $ V.get_at_school ( S.unr stud ) let vors = reverse $ sortBy V.einschreibVon vors0 -- hierfür ist er tutor: tvors <- io $ V.get_tutored snr -- hierfür ist er eingeschrieben: avors <- io $ V.get_attended snr let current v = Control.Vorlesung.enr v == Control.Semester.enr sem vor <- click_choice "Vorlesung" $ do vor <- filter current vors return ( toString $ V.name vor , vor ) close -- btable let motd = toString $ V.motd vor when ( not $ null motd ) $ do par plain motd par let status = if V.vnr vor `elem` map V.vnr tvors then Tutor else Student attends = V.vnr vor `elem` map V.vnr avors open btable when ( status < Tutor ) close -- risky return ( stud, vor, status, attends )
marcellussiegburg/autotool
db/src/Operate/Login.hs
gpl-2.0
2,436
26
16
580
677
369
308
60
2
module ConnectFour ( module ConnectFour.Board , module ConnectFour.Move , module ConnectFour.GameState , module ConnectFour.Piece ) where import ConnectFour.Board import ConnectFour.Move import ConnectFour.GameState import ConnectFour.Piece
RyanBeatty/Falcon
src/ConnectFour.hs
gpl-2.0
260
6
5
43
56
35
21
9
0
{-# LANGUAGE ScopedTypeVariables #-} import Data.Ratio as Ra {- Type of a dyadic rational, a bit like floating point except that operations can be performed exactly. resource tells you which maximum denominator to use for inexact operations (exact operations send dyadic rationals to dyadic rationals.) -} data DyadicRational = DyadicRational {num :: Int, denom :: Int, maxDenom :: Int} deriving Show instance Eq DyadicRational where x == y = (num x * 2 ^ denom y) == (num y * 2 ^ denom x) instance Ord DyadicRational where compare x y = (num x * 2 ^ denom y) `compare` (num y * 2 ^ denom x) resource = 10 :: Int fromInt x = DyadicRational {num = x, denom = 0, maxDenom = resource} -- does not perform any simplification add :: DyadicRational -> DyadicRational -> DyadicRational add x y = let expz = max (denom x) (denom y) in let numz = num x * 2 ^ (expz - denom x) + num y * 2 ^ (expz - denom y) in let maxDenomz = max (maxDenom x) (maxDenom y) in DyadicRational {num = numz , denom = expz , maxDenom = maxDenomz} -- does not perform any simplification, almost identical to add. sub :: DyadicRational -> DyadicRational -> DyadicRational sub x y = let expz = max (denom x) (denom y) in let numz = num x * 2 ^ (expz - denom x) - num y * 2 ^ (expz - denom y) in let maxDenomz = max (maxDenom x) (maxDenom y) in DyadicRational {num = numz , denom = expz , maxDenom = maxDenomz} -- also doesn't perform simplification mul :: DyadicRational -> DyadicRational -> DyadicRational mul x y = let expz = denom x + denom y in let maxDenomz = max (maxDenom x) (maxDenom y) in let numz = num x * num y in DyadicRational {num = numz , denom = expz , maxDenom = maxDenomz} -- simplify a Dyadic rational simplify :: DyadicRational -> DyadicRational simplify x = let largePower :: Int = 2 ^ denom x in let remove :: Int = num x `gcd` largePower in let lb :: Int = (round $ logBase (fromIntegral remove) 2.0) in DyadicRational {num = num x `div` remove, denom = denom x - lb, maxDenom = maxDenom x} -- lower approximation to integer reciprocal recpFloor :: Int -> DyadicRational recpFloor k = let numz = (2^resource) `div` k in -- constructs a lower approximation. DyadicRational {num = numz, denom = resource, maxDenom = resource} -- upper approximation to integer reciprocal recpCeil :: Int -> DyadicRational recpCeil k = let numz = (2^resource) `div` k + (if (2^resource) `mod` k == 0 then 0 else 1) in DyadicRational {num = numz, denom = resource, maxDenom = resource} recpFloor1 :: DyadicRational -> DyadicRational recpFloor1 k = (recpFloor $ num k) `mul` (fromInt (2^ denom k) ) recpCeil1 :: DyadicRational -> DyadicRational recpCeil1 k = (recpCeil $ num k) `mul` (fromInt (2^ denom k) ) toDouble :: DyadicRational -> Double toDouble x = let num' = (fromIntegral $ num x) :: Double in let denom' = (fromIntegral $ denom x) :: Double in num' / 2 ** denom' data Interval = Interval {lower :: DyadicRational, upper :: DyadicRational} zero = Interval {lower = fromInt 0, upper = fromInt 0} instance Show Interval where show x = if lower x == upper x then "{" ++ (show $ toDouble $ lower x) ++ "}" else "{" ++ (show $ toDouble $ lower x) ++ ", " ++ (show $ toDouble $ upper x) ++ "}" instance Eq Interval where x == y = (lower x == lower y) && (upper x == upper y) -- implementation of add is unnecessarily slow but IDGAF -- note, I HAD to define signum. currently it just checks whether the interval contains zero -- which is actually quite handy. Note that abs will not do the right thing. -- I'll make a better version later. instance Num Interval where x + y = apply2 add x y x - y = apply2 sub x y x * y = apply2 mul x y signum x = if (lower x > fromInt 0) then 1 else if (upper x < fromInt 0) then -1 else 0 abs x = case signum x of 1 -> x (-1) -> (fromInteger 0) - x 0 -> Interval {lower = fromInt 0, upper = max (fromInt (-1) `mul` lower x) (upper x) } fromInteger x = promoteDyadicRational $ fromInt $ fromInteger x instance Fractional Interval where recip x = Interval {lower = recpFloor1 $ upper x , upper = recpCeil1 $ lower x} fromRational x = error "seriously you guys" toList :: Interval -> [DyadicRational] toList i0 = [lower i0, upper i0] promoteDyadicRational :: DyadicRational -> Interval promoteDyadicRational x = Interval {lower = x, upper = x} apply2 :: (DyadicRational -> DyadicRational -> DyadicRational) -> Interval -> Interval -> Interval apply2 f i0 i1 = let vals = [ f x y | x <- toList i0 , y <- toList i1 ] in Interval {lower = minimum vals, upper = maximum vals} -- split interval splits the interval into a positive and negative component. splitInterval :: Interval -> [Interval] splitInterval i0 = if (i0 == zero) then [zero] else let up = upper i0 in let down = lower i0 in let raw = [Interval { lower = down, upper = fromInt 0 }, Interval { lower = fromInt 0, upper = up}] in filter (\ i1 -> (upper i1 /= lower i1)) raw
gregory-nisbet/IntervalArithmetic
arithmetic.hs
gpl-2.0
4,966
103
17
1,059
2,010
1,031
979
89
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Debug -- License : GPL-2 -- Maintainer : yi-devel@googlegroups.com -- Stability : experimental -- Portability : portable -- -- Debug utilities used throughout Yi. module Yi.Debug ( initDebug, trace, traceM, traceM_, logPutStrLn , logError, logStream, Yi.Debug.error ) where import Control.Concurrent import Control.Monad.Base import Data.IORef import Data.Monoid import qualified Data.Text as T import Data.Time import GHC.Conc (labelThread) import System.IO import System.IO.Unsafe (unsafePerformIO) import System.Locale dbgHandle :: IORef (Maybe Handle) dbgHandle = unsafePerformIO $ newIORef Nothing {-# NOINLINE dbgHandle #-} -- | Set the file to which debugging output should be written. Though this -- is called /init/Debug. -- Debugging output is not created by default (i.e., if this function -- is never called.) -- The target file can not be changed, nor debugging disabled. initDebug :: FilePath -> IO () initDebug f = do hndl <- readIORef dbgHandle case hndl of Nothing -> do openFile f WriteMode >>= writeIORef dbgHandle . Just logPutStrLn "Logging initialized." Just _ -> logPutStrLn "Attempt to re-initialize the logging system." -- | Outputs the given string before returning the second argument. trace :: T.Text -> a -> a trace s e = unsafePerformIO $ logPutStrLn s >> return e {-# NOINLINE trace #-} error :: T.Text -> a error s = unsafePerformIO $ logPutStrLn s >> Prelude.error (T.unpack s) logPutStrLn :: MonadBase IO m => T.Text -> m () logPutStrLn s = liftBase $ do readIORef dbgHandle >>= \case Nothing -> return () Just h -> do time <- getCurrentTime tId <- myThreadId let m = show tId ++ " " ++ T.unpack s hPutStrLn h $ formatTime defaultTimeLocale rfc822DateFormat' time ++ m hFlush h where -- A bug in rfc822DateFormat makes us use our own format string rfc822DateFormat' = "%a, %d %b %Y %H:%M:%S %Z" logError :: MonadBase IO m => T.Text -> m () logError s = logPutStrLn $ "error: " <> s logStream :: Show a => T.Text -> Chan a -> IO () logStream msg ch = do logPutStrLn $ "Logging stream " <> msg logThreadId <- forkIO $ logStreamThread msg ch labelThread logThreadId "LogStream" logStreamThread :: Show a => T.Text -> Chan a -> IO () logStreamThread msg ch = do stream <- getChanContents =<< dupChan ch mapM_ logPutStrLn [ msg `T.snoc` '(' <> T.pack (show i) `T.snoc` ')' <> T.pack (show event) | (event, i) <- zip stream [(0::Int)..] ] -- | Traces @x@ and returns @y@. traceM :: Monad m => T.Text -> a -> m a traceM x y = trace x $ return y -- | Like traceM, but returns (). traceM_ :: Monad m => T.Text -> m () traceM_ x = traceM x ()
atsukotakahashi/wi
src/library/Yi/Debug.hs
gpl-2.0
3,013
0
19
749
793
403
390
59
2
import Data.Maybe import Data.Monoid import Text.Pandoc import Text.Pandoc.JSON main :: IO () main = toJSONFilter toMinted toMinted :: Block -> Block toMinted = bottomUp toMintedBlock . bottomUp toMintedInline toMintedBlock :: Block -> Block toMintedBlock (CodeBlock (identity, classes, namevals) contents) = RawBlock (Format "latex") $ unlines [ "\\begin{minted}[breakautoindent=false, breaklines=true, linenos=true]{" <> lang <> "}" , contents , "\\end{minted}" ] where label = if identity /= "" then "\\label{" <> identity <> "}" else "" lang = if classes /= [] then head classes else "\\mintlang" caption = fromMaybe "" $ lookup "caption" namevals toMintedBlock x = x toMintedInline :: Inline -> Inline toMintedInline (Code (_, classes, _) contents) = RawInline (Format "latex") $ "\\mintinline{" <> lang <> "}{" <> contents <> "}" where lang = if classes /= [] then head classes else "\\mintlang" toMintedInline x = x
ncaq/pandoc-minted
src/Main.hs
gpl-2.0
999
1
12
213
305
159
146
23
3
{-# LANGUAGE EmptyDataDecls, FlexibleContexts, FlexibleInstances, GADTs, GeneralizedNewtypeDeriving, MultiParamTypeClasses, OverloadedStrings, DeriveGeneric, QuasiQuotes, TemplateHaskell, TypeFamilies #-} {-| Description: The database schema (and some helpers). This module defines the database schema. It uses Template Haskell to also create new types for these values so that they can be used in the rest of the application. Though types and typeclass instances are created automatically, we currently have a few manually-generated spots to clean up. This should be rather straightforward. -} module Database.Tables where import Database.Persist.TH import Database.DataType import qualified Data.Text as T import qualified Data.Vector as V import Data.Aeson import GHC.Generics -- | A data type representing a time for the section of a course. -- The first list is comprised of two values: the date (represented as a number -- of the week), and the time. The dates span Monday-Friday, being represented -- by 1-5 respectively. The time is a number between 0-23. -- TODO: Change this datatype. This datatype shouldn't be implemented with -- a list, perhaps a tuple would be better. data Time = Time { timeField :: [Double] } deriving (Show, Read, Eq, Generic) derivePersistField "Time" -- | A two-dimensional point. type Point = (Double, Double) share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Courses json code T.Text title T.Text Maybe description T.Text Maybe manualTutorialEnrolment Bool Maybe manualPracticalEnrolment Bool Maybe prereqs T.Text Maybe exclusions T.Text Maybe breadth T.Text Maybe distribution T.Text Maybe prereqString T.Text Maybe coreqs T.Text Maybe videoUrls [T.Text] deriving Show Lecture json code T.Text session T.Text section T.Text times [Time] cap Int instructor T.Text enrol Int wait Int extra Int timeStr T.Text deriving Show Tutorial json code T.Text section T.Text Maybe session T.Text times [Time] deriving Show Breadth bId Int description String deriving Show Distribution dId Int description String deriving Show Graph json title String deriving Show Text graph GraphId rId String pos Point text String align String fill String deriving Show Shape graph GraphId id_ String pos Point width Double height Double fill String stroke String text [Text] tolerance Double type_ ShapeType Path graph GraphId id_ String points [Point] fill String stroke String isRegion Bool source String target String deriving Show FacebookTest fId String testString String deriving Show |] -- ** TODO: Remove these extra types and class instances -- | A Session. data Session = Session { lectures :: [Lecture], tutorials :: [Tutorial] } deriving (Show, Generic) -- | A Course. -- each element of prereqs can be one of three things: -- -- * a one-element list containing a course code -- * a list starting with "and", and 2 or more course codes -- * a list starting with "or", and 2 or more course codes data Course = Course { breadth :: Maybe T.Text, description :: Maybe T.Text, title :: Maybe T.Text, prereqString :: Maybe T.Text, fallSession :: Maybe Session, springSession :: Maybe Session, yearSession :: Maybe Session, name :: !T.Text, exclusions :: Maybe T.Text, manualTutorialEnrolment :: Maybe Bool, manualPracticalEnrolment :: Maybe Bool, distribution :: Maybe T.Text, prereqs :: Maybe T.Text, coreqs :: Maybe T.Text, videoUrls :: [T.Text] } deriving (Show, Generic) instance ToJSON Course instance ToJSON Session instance ToJSON Time -- instance FromJSON required so that tables can be parsed into JSON, -- not necessary otherwise. instance FromJSON Time -- | Converts a Double to a T.Text. -- This removes the period from the double, as the JavaScript code, -- uses the output in an element's ID, which is then later used in -- jQuery. @.@ is a jQuery meta-character, and must be removed from the ID. convertTimeToString :: Time -> [T.Text] convertTimeToString (Time [day, timeNum]) = [T.pack . show . floor $ day, T.replace "." "-" . T.pack . show $ timeNum]
pkukulak/courseography
hs/Database/Tables.hs
gpl-3.0
4,672
0
10
1,270
459
267
192
53
1
{- This is the bootstrapping compiler for the Bzo programming language. Copyright (C) 2020 Charles Rosenbauer This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.-} module Tokens where import Data.Int import qualified Data.List as L import qualified Data.Text as T import qualified Data.Set as S import qualified Data.Map.Strict as M import qualified Data.Maybe as Mb import Error import HigherOrder data BzoToken = TkStartTup { spos :: !BzoPos } | TkEndTup { spos :: !BzoPos } | TkStartDat { spos :: !BzoPos } | TkEndDat { spos :: !BzoPos } | TkStartDo { spos :: !BzoPos } | TkEndDo { spos :: !BzoPos } | TkSepExpr { spos :: !BzoPos } | TkSepPoly { spos :: !BzoPos } | TkCurrySym { spos :: !BzoPos } | TkFilterSym { spos :: !BzoPos } | TkLambdaSym { spos :: !BzoPos } | TkReference { spos :: !BzoPos } | TkWildcard { spos :: !BzoPos } | TkDefine { spos :: !BzoPos } | TkFnSym { spos :: !BzoPos } | TkTupEmpt { spos :: !BzoPos } | TkArrGnrl { spos :: !BzoPos } | TkArrMod { spos :: !BzoPos } | TkInt { spos :: !BzoPos, valInt :: !Integer } | TkFlt { spos :: !BzoPos, valFlt :: !Double } | TkStr { spos :: !BzoPos, valStr :: !T.Text } | TkId { spos :: !BzoPos, valId :: !T.Text } | TkTypeId { spos :: !BzoPos, valId :: !T.Text } | TkMutId { spos :: !BzoPos, valId :: !T.Text } | TkTyVar { spos :: !BzoPos, valId :: !T.Text } | TkNewline { spos :: !BzoPos } | TkBuiltin { spos :: !BzoPos, valId :: !T.Text } | TkBIType { spos :: !BzoPos, valId :: !T.Text } | TkNil deriving Eq showTk :: BzoToken -> String showTk (TkStartTup _) = "(" showTk (TkEndTup _) = ")" showTk (TkStartDat _) = "[" showTk (TkEndDat _) = "]" showTk (TkStartDo _) = "{" showTk (TkEndDo _) = "}" showTk (TkSepExpr _) = "." showTk (TkSepPoly _) = "," showTk (TkCurrySym _) = "`" showTk (TkFilterSym _) = ":" showTk (TkLambdaSym _) = ";" showTk (TkReference _) = "@" showTk (TkWildcard _) = "_" showTk (TkDefine _) = "::" showTk (TkFnSym _) = ";;" showTk (TkTupEmpt _) = "()" showTk (TkArrGnrl _) = "[]" showTk (TkArrMod _) = ".." showTk (TkInt _ x) = "I:" ++ show x showTk (TkFlt _ x) = "F:" ++ show x showTk (TkStr _ st) = "S:" ++ show st showTk (TkId _ st) = "ID:" ++ show st showTk (TkMutId _ st) = "MID:" ++ show st showTk (TkTypeId _ st) = "TID:" ++ show st showTk (TkNewline _) = "NEWL\n" showTk (TkBuiltin _ st) = "BI:" ++ show st showTk (TkBIType _ st) = "BIT:" ++ show st showTk (TkTyVar _ st) = "TyVr:" ++ show st showTk _ = "NIL" instance Show BzoToken where show = showTk showTokens :: [BzoToken] -> String showTokens tk = Prelude.unwords $ Prelude.map showTk tk
charlesrosenbauer/Bzo-Compiler
src/Tokens.hs
gpl-3.0
3,560
0
10
1,045
1,016
552
464
147
1
import qualified Data.Text as T wordcount :: String -> Int wordcount "" = 0 wordcount start = let count = T.splitOn (T.pack " ") (T.pack start) in length count main :: IO () main = do line <- getLine print $ wordcount line
torchhound/projects
haskell/wordcount.hs
gpl-3.0
229
3
12
49
109
52
57
9
1
{-# LANGUAGE ViewPatterns, ConstraintKinds, FlexibleContexts #-} module Language.SecreC.TypeChecker.Conversion where import Language.SecreC.TypeChecker.Base import Language.SecreC.TypeChecker.Environment import Language.SecreC.Prover.Base import Language.SecreC.Syntax import Language.SecreC.Location import Language.SecreC.Error import Language.SecreC.Utils import Language.SecreC.Pretty import Language.SecreC.Position import {-# SOURCE #-} Language.SecreC.TypeChecker.Type import Data.Graph.Inductive.Graph as Graph import Text.PrettyPrint import Control.Monad.Except import Data.List as List type ConversionK loc m = ProverK loc m ftloc :: (Location loc,Functor f) => loc -> f (Typed Position) -> f (Typed loc) ftloc l x = fmap (fmap (updpos l)) x dec2ProcDecl :: ConversionK loc m => loc -> DecType -> TcM m (ProcedureDeclaration GIdentifier (Typed loc)) dec2ProcDecl l dec@(DecType _ _ _ hctx bctx _ (ProcType p pn@(PIden _) pargs ret anns (Just body) _)) = do ret' <- type2ReturnTypeSpecifier l ret pargs' <- mapM (parg2ProcedureParameter l) pargs bctx' <- decCtx2TemplateContext l =<< mergeHeadDecCtx l hctx bctx let pn' = (ProcedureName (Typed l $ DecT dec) $ funit pn) return (ProcedureDeclaration (notTyped "decl" l) ret' pn' pargs' bctx' (map (ftloc l) anns) (map (ftloc l) body)) dec2ProcDecl l dec@(DecType _ _ _ hctx bctx _ (ProcType p (OIden on) pargs ret anns (Just body) _)) = do ret' <- type2ReturnTypeSpecifier l ret pargs' <- mapM (parg2ProcedureParameter l) pargs bctx' <- decCtx2TemplateContext l =<< mergeHeadDecCtx l hctx bctx let on' = updLoc (fmap (Typed l) on) (Typed l $ DecT dec) return (OperatorDeclaration (notTyped "decl" l) ret' on' pargs' bctx' (map (ftloc l) anns) (map (ftloc l) body)) dec2ProcDecl l t = do ppt <- pp t genError (locpos l) $ text "dec2ProcDecl:" <+> ppt dec2FunDecl :: ConversionK loc m => loc -> DecType -> TcM m (FunctionDeclaration GIdentifier (Typed loc)) dec2FunDecl l dec@(DecType _ _ _ hctx bctx _ (FunType isLeak p pn@(PIden _) pargs ret anns (Just body) _)) = do ret' <- type2TypeSpecifierNonVoid l ret pargs' <- mapM (parg2ProcedureParameter l) pargs bctx' <- decCtx2TemplateContext l =<< mergeHeadDecCtx l hctx bctx let pn' = (ProcedureName (Typed l $ DecT dec) $ funit pn) return (FunDeclaration (notTyped "decl" l) isLeak ret' pn' pargs' bctx' (map (ftloc l) anns) (ftloc l body)) dec2FunDecl l dec@(DecType _ _ _ hctx bctx _ (FunType isLeak p (OIden on) pargs ret anns (Just body) _)) = do ret' <- type2TypeSpecifierNonVoid l ret pargs' <- mapM (parg2ProcedureParameter l) pargs bctx' <- decCtx2TemplateContext l =<< mergeHeadDecCtx l hctx bctx let on' = updLoc (fmap (Typed l) on) (Typed l $ DecT dec) return (OperatorFunDeclaration (notTyped "decl" l) isLeak ret' on' pargs' bctx' (map (ftloc l) anns) (ftloc l body)) dec2FunDecl l t = do ppt <- pp t genError (locpos l) $ text "dec2FunDecl:" <+> ppt dec2AxiomDecl :: ConversionK loc m => loc -> DecType -> TcM m (AxiomDeclaration GIdentifier (Typed loc)) dec2AxiomDecl l dec@(DecType _ _ targs _ _ _ (AxiomType isLeak p pargs anns _)) = do let vars = map (varNameId . unConstrained . fst) targs targs' <- mapM (targ2TemplateQuantifier l vars) targs pargs' <- mapM (parg2ProcedureParameter l) pargs return $ AxiomDeclaration (Typed l $ DecT dec) isLeak targs' pargs' (map (ftloc l) anns) dec2AxiomDecl l t = do ppt <- pp t genError (locpos l) $ text "dec2AxiomDecl:" <+> ppt decCtx2TemplateContext :: ConversionK loc m => loc -> DecCtx -> TcM m (TemplateContext GIdentifier (Typed loc)) decCtx2TemplateContext l dec@(DecCtx Nothing _ _) = return $ TemplateContext (Typed l (DecCtxT dec)) Nothing decCtx2TemplateContext l dec@(DecCtx (Just _) d _) = liftM (TemplateContext (Typed l (DecCtxT dec)) . Just) $ cstrs2Context l (pureCstrs d) where cstrs2Context :: ConversionK loc m => loc -> TCstrGraph -> TcM m [ContextConstraint GIdentifier (Typed loc)] cstrs2Context l g = mapM (cstr2Context l . unLoc . snd) $ Graph.labNodes g cstr2Context :: ConversionK loc m => loc -> TCstr -> TcM m (ContextConstraint GIdentifier (Typed loc)) cstr2Context l (TcK k st) = tcCstr2Context l k st cstr2Context l (CheckK k _) = do ppk <- pp k genError (locpos l) $ text "cstr2Context: check" <+> ppk cstr2Context l (HypK k _) = do ppk <- pp k genError (locpos l) $ text "cstr2Context: hypothesis" <+> ppk tcCstr2Context :: ConversionK loc m => loc -> TcCstr -> CstrState -> TcM m (ContextConstraint GIdentifier (Typed loc)) tcCstr2Context l k@(TDec dk es (TIden n) ts x) st = do let tn' = TypeName (Typed l $ DecT x) $ TIden n ts' <- mapM (mapFstM (type2TemplateTypeArgument l)) ts return $ ContextTDec (Typed l $ TCstrT $ TcK k st) (cstrExprC st) tn' ts' tcCstr2Context l k@(PDec dk es (PIden n) ts args ret x) st = do ret' <- type2ReturnTypeSpecifier l ret let pn' = ProcedureName (Typed l $ DecT x) $ PIden n ts' <- mapM (mapM (mapFstM (type2TemplateTypeArgument l))) ts args' <- mapM (decPArg2CtxPArg l) args let Just kind = decKind2CstrKind $ cstrDecK st return $ ContextPDec (Typed l $ TCstrT $ TcK k st) (cstrExprC st) (cstrIsLeak st) (cstrIsAnn st) kind ret' pn' ts' args' tcCstr2Context l k@(PDec dk es (OIden o) ts args ret _) st = do ret' <- type2ReturnTypeSpecifier l ret let o' = fmap (Typed l) o ts' <- mapM (mapM (mapFstM (type2TemplateTypeArgument l))) ts args' <- mapM (decPArg2CtxPArg l) args let Just kind = decKind2CstrKind $ cstrDecK st return $ ContextODec (Typed l $ TCstrT $ TcK k st) (cstrExprC st) (cstrIsLeak st) (cstrIsAnn st) kind ret' o' ts' args' tcCstr2Context l k st = do ppk <- pp k genError (locpos l) $ text "tcCstr2Context:" <+> ppk decKind2CstrKind :: DecKind -> Maybe CstrKind decKind2CstrKind PKind = Just CstrProcedure decKind2CstrKind FKind = Just CstrFunction decKind2CstrKind LKind = Just CstrLemma decKind2CstrKind k = Nothing cstrKind2DecKind :: CstrKind -> DecKind cstrKind2DecKind CstrProcedure = PKind cstrKind2DecKind CstrFunction = FKind cstrKind2DecKind CstrLemma = LKind decPArg2CtxPArg :: ConversionK loc m => loc -> (IsConst,Either Expr Type,IsVariadic) -> TcM m (CtxPArg GIdentifier (Typed loc)) decPArg2CtxPArg l (isConst,Left e,isVariadic) = return $ CtxExprPArg (Typed l $ IdxT e) isConst (fmap (Typed l) e) isVariadic decPArg2CtxPArg l (isConst,Right t,isVariadic) = do t' <- type2TypeSpecifierNonVoid l t return $ CtxTypePArg (Typed l t) isConst t' isVariadic dec2LemmaDecl :: ConversionK loc m => loc -> DecType -> TcM m (LemmaDeclaration GIdentifier (Typed loc)) dec2LemmaDecl l dec@(DecType _ _ targs hctx bctx _ (LemmaType isLeak p pn pargs anns (Just body) _)) = do let vars = map (varNameId . unConstrained . fst) targs targs' <- mapM (targ2TemplateQuantifier l vars) targs pargs' <- mapM (parg2ProcedureParameter l) pargs let pn' = (ProcedureName (Typed l $ DecT dec) $ funit pn) return $ LemmaDeclaration (Typed l $ DecT dec) isLeak pn' targs' pargs' (map (ftloc l) anns) (fmap (map (ftloc l)) body) dec2LemmaDecl l t = do ppt <- pp t genError (locpos l) $ text "dec2LemmaDecl:" <+> ppt dec2StructDecl :: ConversionK loc m => loc -> DecType -> TcM m (StructureDeclaration GIdentifier (Typed loc)) dec2StructDecl l dec@(DecType _ _ _ hctx bctx _ (StructType p sid (Just atts) _)) = do bctx' <- decCtx2TemplateContext l =<< mergeHeadDecCtx l hctx bctx let atts' = map (fmap (Typed l)) atts let sid' = fmap (const $ Typed l $ DecT dec) $ TypeName () sid return (StructureDeclaration (notTyped "decl" l) sid' bctx' atts') dec2StructDecl l t = do ppt <- pp t genError (locpos l) $ text "dec2StructDecl:" <+> ppt targ2TemplateQuantifier :: ConversionK loc m => loc -> [GIdentifier] -> (Constrained Var,IsVariadic) -> TcM m (TemplateQuantifier GIdentifier (Typed loc)) targ2TemplateQuantifier l vars cv@(Constrained v@(VarName vt vn) e,isVariadic) = case (typeClass "targ" vt,vt) of (isDomain -> True,KindT k) -> do mbk <- case k of PublicK -> return Nothing PrivateK kn -> return $ Just $ fmap (const $ Typed l $ KindT k) $ KindName () kn KVar kv Nothing -> return $ Just $ KindName (Typed l $ KindT k) $ VIden kv KVar kv (Just NonPublicClass) -> if List.elem (VIden kv) vars then return $ Just $ KindName (Typed l $ KindT k) $ VIden kv else do ppk <- pp k genError (locpos l) $ text "targ2TemplateQuantifier: unsupported kind type" <+> ppk return $ DomainQuantifier (notTyped "targ" l) isVariadic (DomainName (Typed l vt) vn) mbk (isKind -> True,KType isPriv) -> do return $ KindQuantifier (notTyped "targ" l) isPriv isVariadic (KindName (Typed l vt) vn) (isType -> True,BType c) -> do return $ DataQuantifier (notTyped "targ" l) c isVariadic $ TypeName (Typed l vt) vn (isVariable -> True,vt) -> do return $ DimensionQuantifier (notTyped "targ" l) isVariadic (VarName (Typed l vt) vn) $ fmap (fmap (Typed l)) e otherwise -> do ppcv <- pp cv genError (locpos l) $ text "targ2TemplateQuantifier:" <+> ppcv parg2ProcedureParameter :: ConversionK loc m => loc -> (Bool,Var,IsVariadic) -> TcM m (ProcedureParameter GIdentifier (Typed loc)) parg2ProcedureParameter l (isConst,v,isVariadic) = do let t = if isVariadic then variadicBase (loc v) else loc v t' <- type2TypeSpecifierNonVoid l t return $ ProcedureParameter (Typed l $ loc v) isConst t' isVariadic (fmap (Typed l) v) type2TypeSpecifierNonVoid :: ConversionK loc m => loc -> Type -> TcM m ((TypeSpecifier GIdentifier (Typed loc))) type2TypeSpecifierNonVoid l t = do (mb) <- type2TypeSpecifier l t case mb of Just x -> return (x) Nothing -> genError (locpos l) $ text "type2SizedTypeSpecifier: void type" type2ReturnTypeSpecifier :: ConversionK loc m => loc -> Type -> TcM m (ReturnTypeSpecifier GIdentifier (Typed loc)) type2ReturnTypeSpecifier l t = do mb <- type2TypeSpecifier l t let mbt = maybe (ComplexT Void) (typed . loc) mb return $ ReturnType (Typed l mbt) mb type2TypeSpecifier :: ConversionK loc m => loc -> Type -> TcM m (Maybe (TypeSpecifier GIdentifier (Typed loc))) type2TypeSpecifier l (ComplexT t) = do complexType2TypeSpecifier l t type2TypeSpecifier l b@(BaseT t) = do b' <- baseType2DatatypeSpecifier l t return (Just (TypeSpecifier (Typed l b) Nothing b' Nothing)) type2TypeSpecifier l t = do ppl <- ppr l ppt <- ppr t error $ "type2TypeSpecifier: " ++ ppl ++ " " ++ ppt complexType2TypeSpecifier :: ConversionK loc m => loc -> ComplexType -> TcM m (Maybe (TypeSpecifier GIdentifier (Typed loc))) complexType2TypeSpecifier l ct@(CType s t d) = do s' <- secType2SecTypeSpecifier l s t' <- baseType2DatatypeSpecifier l t return (Just (TypeSpecifier (Typed l $ ComplexT ct) (Just s') t' (Just $ DimSpecifier (Typed l $ BaseT index) $ fmap (Typed l) d))) complexType2TypeSpecifier l Void = return (Nothing) complexType2TypeSpecifier l c@(CVar v _) = do ppc <- pp c genError (locpos l) $ text "complexType2TypeSpecifier" <+> ppc sizes2Sizes :: ConversionK loc m => [(Expr,IsVariadic)] -> TcM m (Sizes GIdentifier (Typed loc)) sizes2Sizes = undefined secType2SecTypeSpecifier :: ConversionK loc m => loc -> SecType -> TcM m (SecTypeSpecifier GIdentifier (Typed loc)) secType2SecTypeSpecifier l s@Public = do return $ PublicSpecifier (Typed l $ SecT s) secType2SecTypeSpecifier l s@(Private d _) = do let tl = Typed l $ SecT s return $ PrivateSpecifier tl $ fmap (const tl) $ DomainName () d secType2SecTypeSpecifier l s@(SVar v _) = do let tl = Typed l $ SecT s return $ PrivateSpecifier tl $ fmap (const tl) (DomainName tl $ VIden v) baseType2DatatypeSpecifier :: ConversionK loc m => loc -> BaseType -> TcM m (DatatypeSpecifier GIdentifier (Typed loc)) baseType2DatatypeSpecifier l b@(TyPrim p) = do let t = Typed l $ BaseT b return $ PrimitiveSpecifier t (fmap (const t) p) baseType2DatatypeSpecifier l b@(TApp n ts d) = do ts' <- fmapFstM (type2TemplateTypeArgument l) ts return $ TemplateSpecifier (Typed l $ BaseT b) (fmap (const $ Typed l $ DecT d) $ TypeName () n) ts' baseType2DatatypeSpecifier l b@(BVar v c) = do let tl = Typed l $ BaseT b return $ VariableSpecifier tl (TypeName tl (VIden v)) baseType2DatatypeSpecifier l t@(MSet b) = do b' <- type2TypeSpecifierNonVoid l $ ComplexT b return $ MultisetSpecifier (Typed l $ BaseT t) b' baseType2DatatypeSpecifier l t@(Set b) = do b' <- type2TypeSpecifierNonVoid l $ ComplexT b return $ SetSpecifier (Typed l $ BaseT t) b' --baseType2DatatypeSpecifier l t = genError (locpos l) $ text "baseType2DatatypeSpecifier:" <+> pp t type2TemplateTypeArgument :: ConversionK loc m => loc -> Type -> TcM m (TemplateTypeArgument GIdentifier (Typed loc)) type2TemplateTypeArgument l s@(SecT Public) = return $ PublicTemplateTypeArgument (Typed l s) type2TemplateTypeArgument l s@(SecT (Private d k)) = do let tl = Typed l s return $ GenericTemplateTypeArgument tl (TemplateArgName tl d) type2TemplateTypeArgument l s@(SecT (SVar v k)) = do let tl = Typed l s return $ GenericTemplateTypeArgument tl (TemplateArgName tl $ VIden v) type2TemplateTypeArgument l (IdxT e) = do let tl = Typed l (loc e) return $ ExprTemplateTypeArgument tl (fmap (Typed l) e) type2TemplateTypeArgument l t@(BaseT (TyPrim p)) = do let tl = Typed noloc t return $ PrimitiveTemplateTypeArgument tl $ fmap (const tl) p type2TemplateTypeArgument l t@(BaseT (TApp n ts d)) = do ts' <- fmapFstM (type2TemplateTypeArgument l) ts return $ TemplateTemplateTypeArgument (Typed l t) (fmap (const $ Typed l $ DecT d) $ TypeName () n) ts' type2TemplateTypeArgument l t@(BaseT (BVar v c)) = do let tl = Typed l t return $ GenericTemplateTypeArgument tl $ (TemplateArgName tl $ VIden v) type2TemplateTypeArgument l t = do ppt <- pp t genError (locpos l) $ text "type2TemplateTypeArgument" <+> ppt
haslab/SecreC
src/Language/SecreC/TypeChecker/Conversion.hs
gpl-3.0
14,274
0
21
2,975
5,927
2,841
3,086
235
9
module Main (main) where import Test.Framework import Test.Framework.Providers.QuickCheck2 import Test.Framework.Providers.HUnit import SimulateTests import CompileTests main :: IO () main = defaultMain tests tests :: [Test] tests = [ testGroup "Simulater" [ testProperty "Converting to and from bits identity" propToBitsFromBitsId ] , testGroup "Compiler" [ testCase "Simple simulation test" simpleTestSim , testProperty "Ancilla are zeroed for unoptimized circuits" propAncillaZero , testProperty "Ancilla are zeroed for Optimized circuits" propAncillaZeroOpt ] ]
aparent/jcc
tests/tests.hs
gpl-3.0
618
0
8
121
113
64
49
19
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.CodeDeploy.ListApplications -- 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. -- | Lists the applications registered within the AWS user account. -- -- <http://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ListApplications.html> module Network.AWS.CodeDeploy.ListApplications ( -- * Request ListApplications -- ** Request constructor , listApplications -- ** Request lenses , laNextToken -- * Response , ListApplicationsResponse -- ** Response constructor , listApplicationsResponse -- ** Response lenses , lar1Applications , lar1NextToken ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.CodeDeploy.Types import qualified GHC.Exts newtype ListApplications = ListApplications { _laNextToken :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'ListApplications' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'laNextToken' @::@ 'Maybe' 'Text' -- listApplications :: ListApplications listApplications = ListApplications { _laNextToken = Nothing } -- | An identifier that was returned from the previous list applications call, -- which can be used to return the next set of applications in the list. laNextToken :: Lens' ListApplications (Maybe Text) laNextToken = lens _laNextToken (\s a -> s { _laNextToken = a }) data ListApplicationsResponse = ListApplicationsResponse { _lar1Applications :: List "applications" Text , _lar1NextToken :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'ListApplicationsResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lar1Applications' @::@ ['Text'] -- -- * 'lar1NextToken' @::@ 'Maybe' 'Text' -- listApplicationsResponse :: ListApplicationsResponse listApplicationsResponse = ListApplicationsResponse { _lar1Applications = mempty , _lar1NextToken = Nothing } -- | A list of application names. lar1Applications :: Lens' ListApplicationsResponse [Text] lar1Applications = lens _lar1Applications (\s a -> s { _lar1Applications = a }) . _List -- | If the amount of information that is returned is significantly large, an -- identifier will also be returned, which can be used in a subsequent list -- applications call to return the next set of applications in the list. lar1NextToken :: Lens' ListApplicationsResponse (Maybe Text) lar1NextToken = lens _lar1NextToken (\s a -> s { _lar1NextToken = a }) instance ToPath ListApplications where toPath = const "/" instance ToQuery ListApplications where toQuery = const mempty instance ToHeaders ListApplications instance ToJSON ListApplications where toJSON ListApplications{..} = object [ "nextToken" .= _laNextToken ] instance AWSRequest ListApplications where type Sv ListApplications = CodeDeploy type Rs ListApplications = ListApplicationsResponse request = post "ListApplications" response = jsonResponse instance FromJSON ListApplicationsResponse where parseJSON = withObject "ListApplicationsResponse" $ \o -> ListApplicationsResponse <$> o .:? "applications" .!= mempty <*> o .:? "nextToken"
dysinger/amazonka
amazonka-codedeploy/gen/Network/AWS/CodeDeploy/ListApplications.hs
mpl-2.0
4,167
0
12
858
524
315
209
60
1
-- ----------------------------------------------------------------------------- -- This file is part of Skema-Common. -- Skema-Common is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- Skema-Common 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 Skema-Common. If not, see <http://www.gnu.org/licenses/>. -- ----------------------------------------------------------------------------- -- | Data Values are haskell types representing Skema Program Types values module Skema.DataValue( DataValue(..), updateDataValue, extractValue, valueToByteString, valuesToByteString, convertToDataValues, convertNValues, dvToIntegral, dvToFloat ) where -- ----------------------------------------------------------------------------- import Data.Word( Word8, Word16, Word32, Word64 ) import Data.Int( Int8, Int16, Int32, Int64 ) import Data.Bits( (.&.), (.|.), shiftR, shiftL ) import Data.Binary.IEEE754( floatToWord, wordToFloat, doubleToWord, wordToDouble ) import GHC.Float( double2Float, float2Double ) import qualified Data.ByteString as B( ByteString, empty, pack, index, singleton, concat, drop, take ) import Skema.Types( IOPointDataType(..), dataTypeBase, dataTypeVectorSize, dataTypeSize ) -- ----------------------------------------------------------------------------- -- | Value with a corresponding OpenCL Type data DataValue = DVchar Int8 | DVuchar Word8 | DVshort Int16 | DVushort Word16 | DVint Int32 | DVuint Word32 | DVlong Int64 | DVulong Word64 | DVfloat Float | DVdouble Double deriving( Show ) -- ----------------------------------------------------------------------------- -- | put a real value into a `DataValue`, converting to the same type. updateDataValue :: Double -- ^ New value. -> DataValue -- ^ Type to convert to. -> DataValue updateDataValue d (DVchar _) = DVchar $ round d updateDataValue d (DVuchar _) = DVuchar $ round d updateDataValue d (DVshort _) = DVshort $ round d updateDataValue d (DVushort _) = DVushort $ round d updateDataValue d (DVint _) = DVint $ round d updateDataValue d (DVuint _) = DVuint $ round d updateDataValue d (DVlong _) = DVlong $ round d updateDataValue d (DVulong _) = DVulong $ round d updateDataValue d (DVfloat _) = DVfloat $ double2Float d updateDataValue d (DVdouble _) = DVdouble d -- ----------------------------------------------------------------------------- -- | get a real value from a `DataValue`, converting it to `Double`. extractValue :: DataValue -> Double extractValue (DVchar v) = fromIntegral v extractValue (DVuchar v) = fromIntegral v extractValue (DVshort v) = fromIntegral v extractValue (DVushort v) = fromIntegral v extractValue (DVint v) = fromIntegral v extractValue (DVuint v) = fromIntegral v extractValue (DVlong v) = fromIntegral v extractValue (DVulong v) = fromIntegral v extractValue (DVfloat v) = float2Double v extractValue (DVdouble v) = v -- ----------------------------------------------------------------------------- -- | Numerical Type convertible to a ByteString, in Big Endian or Little Endian. class Num a => ToByteString a where toByteString_le, toByteString_be :: a -> B.ByteString toByteString_le = const B.empty toByteString_be = const B.empty fromByteString_le, fromByteString_be :: B.ByteString -> a fromByteString_le = const 0 fromByteString_be = const 0 instance ToByteString Int8 where toByteString_le = B.singleton . fromIntegral toByteString_be = toByteString_le fromByteString_le = fromIntegral . (`B.index` 0) fromByteString_be = fromByteString_le instance ToByteString Word8 where toByteString_le = B.singleton toByteString_be = toByteString_le fromByteString_le = (`B.index` 0) fromByteString_be = fromByteString_le instance ToByteString Int16 where toByteString_le w = B.pack [a,b] where a = fromIntegral $ (w .&. 0xff) b = fromIntegral $ (w .&. 0xff00) `shiftR` 8 toByteString_be w = B.pack [b,a] where a = fromIntegral $ (w .&. 0xff) b = fromIntegral $ (w .&. 0xff00) `shiftR` 8 fromByteString_le w = a .|. b where a = fromIntegral $ w `B.index` 0 b = (fromIntegral $ w `B.index` 1) `shiftL` 8 fromByteString_be w = a .|. b where a = fromIntegral $ w `B.index` 1 b = (fromIntegral $ w `B.index` 0) `shiftL` 8 instance ToByteString Word16 where toByteString_le w = B.pack [a,b] where a = fromIntegral $ (w .&. 0xff) b = fromIntegral $ (w .&. 0xff00) `shiftR` 8 toByteString_be w = B.pack [b,a] where a = fromIntegral $ (w .&. 0xff) b = fromIntegral $ (w .&. 0xff00) `shiftR` 8 fromByteString_le w = a .|. b where a = fromIntegral $ w `B.index` 0 b = (fromIntegral $ w `B.index` 1) `shiftL` 8 fromByteString_be w = a .|. b where a = fromIntegral $ w `B.index` 1 b = (fromIntegral $ w `B.index` 0) `shiftL` 8 instance ToByteString Int32 where toByteString_le w = B.pack [a,b,c,d] where a = fromIntegral $ (w .&. 0xff) b = fromIntegral $ (w .&. 0xff00) `shiftR` 8 c = fromIntegral $ (w .&. 0xff0000) `shiftR` 16 d = fromIntegral $ (w .&. 0xff000000) `shiftR` 24 toByteString_be w = B.pack [d,c,b,a] where a = fromIntegral $ (w .&. 0xff) b = fromIntegral $ (w .&. 0xff00) `shiftR` 8 c = fromIntegral $ (w .&. 0xff0000) `shiftR` 16 d = fromIntegral $ (w .&. 0xff000000) `shiftR` 24 fromByteString_le w = a .|. b .|. c .|. d where a = fromIntegral $ w `B.index` 0 b = (fromIntegral $ w `B.index` 1) `shiftL` 8 c = (fromIntegral $ w `B.index` 2) `shiftL` 16 d = (fromIntegral $ w `B.index` 3) `shiftL` 24 fromByteString_be w = a .|. b .|. c .|. d where a = fromIntegral $ w `B.index` 3 b = (fromIntegral $ w `B.index` 2) `shiftL` 8 c = (fromIntegral $ w `B.index` 1) `shiftL` 16 d = (fromIntegral $ w `B.index` 0) `shiftL` 24 instance ToByteString Word32 where toByteString_le w = B.pack [a,b,c,d] where a = fromIntegral $ (w .&. 0xff) b = fromIntegral $ (w .&. 0xff00) `shiftR` 8 c = fromIntegral $ (w .&. 0xff0000) `shiftR` 16 d = fromIntegral $ (w .&. 0xff000000) `shiftR` 24 toByteString_be w = B.pack [d,c,b,a] where a = fromIntegral $ (w .&. 0xff) b = fromIntegral $ (w .&. 0xff00) `shiftR` 8 c = fromIntegral $ (w .&. 0xff0000) `shiftR` 16 d = fromIntegral $ (w .&. 0xff000000) `shiftR` 24 fromByteString_le w = a .|. b .|. c .|. d where a = fromIntegral $ w `B.index` 0 b = (fromIntegral $ w `B.index` 1) `shiftL` 8 c = (fromIntegral $ w `B.index` 2) `shiftL` 16 d = (fromIntegral $ w `B.index` 3) `shiftL` 24 fromByteString_be w = a .|. b .|. c .|. d where a = fromIntegral $ w `B.index` 3 b = (fromIntegral $ w `B.index` 2) `shiftL` 8 c = (fromIntegral $ w `B.index` 1) `shiftL` 16 d = (fromIntegral $ w `B.index` 0) `shiftL` 24 instance ToByteString Word64 where toByteString_le w = B.pack [a,b,c,d,e,f,g,h] where a = fromIntegral $ (w .&. 0xff) b = fromIntegral $ (w .&. 0xff00) `shiftR` 8 c = fromIntegral $ (w .&. 0xff0000) `shiftR` 16 d = fromIntegral $ (w .&. 0xff000000) `shiftR` 24 e = fromIntegral $ (w .&. 0xff00000000) `shiftR` 32 f = fromIntegral $ (w .&. 0xff0000000000) `shiftR` 40 g = fromIntegral $ (w .&. 0xff000000000000) `shiftR` 48 h = fromIntegral $ (w .&. 0xff00000000000000) `shiftR` 56 toByteString_be w = B.pack [h,g,f,e,d,c,b,a] where a = fromIntegral $ (w .&. 0xff) b = fromIntegral $ (w .&. 0xff00) `shiftR` 8 c = fromIntegral $ (w .&. 0xff0000) `shiftR` 16 d = fromIntegral $ (w .&. 0xff000000) `shiftR` 24 e = fromIntegral $ (w .&. 0xff00000000) `shiftR` 32 f = fromIntegral $ (w .&. 0xff0000000000) `shiftR` 40 g = fromIntegral $ (w .&. 0xff000000000000) `shiftR` 48 h = fromIntegral $ (w .&. 0xff00000000000000) `shiftR` 56 fromByteString_le w = a .|. b .|. c .|. d .|. e .|. f .|. g .|. h where a = fromIntegral $ w `B.index` 0 b = (fromIntegral $ w `B.index` 1) `shiftL` 8 c = (fromIntegral $ w `B.index` 2) `shiftL` 16 d = (fromIntegral $ w `B.index` 3) `shiftL` 24 e = (fromIntegral $ w `B.index` 4) `shiftL` 32 f = (fromIntegral $ w `B.index` 5) `shiftL` 40 g = (fromIntegral $ w `B.index` 6) `shiftL` 48 h = (fromIntegral $ w `B.index` 7) `shiftL` 56 fromByteString_be w = a .|. b .|. c .|. d .|. e .|. f .|. g .|. h where a = fromIntegral $ w `B.index` 7 b = (fromIntegral $ w `B.index` 6) `shiftL` 8 c = (fromIntegral $ w `B.index` 5) `shiftL` 16 d = (fromIntegral $ w `B.index` 4) `shiftL` 24 e = (fromIntegral $ w `B.index` 3) `shiftL` 32 f = (fromIntegral $ w `B.index` 2) `shiftL` 40 g = (fromIntegral $ w `B.index` 1) `shiftL` 48 h = (fromIntegral $ w `B.index` 0) `shiftL` 56 instance ToByteString Int64 where toByteString_le w = B.pack [a,b,c,d,e,f,g,h] where a = fromIntegral $ (w .&. 0xff) b = fromIntegral $ (w .&. 0xff00) `shiftR` 8 c = fromIntegral $ (w .&. 0xff0000) `shiftR` 16 d = fromIntegral $ (w .&. 0xff000000) `shiftR` 24 e = fromIntegral $ (w .&. 0xff00000000) `shiftR` 32 f = fromIntegral $ (w .&. 0xff0000000000) `shiftR` 40 g = fromIntegral $ (w .&. 0xff000000000000) `shiftR` 48 h = fromIntegral $ (w .&. 0xff00000000000000) `shiftR` 56 toByteString_be w = B.pack [h,g,f,e,d,c,b,a] where a = fromIntegral $ (w .&. 0xff) b = fromIntegral $ (w .&. 0xff00) `shiftR` 8 c = fromIntegral $ (w .&. 0xff0000) `shiftR` 16 d = fromIntegral $ (w .&. 0xff000000) `shiftR` 24 e = fromIntegral $ (w .&. 0xff00000000) `shiftR` 32 f = fromIntegral $ (w .&. 0xff0000000000) `shiftR` 40 g = fromIntegral $ (w .&. 0xff000000000000) `shiftR` 48 h = fromIntegral $ (w .&. 0xff00000000000000) `shiftR` 56 fromByteString_le w = a .|. b .|. c .|. d .|. e .|. f .|. g .|. h where a = fromIntegral $ w `B.index` 0 b = (fromIntegral $ w `B.index` 1) `shiftL` 8 c = (fromIntegral $ w `B.index` 2) `shiftL` 16 d = (fromIntegral $ w `B.index` 3) `shiftL` 24 e = (fromIntegral $ w `B.index` 4) `shiftL` 32 f = (fromIntegral $ w `B.index` 5) `shiftL` 40 g = (fromIntegral $ w `B.index` 6) `shiftL` 48 h = (fromIntegral $ w `B.index` 7) `shiftL` 56 fromByteString_be w = a .|. b .|. c .|. d .|. e .|. f .|. g .|. h where a = fromIntegral $ w `B.index` 7 b = (fromIntegral $ w `B.index` 6) `shiftL` 8 c = (fromIntegral $ w `B.index` 5) `shiftL` 16 d = (fromIntegral $ w `B.index` 4) `shiftL` 24 e = (fromIntegral $ w `B.index` 3) `shiftL` 32 f = (fromIntegral $ w `B.index` 2) `shiftL` 40 g = (fromIntegral $ w `B.index` 1) `shiftL` 48 h = (fromIntegral $ w `B.index` 0) `shiftL` 56 instance ToByteString Float where toByteString_le = toByteString_le . floatToWord toByteString_be = toByteString_be . floatToWord fromByteString_le = wordToFloat . fromByteString_le fromByteString_be = wordToFloat . fromByteString_be instance ToByteString Double where toByteString_le = toByteString_le . doubleToWord toByteString_be = toByteString_be . doubleToWord fromByteString_le = wordToDouble . fromByteString_le fromByteString_be = wordToDouble . fromByteString_be -- ----------------------------------------------------------------------------- -- | Pack a `DataValue` into a ByteString. valueToByteString :: DataValue -> B.ByteString valueToByteString (DVchar v) = toByteString_le v valueToByteString (DVuchar v) = toByteString_le v valueToByteString (DVshort v) = toByteString_le v valueToByteString (DVushort v) = toByteString_le v valueToByteString (DVint v) = toByteString_le v valueToByteString (DVuint v) = toByteString_le v valueToByteString (DVlong v) = toByteString_le v valueToByteString (DVulong v) = toByteString_le v valueToByteString (DVfloat v) = toByteString_le v valueToByteString (DVdouble v) = toByteString_le v -- ----------------------------------------------------------------------------- -- | Pack a `DataValue` list into a ByteString. valuesToByteString :: [DataValue] -> B.ByteString valuesToByteString = B.concat . map valueToByteString -- ----------------------------------------------------------------------------- -- | Extract from a ByteString the `DataValue`. convertToDataValues :: B.ByteString -> IOPointDataType -- ^ Type to extract. -> [DataValue] convertToDataValues b IOchar = [DVchar $ fromByteString_le b] convertToDataValues b IOuchar = [DVuchar $ fromByteString_le b] convertToDataValues b IOshort = [DVshort $ fromByteString_le b] convertToDataValues b IOushort = [DVushort $ fromByteString_le b] convertToDataValues b IOint = [DVint $ fromByteString_le b] convertToDataValues b IOuint = [DVuint $ fromByteString_le b] convertToDataValues b IOlong = [DVlong $ fromByteString_le b] convertToDataValues b IOulong = [DVulong $ fromByteString_le b] convertToDataValues b IOfloat = [DVfloat $ fromByteString_le b] convertToDataValues b IOdouble = [DVdouble $ fromByteString_le b] convertToDataValues b t = convertNValues b (dataTypeBase t) (dataTypeVectorSize t) -- | Extract n `DataValue` elements from a ByteString. convertNValues :: B.ByteString -> IOPointDataType -- ^ Type to extract. -> Int -- ^ Number of elements to extract. -> [DataValue] convertNValues b t n = concatMap (\x-> convertToDataValues x t) $ map (B.take (dataTypeSize t)) $ take n $ iterate (B.drop (dataTypeSize t)) b -- ----------------------------------------------------------------------------- -- | Convert `DataValue` to Integral type. dvToIntegral :: Integral a => DataValue -> a dvToIntegral (DVchar v) = fromIntegral v dvToIntegral (DVuchar v) = fromIntegral v dvToIntegral (DVshort v) = fromIntegral v dvToIntegral (DVushort v) = fromIntegral v dvToIntegral (DVint v) = fromIntegral v dvToIntegral (DVuint v) = fromIntegral v dvToIntegral (DVlong v) = fromIntegral v dvToIntegral (DVulong v) = fromIntegral v dvToIntegral (DVfloat v) = round v dvToIntegral (DVdouble v) = round v -- | Conversion to `Float`. dvToFloat :: DataValue -> Float dvToFloat (DVchar v) = fromIntegral v dvToFloat (DVuchar v) = fromIntegral v dvToFloat (DVshort v) = fromIntegral v dvToFloat (DVushort v) = fromIntegral v dvToFloat (DVint v) = fromIntegral v dvToFloat (DVuint v) = fromIntegral v dvToFloat (DVlong v) = fromIntegral v dvToFloat (DVulong v) = fromIntegral v dvToFloat (DVfloat v) = v dvToFloat (DVdouble v) = double2Float v -- -----------------------------------------------------------------------------
SkemaPlatform/skema-common
src/Skema/DataValue.hs
agpl-3.0
15,418
0
12
3,400
5,074
2,857
2,217
268
1
-- GSoC 2015 - Haskell bindings for OpenCog. {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DataKinds #-} -- | This Module defines the main functions to interact with the AtomSpace -- creating/removing/modifying atoms. module OpenCog.AtomSpace.Api ( insert , remove , get , debug , getByUUID , getWithUUID , execute , evaluate , exportFunction ) where import Foreign (Ptr) import Foreign.C.Types (CULong(..),CInt(..),CDouble(..)) import Foreign.C.String (CString,withCString,peekCString) import Foreign.Marshal.Array (withArray,allocaArray,peekArray) import Foreign.Marshal.Utils (toBool) import Foreign.Marshal.Alloc (alloca,free) import Foreign.Storable (peek) import Data.Functor ((<$>)) import Data.Typeable (Typeable) import Data.Maybe (fromJust) import Control.Monad.Trans.Reader (ReaderT,runReaderT,ask) import Control.Monad.IO.Class (liftIO) import OpenCog.AtomSpace.Env (AtomSpaceObj(..),AtomSpaceRef(..),(<:), AtomSpace(..),getAtomSpace,refToObj) import OpenCog.AtomSpace.Internal (toTVRaw,fromTVRaw,UUID,TVRaw(..),tvMAX_PARAMS) import OpenCog.AtomSpace.Types (Atom(..),AtomType(..),AtomName(..),TruthVal(..)) import OpenCog.AtomSpace.CUtils sUCCESS :: CInt sUCCESS = 0 -------------------------------------------------------------------------------- foreign import ccall "AtomSpace_debug" c_atomspace_debug :: AtomSpaceRef -> IO () -- | 'debug' prints the state of the AtomSpace on stderr. -- (only for debugging purposes) debug :: AtomSpace () debug = do asRef <- getAtomSpace liftIO $ c_atomspace_debug asRef -------------------------------------------------------------------------------- foreign import ccall "AtomSpace_addNode" c_atomspace_addnode :: AtomSpaceRef -> CString -> CString -> Ptr UUID -> IO CInt insertNode :: AtomType -> AtomName -> AtomSpace (Maybe UUID) insertNode aType aName = do asRef <- getAtomSpace liftIO $ withCString aType $ \atype -> withCString aName $ \aname -> alloca $ \uptr -> do res <- c_atomspace_addnode asRef atype aname uptr if res == sUCCESS then do uuid <- peek uptr return $ Just uuid else return Nothing foreign import ccall "AtomSpace_addLink" c_atomspace_addlink :: AtomSpaceRef -> CString -> Ptr UUID -> CInt -> Ptr UUID -> IO CInt insertLink :: AtomType -> [Atom] -> AtomSpace (Maybe UUID) insertLink aType aOutgoing = do mlist <- mapM insertAndGetUUID aOutgoing case mapM id mlist of Nothing -> return Nothing Just list -> do asRef <- getAtomSpace liftIO $ withCString aType $ \atype -> withArray list $ \lptr -> alloca $ \uptr -> do res <- c_atomspace_addlink asRef atype lptr (fromIntegral $ length list) uptr if res == sUCCESS then do uuid <- peek uptr return $ Just uuid else return Nothing insertAndGetUUID :: Atom -> AtomSpace (Maybe UUID) insertAndGetUUID i = case i of Node aType aName tv -> do h <- insertNode aType aName case h of -- set truth value after inserting. Just hand -> setTruthValue hand tv _ -> return False return h Link aType aOutgoing tv -> do h <- insertLink aType aOutgoing case h of -- set truth value after inserting. Just hand -> setTruthValue hand tv _ -> return False return h -- | 'insert' creates a new atom on the atomspace or updates the existing one. insert :: Atom -> AtomSpace () insert i = insertAndGetUUID i >> return () -------------------------------------------------------------------------------- foreign import ccall "AtomSpace_removeAtom" c_atomspace_remove :: AtomSpaceRef -> UUID -> IO CInt -- | 'remove' deletes an atom from the atomspace. -- Returns True in success or False if it couldn't locate the specified atom. remove :: Atom -> AtomSpace Bool remove i = do asRef <- getAtomSpace m <- getWithUUID i case m of Just (_,handle) -> liftIO $ (==) sUCCESS <$> c_atomspace_remove asRef handle _ -> return False -------------------------------------------------------------------------------- foreign import ccall "AtomSpace_getNode" c_atomspace_getnode :: AtomSpaceRef -> CString -> CString -> Ptr UUID -> IO CInt getNodeUUID :: AtomType -> AtomName -> AtomSpace (Maybe UUID) getNodeUUID aType aName = do asRef <- getAtomSpace liftIO $ withCString aType $ \atype -> withCString aName $ \aname -> alloca $ \hptr -> do res <- c_atomspace_getnode asRef atype aname hptr let found = res == sUCCESS h <- peek hptr return $ if found then Just h else Nothing getNode :: AtomType -> AtomName -> AtomSpace (Maybe (TruthVal,UUID)) getNode aType aName = do m <- getNodeUUID aType aName case m of Nothing -> return Nothing Just h -> do asRef <- getAtomSpace res <- liftIO $ getTruthValue asRef h return $ case res of Just tv -> Just (tv,h) Nothing -> Nothing foreign import ccall "AtomSpace_getLink" c_atomspace_getlink :: AtomSpaceRef -> CString -> Ptr UUID -> CInt -> Ptr UUID -> IO CInt getLinkUUID :: AtomType -> [UUID] -> AtomSpace (Maybe UUID) getLinkUUID aType aOutgoing = do asRef <- getAtomSpace liftIO $ withCString aType $ \atype -> withArray aOutgoing $ \lptr -> alloca $ \hptr -> do res <- c_atomspace_getlink asRef atype lptr (fromIntegral $ length aOutgoing) hptr let found = res == sUCCESS h <- peek hptr return $ if found then Just h else Nothing getLink :: AtomType -> [UUID] -> AtomSpace (Maybe (TruthVal,UUID)) getLink aType aOutgoing = do m <- getLinkUUID aType aOutgoing case m of Nothing -> return Nothing Just h -> do asRef <- getAtomSpace res <- liftIO $ getTruthValue asRef h return $ case res of Just tv -> Just (tv,h) Nothing -> Nothing getWithUUID :: Atom -> AtomSpace (Maybe (Atom,UUID)) getWithUUID i = do let onLink :: AtomType -> [Atom] -> AtomSpace (Maybe (TruthVal,UUID,[Atom])) onLink aType aOutgoing = do ml <- sequence <$> mapM getWithUUID aOutgoing case ml of -- ml :: Maybe [(AtomRaw,UUID)] Nothing -> return Nothing Just l -> do res <- getLink aType $ map snd l case res of Just (tv,h) -> return $ Just (tv,h,map fst l) _ -> return Nothing in case i of Node aType aName _ -> do m <- getNode aType aName return $ case m of Just (tv,h) -> Just $ (Node aType aName tv,h) _ -> Nothing Link aType aOutgoing _ -> do m <- onLink aType aOutgoing return $ case m of Just (tv,h,newOutgoing) -> Just $ (Link aType newOutgoing tv, h) _ -> Nothing -- | 'get' looks for an atom in the atomspace and returns it. -- (With updated mutable information) get :: Atom -> AtomSpace (Maybe Atom) get i = do m <- getWithUUID i return $ case m of Just (araw,_) -> Just araw _ -> Nothing -------------------------------------------------------------------------------- foreign import ccall "Exec_execute" c_exec_execute :: AtomSpaceRef -> UUID -> IO UUID execute :: Atom -> AtomSpace (Maybe Atom) execute atom = do m <- getWithUUID atom case m of Just (_,handle) -> do asRef <- getAtomSpace res <- liftIO $ c_exec_execute asRef handle resAtom <- getByUUID res return resAtom _ -> return Nothing foreign import ccall "Exec_evaluate" c_exec_evaluate :: AtomSpaceRef -> UUID -> Ptr CInt -> Ptr CDouble -> IO CInt evaluate :: Atom -> AtomSpace (Maybe TruthVal) evaluate atom = do m <- getWithUUID atom case m of Just (_,handle) -> do asRef <- getAtomSpace res <- liftIO $ getTVfromC $ c_exec_evaluate asRef handle return $ res _ -> return Nothing -------------------------------------------------------------------------------- foreign import ccall "AtomSpace_getAtomByUUID" c_atomspace_getAtomByUUID :: AtomSpaceRef -> UUID -> Ptr CInt -> Ptr CString -> Ptr CString -> Ptr (Ptr UUID) -> Ptr CInt -> IO CInt getByUUID :: UUID -> AtomSpace (Maybe Atom) getByUUID h = do asRef <- getAtomSpace resTv <- liftIO $ getTruthValue asRef h case resTv of Nothing -> return Nothing Just tv -> do res <- liftIO $ alloca $ \aptr -> alloca $ \tptr -> alloca $ \nptr -> alloca $ \hptr -> alloca $ \iptr -> do res <- c_atomspace_getAtomByUUID asRef h aptr tptr nptr hptr iptr if res /= sUCCESS then return Nothing else do isNode <- toBool <$> peek aptr ctptr <- peek tptr atype <- peekCString ctptr free ctptr if isNode then do cnptr <- peek nptr aname <- peekCString cnptr free cnptr return $ Just $ Right (atype,aname) else do outLen <- fromIntegral <$> peek iptr chptr <- peek hptr outList <- peekArray outLen chptr free chptr return $ Just $ Left (atype,outList) case res of Nothing -> return Nothing Just (Right (atype,aname)) -> return $ Just $ Node atype aname tv Just (Left (atype,outList)) -> do mout <- mapM getByUUID outList return $ case mapM id mout of Just out -> Just $ Link atype out tv Nothing -> Nothing -------------------------------------------------------------------------------- foreign import ccall "AtomSpace_getTruthValue" c_atomspace_getTruthValue :: AtomSpaceRef -> UUID -> Ptr CInt -> Ptr CDouble -> IO CInt -- Internal function to get an atom's truth value. getTruthValue :: AtomSpaceRef -> UUID -> IO (Maybe TruthVal) getTruthValue asRef handle = do liftIO $ getTVfromC $ c_atomspace_getTruthValue asRef handle foreign import ccall "AtomSpace_setTruthValue" c_atomspace_setTruthValue :: AtomSpaceRef -> UUID -> CInt -> Ptr CDouble -> IO CInt -- Internal function to set an atom's truth value. setTruthValue :: UUID -> TruthVal -> AtomSpace Bool setTruthValue handle tv = do let (TVRaw tvtype list) = toTVRaw tv asRef <- getAtomSpace liftIO $ withArray (map realToFrac list) $ \lptr -> do res <- c_atomspace_setTruthValue asRef handle (fromIntegral $ fromEnum tvtype) lptr return $ res == sUCCESS -- Helpfer function for creating function that can be called from C exportFunction :: (Atom -> AtomSpace (Atom)) -> Ptr AtomSpaceRef -> UUID -> IO (UUID) exportFunction f asRef id = do as <- refToObj asRef (Just atom) <- as <: getByUUID id let (AtomSpace op) = f atom resAtom <- runReaderT op (AtomSpaceRef asRef) (Just resID) <- as <: insertAndGetUUID resAtom return resID
ceefour/atomspace
opencog/haskell/OpenCog/AtomSpace/Api.hs
agpl-3.0
13,025
0
34
4,830
3,322
1,649
1,673
312
7
module Main where import System.Environment import Sum import Nope import PhhhbbtttEither import Identity import List main :: IO () main = getArgs >>= checkBasedOnArgs checkBasedOnArgs :: [String] -> IO () checkBasedOnArgs ("Sum":_) = checkSum checkBasedOnArgs ("Nope":_) = checkNope checkBasedOnArgs ("PhhhbbtttEither":_) = checkPhhhbbtttEither checkBasedOnArgs ("Identity":_) = checkIdentityEither checkBasedOnArgs ("List":_) = checkListEither checkBasedOnArgs (x:_) = do putStrLn $ "First argument '" ++ x ++ "' didn't match a check." putStrLn $ "Try one of the following:\n Sum\n Nope\n PhhhbbtttEither\n List" checkBasedOnArgs [] = do putStrLn "Enter one of these test names as argument:" putStrLn " Sum" putStrLn " Nope" putStrLn " PhhhbbtttEither" putStrLn " Identity" putStrLn " List"
dmp1ce/Haskell-Programming-Exercises
Chapter 18/MonadInstances/app/Main.hs
unlicense
817
0
9
130
218
110
108
25
1
module Mdb.Types ( FileId, PersonId, AlbumId, SerialId, SeasonId, EpisodeId, TagId ) where import Data.Int (Int64) type FileId = Int64 type AlbumId = Int64 type PersonId = Int64 type SerialId = Int64 type SeasonId = Int64 type EpisodeId = Int64 type TagId = Int64
waldheinz/mdb
src/lib/Mdb/Types.hs
apache-2.0
319
0
5
98
81
53
28
14
0
{- | Module : Data.DRS.Variables Copyright : (c) Harm Brouwer and Noortje Venhuizen License : Apache-2.0 Maintainer : me@hbrouwer.eu, n.j.venhuizen@rug.nl Stability : provisional Portability : portable DRS variables -} module Data.DRS.Variables ( -- * Conversion drsRefToDRSVar , drsRelToString -- * New Variables , newDRSRefs -- * Variable Collections , drsUniverses , drsVariables , drsLambdas ) where import Data.Char (isDigit) import Data.DRS.DataType import Data.List (sortBy, union) import Data.Ord (comparing) --------------------------------------------------------------------------- -- * Exported --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- ** Conversion --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- | Converts a 'DRSRef' @r@ into a 'DRSVar'. --------------------------------------------------------------------------- drsRefToDRSVar :: DRSRef -> DRSVar drsRefToDRSVar (LambdaDRSRef ((r,_),_)) = r drsRefToDRSVar (DRSRef r) = r --------------------------------------------------------------------------- -- | Converts a 'DRSRef' @r@ into a 'DRSVar'. --------------------------------------------------------------------------- drsRelToString :: DRSRel -> String drsRelToString (LambdaDRSRel ((r,_),_)) = r drsRelToString (DRSRel r) = r --------------------------------------------------------------------------- -- ** New Variables --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- | Returns a list of new 'DRSRef's, based on a list of old 'DRSRef's and -- a list of existing 'DRSRef's. --------------------------------------------------------------------------- newDRSRefs :: [DRSRef] -> [DRSRef] -> [DRSRef] newDRSRefs [] _ = [] newDRSRefs (r:ors) ers | r' `elem` (ors `union` ers) = newDRSRefs (r':ors) ers | otherwise = r':newDRSRefs ors (r':ers) where r' = case r of (LambdaDRSRef ((dv,dvs),lp)) -> LambdaDRSRef ((increase dv,dvs),lp) (DRSRef dv) -> DRSRef (increase dv) --------------------------------------------------------------------------- -- ** Variable Collections --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- | Returns the list of 'DRSRef's from all universes in a 'DRS'. --------------------------------------------------------------------------- drsUniverses :: DRS -> [DRSRef] drsUniverses (LambdaDRS _) = [] drsUniverses (Merge d1 d2) = drsUniverses d1 ++ drsUniverses d2 drsUniverses (DRS u c) = u ++ universes c where universes :: [DRSCon] -> [DRSRef] universes [] = [] universes (Rel _ _:cs) = universes cs universes (Neg d1:cs) = drsUniverses d1 ++ universes cs universes (Imp d1 d2:cs) = drsUniverses d1 ++ drsUniverses d2 ++ universes cs universes (Or d1 d2:cs) = drsUniverses d1 ++ drsUniverses d2 ++ universes cs universes (Prop _ d1:cs) = drsUniverses d1 ++ universes cs universes (Diamond d1:cs) = drsUniverses d1 ++ universes cs universes (Box d1:cs) = drsUniverses d1 ++ universes cs --------------------------------------------------------------------------- -- | Returns the list of all 'DRSRef's in a 'DRS' (equals 'drsUniverses' -- ++ 'drsFreeRefs'). --------------------------------------------------------------------------- drsVariables :: DRS -> [DRSRef] drsVariables (LambdaDRS _) = [] drsVariables (Merge d1 d2) = drsVariables d1 `union` drsVariables d2 drsVariables (DRS u c) = u `union` variables c where variables :: [DRSCon] -> [DRSRef] variables [] = [] variables (Rel _ d:cs) = d `union` variables cs variables (Neg d1:cs) = drsVariables d1 `union` variables cs variables (Imp d1 d2:cs) = drsVariables d1 `union` drsVariables d2 `union` variables cs variables (Or d1 d2:cs) = drsVariables d1 `union` drsVariables d2 `union` variables cs variables (Prop r d1:cs) = [r] `union` drsVariables d1 `union` variables cs variables (Diamond d1:cs) = drsVariables d1 `union` variables cs variables (Box d1:cs) = drsVariables d1 `union` variables cs --------------------------------------------------------------------------- -- | Returns the ordered list of all lambda variables in a 'DRS'. --------------------------------------------------------------------------- drsLambdas :: DRS -> [(DRSVar,[DRSVar])] drsLambdas d = map fst (sortBy (comparing snd) (lambdas d)) --------------------------------------------------------------------------- -- * Private --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- | Returns the list of all lambda tuples in a 'DRS'. --------------------------------------------------------------------------- lambdas :: DRS -> [((DRSVar,[DRSVar]),Int)] lambdas (LambdaDRS lt) = [lt] lambdas (Merge d1 d2) = lambdas d1 `union` lambdas d2 lambdas (DRS u c) = lamRefs u `union` lamCons c where lamRefs :: [DRSRef] -> [((DRSVar,[DRSVar]),Int)] lamRefs [] = [] lamRefs (DRSRef _:ds) = lamRefs ds lamRefs (LambdaDRSRef lt:ds) = lt : lamRefs ds lamCons :: [DRSCon] -> [((DRSVar,[DRSVar]),Int)] lamCons [] = [] lamCons (Rel r d:cs) = lamRel r `union` lamRefs d `union` lamCons cs lamCons (Neg d1:cs) = lambdas d1 `union` lamCons cs lamCons (Imp d1 d2:cs) = lambdas d1 `union` lambdas d2 `union` lamCons cs lamCons (Or d1 d2:cs) = lambdas d1 `union` lambdas d2 `union` lamCons cs lamCons (Prop r d1:cs) = lamRefs [r] `union` lambdas d1 `union` lamCons cs lamCons (Diamond d1:cs) = lambdas d1 `union` lamCons cs lamCons (Box d1:cs) = lambdas d1 `union` lamCons cs lamRel :: DRSRel -> [((DRSVar,[DRSVar]),Int)] lamRel (LambdaDRSRel lt) = [lt] lamRel (DRSRel _) = [] --------------------------------------------------------------------------- -- | Increases the index of a 'DRSVar' by 1, or adds an index to it. --------------------------------------------------------------------------- increase :: DRSVar -> DRSVar increase v = reverse (dropWhile isDigit (reverse v)) ++ i where i = case index v of Nothing -> show (1 :: Int) Just n -> show (n + 1) index :: DRSVar -> Maybe Int index v' | i' == "" = Nothing | otherwise = Just $ read i' where i' = reverse (takeWhile isDigit (reverse v'))
hbrouwer/pdrt-sandbox
src/Data/DRS/Variables.hs
apache-2.0
7,009
0
13
1,375
1,822
971
851
84
11
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-} module Types ( Game , Model , readGamesFromCsv , team1 , team2 , result , gameID , gameOdds )where import Control.Applicative ( (<$>), (<*>) ) import Control.Lens hiding ( (.=) ) import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString as B import Data.ByteString.Char8 ( pack ) import Data.Csv ( decodeByName , FromNamedRecord(..) , (.:) ) import qualified Data.HashMap.Strict as M import qualified Data.Vector as V import TrueSkill ( Player , Result(..) ) type Model d = M.HashMap String (Player d) data Game = Game { _team1 :: ![String] , _team2 :: ![String] , _result :: !Result , _gameOdds :: !(Double, Double, Double) , _gameID :: !String } deriving Show makeLenses ''Game instance FromNamedRecord Game where parseNamedRecord m = do goalsHome <- m.: "Goals_Home" goalsGuest <- m.: "Goals_Guest" let lookupPlayers base = mapM (\p -> m .: (base `B.append` (pack $ show p))) ([1..11] :: [Int]) teamHome <- lookupPlayers "Player_Home_Name_" teamGuest <- lookupPlayers "Player_Guest_Name_" -- teamHome <- (:[]) <$> m.: "Home" -- teamGuest <- (:[]) <$> m.: "Guest" odds <- (,,) <$> m .: "OddsMeanH" <*> m .: "OddsMeanD" <*> m .: "OddsMeanA" Game teamHome teamGuest (Result (goalsHome, goalsGuest)) odds <$> m.: "Game_ID" readGamesFromCsv :: FilePath -> IO (Either String (V.Vector Game)) readGamesFromCsv path =BL.readFile path >>= (\f -> return $ snd <$> decodeByName f)
mkiefel/trueskill
Types.hs
bsd-2-clause
1,827
0
19
602
488
280
208
53
1
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell, QuasiQuotes #-} {-# LANGUAGE OverloadedStrings #-} -- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings ( hamletFile , cassiusFile , juliusFile , luciusFile , textFile , widgetFile , ConnectionPool , withConnectionPool , runConnectionPool , staticRoot , staticDir ) where import qualified Text.Hamlet as S import qualified Text.Cassius as S import qualified Text.Julius as S import qualified Text.Lucius as S import qualified Text.Shakespeare.Text as S import Text.Shakespeare.Text (st) import Language.Haskell.TH.Syntax import Database.Persist.Postgresql import Database.Persist.Base (loadConfig) import Yesod (liftIO, MonadControlIO, addWidget, addCassius, addJulius, addLucius, whamletFile, withYamlEnvironment) import Data.Monoid (mempty) import System.Directory (doesFileExist) import Data.Text (Text) import Prelude hiding (concat) import Yesod.Default.Config (AppConfig (..), DefaultEnv) -- Static setting below. Changing these requires a recompile -- | The location of static files on your system. This is a file system -- path. The default value works properly with your scaffolded site. staticDir :: FilePath staticDir = "static" -- | The base URL for your static files. As you can see by the default -- value, this can simply be "static" appended to your application root. -- A powerful optimization can be serving static files from a separate -- domain name. This allows you to use a web server optimized for static -- files, more easily set expires and cache values, and avoid possibly -- costly transference of cookies on static files. For more information, -- please see: -- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain -- -- If you change the resource pattern for StaticR in Foundation.hs, you will -- have to make a corresponding change here. -- -- To see how this value is used, see urlRenderOverride in Foundation.hs staticRoot :: AppConfig DefaultEnv -> Text staticRoot conf = [st|#{appRoot conf}/static|] -- The rest of this file contains settings which rarely need changing by a -- user. -- The next functions are for allocating a connection pool and running -- database actions using a pool, respectively. They are used internally -- by the scaffolded application, and therefore you will rarely need to use -- them yourself. runConnectionPool :: MonadControlIO m => SqlPersist m a -> ConnectionPool -> m a runConnectionPool = runSqlPool withConnectionPool :: MonadControlIO m => AppConfig DefaultEnv -> (ConnectionPool -> m a) -> m a withConnectionPool conf f = do dbConf <- liftIO $ withYamlEnvironment "config/postgresql.yml" (appEnv conf) $ either error return . loadConfig withPostgresqlPool (pgConnStr dbConf) (pgPoolSize dbConf) f -- Example of making a dynamic configuration static -- use /return $(mkConnStr Production)/ instead of loadConnStr -- mkConnStr :: AppEnvironment -> Q Exp -- mkConnStr env = qRunIO (loadConnStr env) >>= return . LitE . StringL -- The following functions are used for calling HTML, CSS, -- Javascript, and plain text templates from your Haskell code. During development, -- the "Debug" versions of these functions are used so that changes to -- the templates are immediately reflected in an already running -- application. When making a production compile, the non-debug version -- is used for increased performance. -- -- You can see an example of how to call these functions in Handler/Root.hs -- -- Note: due to polymorphic Hamlet templates, hamletFileDebug is no longer -- used; to get the same auto-loading effect, it is recommended that you -- use the devel server. -- | expects a root folder for each type, e.g: hamlet/ lucius/ julius/ globFile :: String -> String -> FilePath globFile kind x = kind ++ "/" ++ x ++ "." ++ kind hamletFile :: FilePath -> Q Exp hamletFile = S.hamletFile . globFile "hamlet" cassiusFile :: FilePath -> Q Exp cassiusFile = #ifdef PRODUCTION S.cassiusFile . globFile "cassius" #else S.cassiusFileDebug . globFile "cassius" #endif luciusFile :: FilePath -> Q Exp luciusFile = #ifdef PRODUCTION S.luciusFile . globFile "lucius" #else S.luciusFileDebug . globFile "lucius" #endif juliusFile :: FilePath -> Q Exp juliusFile = #ifdef PRODUCTION S.juliusFile . globFile "julius" #else S.juliusFileDebug . globFile "julius" #endif textFile :: FilePath -> Q Exp textFile = #ifdef PRODUCTION S.textFile . globFile "text" #else S.textFileDebug . globFile "text" #endif widgetFile :: FilePath -> Q Exp widgetFile x = do let h = whenExists (globFile "hamlet") (whamletFile . globFile "hamlet") let c = whenExists (globFile "cassius") cassiusFile let j = whenExists (globFile "julius") juliusFile let l = whenExists (globFile "lucius") luciusFile [|addWidget $h >> addCassius $c >> addJulius $j >> addLucius $l|] where whenExists tofn f = do e <- qRunIO $ doesFileExist $ tofn x if e then f x else [|mempty|]
snoyberg/yesodcms
Settings.hs
bsd-2-clause
5,305
0
13
915
762
442
320
66
2
import Data.List tst = do getLine xstr <- getLine let xs = map read (words xstr) putStrLn $ intercalate " " $ map show $ map (uncurry lcm) (zip (1 : xs) (xs ++ [1])) main = do tstr <- getLine mapM_ (const tst) [1 .. read tstr]
pbl64k/HackerRank-Contests
2014-08-04-Weekly/JohnAndGcdList/jagl.accepted.hs
bsd-2-clause
254
2
13
75
139
64
75
9
1
{-| /NOTE/: This module is preliminary and may change at a future date. If you wish to use its features, please email me and I will help evolve an API that suits you. This module is intended to help converting a list of tags into a tree of tags. -} module Text.HTML.TagSoup.Tree {-# DEPRECATED "Not quite ready for use yet, email me if it looks useful to you" #-} ( TagTree(..), tagTree, flattenTree, transformTree, universeTree ) where import Text.HTML.TagSoup.Type import Control.Arrow data TagTree str = TagBranch str [Attribute str] [TagTree str] | TagLeaf (Tag str) deriving Show instance Functor TagTree where fmap f (TagBranch x y z) = TagBranch (f x) (map (f***f) y) (map (fmap f) z) fmap f (TagLeaf x) = TagLeaf (fmap f x) -- | Convert a list of tags into a tree. This version is not lazy at -- all, that is saved for version 2. tagTree :: Eq str => [Tag str] -> [TagTree str] tagTree = g where g :: Eq str => [Tag str] -> [TagTree str] g [] = [] g xs = a ++ map TagLeaf (take 1 b) ++ g (drop 1 b) where (a,b) = f xs -- the second tuple is either null or starts with a close f :: Eq str => [Tag str] -> ([TagTree str],[Tag str]) f (TagOpen name atts:rest) = case f rest of (inner,[]) -> (TagLeaf (TagOpen name atts):inner, []) (inner,TagClose x:xs) | x == name -> let (a,b) = f xs in (TagBranch name atts inner:a, b) | otherwise -> (TagLeaf (TagOpen name atts):inner, TagClose x:xs) _ -> error "TagSoup.Tree.tagTree: safe as - forall x . isTagClose (snd (f x))" f (TagClose x:xs) = ([], TagClose x:xs) f (x:xs) = (TagLeaf x:a,b) where (a,b) = f xs f [] = ([], []) flattenTree :: [TagTree str] -> [Tag str] flattenTree xs = concatMap f xs where f (TagBranch name atts inner) = TagOpen name atts : flattenTree inner ++ [TagClose name] f (TagLeaf x) = [x] universeTree :: [TagTree str] -> [TagTree str] universeTree = concatMap f where f t@(TagBranch _ _ inner) = t : universeTree inner f x = [x] transformTree :: (TagTree str -> [TagTree str]) -> [TagTree str] -> [TagTree str] transformTree act = concatMap f where f (TagBranch a b inner) = act $ TagBranch a b (transformTree act inner) f x = act x
nfjinjing/yuuko
src/Text/HTML/TagSoup/Tree.hs
bsd-3-clause
2,481
0
15
773
895
462
433
44
7
------------------------------------------------------------------------------- -- | -- Module : Control.Monad.Trans.Supply -- Copyright : (C) 2013 Merijn Verstraaten -- License : BSD-style (see the file LICENSE) -- Maintainer : Merijn Verstraaten <merijn@inconsistent.nl> -- Stability : experimental -- Portability : portable -- -- [Computation type:] Computations that require a supply of values. -- -- [Binding strategy:] Applicative values are functions that consume an input -- from a supply to produce a value. -- -- [Useful for:] Providing a supply of unique names or other values to -- computations needing them. -- -- [Zero and plus:] Identical to the underlying implementations (if any) of -- 'empty', '<|>', 'mzero' and 'mplus'. -- -- [Example type:] @'Supply' s a@ &#160; or &#160; @'SupplyT' s f a@ -- -- [Difference from "Control.Applicative.Supply":] The 'Applicative' instance -- of 'SupplyT' defined in this module requires that the wrapped type is an -- instance of 'Monad'. See the "Applicative vs Monad" section below for an -- in-depth explanation. -- -- The @'Supply' s a@ monad represents a computation that consumes a supply of -- @s@'s to produce a value of type @a@. One example use is to simplify -- computations that require the generation of unique names. The 'Supply' monad -- can be used to provide a stream of unique names to such a computation. ------------------------------------------------------------------------------- module Control.Monad.Trans.Supply ( -- ** Applicative vs Monad SupplyT -- $why-monad -- * Supply and SupplyT Type Supply , SupplyT -- * Supply Operations , supply , provide , demand , withSupply , withSupplyT -- * Running Supply Computations , runSupply , runSupplyT , runListSupply , runListSupplyT , runMonadSupply , runMonadSupplyT ) where import Control.Applicative import Control.Monad import Control.Monad.Trans import Data.Functor.Identity -- $why-monad -- 𝐓𝐋;𝐃𝐑: Ignore "Control.Applicative.Supply" if you're wrapping a 'Monad'. -- -- A 'Monad' instance of 'Supply' results in 'Supply' actions that can be -- executed conditionally (after all, that's what 'Monad's are for!), -- implementing the 'SupplyT' in a way that allows this results in an important -- restriction, it is impossible to define an 'Applicative' instance for -- @'SupplyT' s m a@ without a 'Monad' instance for @m@! As a result, it is not -- possible to use this transformer to wrap something that is only -- 'Applicative' and not 'Monad' and still get an 'Applicative' instance back. -- To solve this issue, a slightly different transformer is implemented in -- "Control.Applicative.Supply", which does allow this! -- -- Since it cannot be made an instance of 'Monad', the -- 'Control.Applicative.Supply.SupplyT' transformer from -- "Control.Applicative.Supply" is less powerful than the one defined here. If -- you're wrapping a 'Monad', use the transformer defined in this module, -- instead of the one defined in "Control.Applicative.Supply". -- | The Supply monad. -- -- Computations consume values of type @s@ from a supply of values. -- -- 'return' ignores the supply of values, while '>>=' passes the supply to the -- second argument after the first argument is done consuming values. type Supply s a = SupplyT s Identity a -- | The Supply transformer. -- -- Composes Supply with an underlying monad, allowing it to be used monad in -- transformer stacks. -- -- The resulting SupplyT value has 'Alternative' and 'MonadPlus' instances if -- the underlying monad has such these instances. newtype SupplyT s m a = SupplyT { unwrapSupplyT :: m (Consumer s m a) } data Consumer s m a = Done a | More (s -> SupplyT s m a) instance Functor f => Functor (Consumer s f) where fmap f (Done a) = Done (f a) fmap f (More g) = More $ fmap f . g instance Functor f => Functor (SupplyT s f) where fmap f (SupplyT x) = SupplyT (fmap (fmap f) x) instance (Functor m, Monad m) => Applicative (SupplyT s m) where pure = SupplyT . return . Done (<*>) = ap instance (Functor m, Monad m) => Monad (SupplyT s m) where return = pure SupplyT m >>= f = SupplyT $ m >>= \v -> case v of Done a -> unwrapSupplyT (f a) More g -> return . More $ g >=> f instance MonadTrans (SupplyT s) where lift = SupplyT . liftM Done instance (Alternative m, Monad m) => Alternative (SupplyT s m) where empty = SupplyT empty SupplyT x <|> SupplyT y = SupplyT (x <|> y) instance (Functor m, MonadPlus m) => MonadPlus (SupplyT s m) where mzero = SupplyT mzero SupplyT x `mplus` SupplyT y = SupplyT (x `mplus` y) instance (Functor m, MonadIO m) => MonadIO (SupplyT s m) where liftIO = lift . liftIO ------------------------------------------------------------------------------- -- Supply Operations -- | Supply a construction function with an @s@ value from the supply. supply :: Monad m => (s -> m a) -> SupplyT s m a supply f = SupplyT . return . More $ SupplyT . liftM Done . f -- | Supply a non-monadic construction function with an @s@ value from the -- supply and automatically lift its result into the @m@ monad that 'SupplyT' -- wraps. provide :: Monad m => (s -> a) -> SupplyT s m a provide f = supply (return . f) -- | Demand an @s@ value from the supply. demand :: Monad m => SupplyT s m s demand = provide id -- | Change the type of values consumed by a 'Supply' computation. withSupply :: (s' -> s) -> Supply s a -> Supply s' a withSupply = withSupplyT -- | Change the type of values consumed by a 'SupplyT' computation. withSupplyT :: Functor f => (s' -> s) -> SupplyT s f a -> SupplyT s' f a withSupplyT f (SupplyT m) = SupplyT (fmap go m) where go (Done x) = Done x go (More g) = More $ withSupplyT f . g . f ------------------------------------------------------------------------------- -- Running Supply Computations -- | Run a supply consuming computation, using a generation function and -- initial value to compute the values consumed by the 'Supply' computation. runSupply :: Supply s a -> (s -> s) -> s -> a runSupply act gen = runIdentity . runSupplyT act gen -- | Run a supply consuming computation, using a generation function and -- initial value to compute the values consumed by the 'SupplyT' computation. runSupplyT :: Monad m => SupplyT s m a -> (s -> s) -> s -> m a runSupplyT (SupplyT m) gen s = join $ liftM go m where go (Done x) = return x go (More f) = runSupplyT (f s) gen (gen s) -- | Feed a supply consuming computation from a list until the computation -- finishes or the list runs out. If the list does not contain sufficient -- elements, @runListSupply@ returns uncompleted computation. runListSupply :: Supply s a -> [s] -> Either (Supply s a) a runListSupply sink l = runIdentity $ runListSupplyT sink l -- | Feed a supply consuming computation from a list until the computation -- finishes or the list runs out. If the list does not contain sufficient -- elements, @runListSupplyT@ returns uncompleted computation. runListSupplyT :: Monad m => SupplyT s m a -> [s] -> m (Either (SupplyT s m a) a) runListSupplyT (SupplyT m) [] = return $ Left (SupplyT m) runListSupplyT (SupplyT m) (s:ss) = join $ liftM go m where go (Done x) = return (Right x) go (More f) = runListSupplyT (f s) ss -- | Feed a supply consuming computation from a monadic action until the -- computation finishes. runMonadSupply :: Monad m => Supply s a -> m s -> m a runMonadSupply (SupplyT m) src = go $ runIdentity m where go (Done x) = return x go (More f) = src >>= \s -> runMonadSupply (f s) src -- | Feed a supply consuming computation from a monadic action until the -- computation finishes. runMonadSupplyT :: Monad m => SupplyT s m a -> m s -> m a runMonadSupplyT (SupplyT m) src = join $ liftM go m where go (Done x) = return x go (More f) = src >>= \s -> runMonadSupplyT (f s) src
merijn/transformers-supply
Control/Monad/Trans/Supply.hs
bsd-3-clause
7,980
0
13
1,605
1,622
864
758
77
2
{-# LANGUAGE TemplateHaskell #-} module VectorTests.TH (TestType (..), writeTests, aggregateTests) where import Test.Framework import Data.List (sortBy, groupBy, intersectBy, foldl1') import Data.Function (on) import Data.Geometry import Language.Haskell.TH import VectorTests.VectorGenerators () import Control.Monad (liftM,forM,join) import Data.Maybe (catMaybes) -- import Debug.Trace (traceShow) -- | Type of tests data TestType = VecT | MatT | VecMat -- | All instances of this class are to be added automatically to HTF main test function class MultitypeTestSuite name where multitypeTestSuite :: name -> TestSuite -- | Write a single test, with specified type signature and name writeTest :: (TypeQ -> Q [Dec]) -> (String, TypeQ, Integer, Name) -> Q [(Dec, Maybe (Name, Name))] writeTest test (t, typeQ, di, typeName) = liftM (renameFuncSuf $ nameBase typeName ++ t ++ "X" ++ show di) (test typeQ) -- | Append suffix to the names of the functions renameFuncSuf :: String -> [Dec] -> [(Dec, Maybe (Name, Name))] renameFuncSuf suffix = map f where appendSuf name = mkName $ nameBase name ++ suffix f (SigD name sig) = (SigD (appendSuf name) sig, Nothing ) f (FunD name fun) = (FunD (appendSuf name) fun, Just (name, appendSuf name)) f x = (x, Nothing) -- | Write specified test on specified types writeTests :: TestType -> [Name] -> (TypeQ -> Q [Dec]) -> Q [Dec] writeTests ttype classes test = do locTH <- location -- Generating all tests (tests, mnames) <- liftM (>>= (\t@(dim,name) -> case ttype of VecT -> [("Vec", makeVectorType t, dim, name)] MatT -> [("Mat", makeMatrixType t, dim, name)] VecMat -> [ ("Vec", makeVectorType t, dim, name) , ("Mat", makeMatrixType t, dim, name)])) (getVectorMathTypes classes) >>= (liftM (unzip . join) . mapM (writeTest test)) let -- name of the module moduleName = loc_module locTH -- Location of the splice in HTF format loc = VarE 'makeLoc `AppE` (LitE . StringL $ loc_filename locTH) `AppE` (LitE . IntegerL . fromIntegral . fst $ loc_start locTH) -- [(name of the original function, names of generated functions)] names = map (\xs -> (fst $ head xs, map snd xs)) . groupBy (\(n1,_) (n2,_) -> nameBase n1 == nameBase n2) . sortBy (\(n1,_) (n2,_) -> nameBase n1 `compare` nameBase n2) $ catMaybes mnames -- make test suite suite :: Name -> ExpQ -> Q [Dec] suite name gnames = liftM (DataD [] dataName [] [NormalC dataCon []] [] : ) [d| instance MultitypeTestSuite $(return $ ConT dataName) where multitypeTestSuite _ = makeTestSuite $(return . LitE . StringL . ((moduleName ++ ":") ++) . drop 5 $ nameBase name) . map (\(gname,gfunc) -> makeQuickCheckTest gname $(return loc) gfunc) $ $(gnames) |] where dataName = mkName $ "MTS_" ++ nameBase name dataCon = mkName $ "MTS_" ++ nameBase name ++ "_val" -- generate pairs of function (string) names and functions theirselves (IO ()) gennames :: String -> [Name] -> ExpQ gennames basename = return . ListE . map (\gn -> TupE [ LitE . StringL . drop (length basename) $ nameBase gn , VarE 'qcAssertion `AppE` VarE gn] ) suites <- mapM (\(n,gns) -> suite n (gennames (nameBase n) gns) ) names return $ concat suites ++ tests -- | Aggregate all generated tests into list of test suites aggregateTests :: ExpQ aggregateTests = do ClassI _ instances <- reify ''MultitypeTestSuite liftM ListE . forM instances $ \(InstanceD _ (AppT _ (ConT name)) _) -> [e| multitypeTestSuite $(return . ConE . mkName $ nameBase name ++ "_val") |] --liftM (renameFunc $ nameBase n) $ -- DataD Cxt Name [TyVarBndr] [Con] [Name] -- DataD [] MTS2_1627463391 [] [NormalC MTS2_1627463392 []] [] -- $(return . mkName $ "MTS" ++ nameBase name) ---------------------------------------------------------------------------------------------------- getVectorMathTypes :: [Name] -> Q [(Integer, Name)] getVectorMathTypes classes = do ClassI _ instances <- reify ''VectorMath let vtypes = sortTypes $ instances >>= getDimName types <- liftM (map ((,) 0) . foldl1' (intersectBy ( (==) `on` nameBase ) )) $ mapM findInstances classes return $ intersectBy ( (==) `on` (nameBase . snd) ) vtypes types where findInstances cname = do ClassI _ is <- reify cname return . sortBy (compare `on` nameBase) $ is >>= getIName getIName (InstanceD _ (AppT _ (ConT tn)) _ ) = [tn] getIName _ = [] getDimName (InstanceD _ (AppT (AppT _ (LitT (NumTyLit di))) (ConT typeName)) _) = [(di,typeName)] getDimName _ = [] makeMatrixType :: (Integer, Name) -> TypeQ makeMatrixType (di, name) = pure $ ConT ''Matrix `AppT` LitT (NumTyLit di) `AppT` ConT name makeVectorType :: (Integer, Name) -> TypeQ makeVectorType (di, name) = pure $ ConT ''Vector `AppT` LitT (NumTyLit di) `AppT` ConT name sortTypes :: [(Integer, Name)] -> [(Integer, Name)] sortTypes = sortBy ( \(p1, name1) (p2, name2) -> compare p1 p2 `mappend` compare (nameBase name1) (nameBase name2) )
achirkin/fastvec
test/VectorTests/TH.hs
bsd-3-clause
5,661
0
20
1,640
1,707
926
781
91
3
import Data.Map class (Ord c) => IdEntity c a where entt :: c -> a code :: a -> c main :: IO() main = putStrLn("It has Begun!")
rafaelbfs/bovhistory
src/Main.hs
bsd-3-clause
144
1
7
44
68
34
34
-1
-1
{-# LANGUAGE Safe, PatternGuards, BangPatterns #-} {-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} {- | Simplification. The rules in this module are all conditional on the expressions being well-defined. So, for example, consider the formula `P`, which corresponds to `fin e`. `P` says the following: if e is well-formed, then will evaluate to a finite natural number. More concretely, consider `fin (3 - 5)`. This will be simplified to `True`, which does not mean that `3 - 5` is actually finite. -} module Cryptol.TypeCheck.Solver.Numeric.Simplify1 (propToProp', ppProp') where import Cryptol.TypeCheck.Solver.Numeric.SimplifyExpr (crySimpExpr, splitSum, normSum, Sign(..)) import Cryptol.TypeCheck.Solver.Numeric.AST import Cryptol.Utils.Misc ( anyJust ) import Cryptol.Utils.PP import Control.Monad ( liftM2 ) import Data.Maybe ( fromMaybe ) import qualified Data.Map as Map import Data.Either(partitionEithers) data Atom = AFin Name | AGt Expr Expr -- on naturals | AEq Expr Expr -- on naturals deriving Eq type I = IfExpr' Atom -- tmp propToProp' :: Prop -> I Bool propToProp' prop = case prop of Fin e -> pFin e x :== y -> pEq x y x :>= y -> pGeq x y x :> y -> pGt x y x :>: y -> pAnd (pFin x) (pAnd (pFin y) (pGt x y)) x :==: y -> pAnd (pFin x) (pAnd (pFin y) (pEq x y)) p :&& q -> pAnd (propToProp' p) (propToProp' q) p :|| q -> pOr (propToProp' p) (propToProp' q) Not p -> pNot (propToProp' p) PFalse -> pFalse PTrue -> pTrue instance (Eq a, HasVars a) => HasVars (I a) where apSubst su prop = case prop of Impossible -> Nothing Return _ -> Nothing If a t e -> case apSubstAtom su a of Nothing -> do [x,y] <- branches return (If a x y) Just a' -> Just $ fromMaybe (pIf a' t e) $ do [x,y] <- branches return (pIf a' x y) where branches = anyJust (apSubst su) [t,e] -- | Apply a substituition to an atom apSubstAtom :: Subst -> Atom -> Maybe (I Bool) apSubstAtom su atom = case atom of AFin x -> do e <- Map.lookup x su return (pFin e) AEq e1 e2 -> do [x,y] <- anyJust (apSubst su) [e1,e2] return (pEq x y) AGt e1 e2 -> do [x,y] <- anyJust (apSubst su) [e1,e2] return (pGt x y) {- TODO: Unused -- | The various way in which the given proposition may be true. -- The Boolean indicates if the atom is +ve: -- 'True' for positive, 'False' for -ve. truePaths :: I Bool -> [ [(Bool,Atom)] ] truePaths prop = case prop of Impossible -> [] Return False -> [] Return True -> [ [] ] If a t e -> map ((True,a):) (truePaths t) ++ map ((False,a):) (truePaths e) -} -------------------------------------------------------------------------------- -- Pretty print ppAtom :: Atom -> Doc ppAtom atom = case atom of AFin x -> text "fin" <+> ppName x AGt x y -> ppExpr x <+> text ">" <+> ppExpr y AEq x y -> ppExpr x <+> text "=" <+> ppExpr y ppProp' :: I Bool -> Doc ppProp' = ppIf ppAtom (text . show) -------------------------------------------------------------------------------- -- General logic stuff -- | False pFalse :: I Bool pFalse = Return False -- | True pTrue :: I Bool pTrue = Return True -- | Negation pNot :: I Bool -> I Bool pNot p = case p of Impossible -> Impossible Return a -> Return (not a) If c t e -> If c (pNot t) (pNot e) -- | And pAnd :: I Bool -> I Bool -> I Bool pAnd p q = pIf p q pFalse -- | Or pOr :: I Bool -> I Bool -> I Bool pOr p q = pIf p pTrue q mkIf :: (Eq a, HasVars a) => Atom -> I a -> I a -> I a mkIf a t e | t == e = t | otherwise = case a of AFin x -> If a (pKnownFin x t) (pKnownInf x e) _ | If b@(AFin y) _ _ <- t -> If b (mkFinIf y) (mkInfIf y) | If b@(AFin y) _ _ <- e -> If b (mkFinIf y) (mkInfIf y) AEq x' y' | x == y -> t | otherwise -> If (AEq x y) t e where (x,y) = balanceEq x' y' _ -> If a t e where mkFinIf y = mkIf a (pKnownFin y t) (pKnownFin y e) mkInfIf y = case apSubstAtom (Map.singleton y (K Inf)) a of Nothing -> mkIf a (pKnownInf y t) (pKnownInf y t) Just a' -> pIf a' (pKnownInf y t) (pKnownInf y t) -- | If-then-else with non-atom at decision. pIf :: (Eq a, HasVars a) => I Bool -> I a -> I a -> I a pIf c t e = case c of Impossible -> Impossible Return True -> t Return False -> e If p t1 e1 | t2 == e2 -> t2 | otherwise -> mkIf p t2 e2 where t2 = pIf t1 t e e2 = pIf e1 t e -- | Atoms to propositions. pAtom :: Atom -> I Bool pAtom p = do a <- case p of AFin _ -> return p AEq x y -> bin AEq x y AGt x y -> bin AGt x y If a pTrue pFalse where prep x = do y <- eNoInf x case y of K Inf -> Impossible _ -> return (crySimpExpr y) bin f x y = liftM2 f (prep x) (prep y) -------------------------------------------------------------------------------- -- Implementation of Cryptol constraints -- | Implementation of `==` pEq :: Expr -> Expr -> I Bool pEq x (K (Nat 0)) = pEq0 x pEq x (K (Nat 1)) = pEq1 x pEq (K (Nat 0)) y = pEq0 y pEq (K (Nat 1)) y = pEq1 y pEq x y = pIf (pInf x) (pInf y) $ pAnd (pFin y) (pAtom (AEq x y)) -- | Implementation of `>=` pGeq :: Expr -> Expr -> I Bool pGeq x y = pIf (pInf x) pTrue $ pIf (pFin y) (pAtom (AGt (x :+ one) y)) pFalse -- | Implementation of `Fin` pFin :: Expr -> I Bool pFin expr = case expr of K Inf -> pFalse K (Nat _) -> pTrue Var x -> pAtom (AFin x) t1 :+ t2 -> pAnd (pFin t1) (pFin t2) t1 :- _ -> pFin t1 t1 :* t2 -> pIf (pInf t1) (pEq t2 zero) $ pIf (pInf t2) (pEq t1 zero) $ pTrue Div t1 _ -> pFin t1 Mod _ _ -> pTrue t1 :^^ t2 -> pIf (pInf t1) (pEq t2 zero) $ pIf (pInf t2) (pOr (pEq t1 zero) (pEq t1 one)) $ pTrue Min t1 t2 -> pOr (pFin t1) (pFin t2) Max t1 t2 -> pAnd (pFin t1) (pFin t2) Width t1 -> pFin t1 LenFromThen _ _ _ -> pTrue LenFromThenTo _ _ _ -> pTrue -- | Implementation `e1 > e2`. pGt :: Expr -> Expr -> I Bool pGt x y = pIf (pFin y) (pIf (pFin x) (pAtom (AGt x y)) pTrue) pFalse -- | Implementation of `e == inf` pInf :: Expr -> I Bool pInf = pNot . pFin -- | Special case: `e == 0` pEq0 :: Expr -> I Bool pEq0 expr = case expr of K Inf -> pFalse K (Nat n) -> if n == 0 then pTrue else pFalse Var _ -> pAnd (pFin expr) (pAtom (AEq expr zero)) t1 :+ t2 -> pAnd (pEq t1 zero) (pEq t2 zero) t1 :- t2 -> pEq t1 t2 t1 :* t2 -> pOr (pEq t1 zero) (pEq t2 zero) Div t1 t2 -> pGt t2 t1 Mod _ _ -> pAtom (AEq expr zero) -- or divides t1 :^^ t2 -> pIf (pEq t2 zero) pFalse (pEq t1 zero) Min t1 t2 -> pOr (pEq t1 zero) (pEq t2 zero) Max t1 t2 -> pAnd (pEq t1 zero) (pEq t2 zero) Width t1 -> pEq t1 zero LenFromThen _ _ _ -> pFalse LenFromThenTo x y z -> pIf (pGt x y) (pGt z x) (pGt x z) -- | Special case: `e == 1` pEq1 :: Expr -> I Bool pEq1 expr = case expr of K Inf -> pFalse K (Nat n) -> if n == 1 then pTrue else pFalse Var _ -> pAnd (pFin expr) (pAtom (AEq expr one)) t1 :+ t2 -> pIf (pEq t1 zero) (pEq t2 one) $ pIf (pEq t2 zero) (pEq t1 one) pFalse t1 :- t2 -> pEq t1 (t2 :+ one) t1 :* t2 -> pAnd (pEq t1 one) (pEq t2 one) Div t1 t2 -> pAnd (pGt (two :* t2) t1) (pGeq t1 t2) Mod _ _ -> pAtom (AEq expr one) t1 :^^ t2 -> pOr (pEq t1 one) (pEq t2 zero) Min t1 t2 -> pIf (pEq t1 one) (pGt t2 zero) $ pIf (pEq t2 one) (pGt t1 zero) pFalse Max t1 t2 -> pIf (pEq t1 one) (pGt two t2) $ pIf (pEq t2 one) (pGt two t1) pFalse Width t1 -> pEq t1 one -- See Note [Sequences of Length 1] in 'Cryptol.TypeCheck.Solver.InfNat' LenFromThen x y w -> pAnd (pGt y x) (pGeq y (two :^^ w)) LenFromThenTo x y z -> pIf (pGt z y) (pGeq x z) (pGeq z x) -------------------------------------------------------------------------------- pKnownFin :: (HasVars a, Eq a) => Name -> I a -> I a pKnownFin x prop = case prop of If (AFin y) t _ | x == y -> pKnownFin x t If p t e -> mkIf p (pKnownFin x t) (pKnownFin x e) _ -> prop pKnownInf :: (Eq a, HasVars a) => Name -> I a -> I a pKnownInf x prop = fromMaybe prop (apSubst (Map.singleton x (K Inf)) prop) -- Cancel constants -- If the original equation was valid, it continues to be valid. balanceEq :: Expr -> Expr -> (Expr, Expr) balanceEq (K (Nat a) :+ e1) (K (Nat b) :+ e2) | a >= b = balanceEq e2 (K (Nat (a - b)) :+ e1) | otherwise = balanceEq e1 (K (Nat (b - a)) :+ e2) -- Move subtraction to the other side. -- If the original equation was valid, this will continue to be valid. balanceEq e1 e2 | not (null neg_es1 && null neg_es2) = balanceEq (mk neg_es2 pos_es1) (mk neg_es1 pos_es2) where (pos_es1, neg_es1) = partitionEithers (map classify (splitSum e1)) (pos_es2, neg_es2) = partitionEithers (map classify (splitSum e2)) classify (sign,e) = case sign of Pos -> Left e Neg -> Right e mk as bs = normSum (foldr (:+) zero (as ++ bs)) -- fallback balanceEq x y = (x,y) {- TODO: unused balanceGt (K (Nat a) :+ e1) (K (Nat b) :+ e2) | a >= b = balanceGt (K (Nat (a - b)) :+ e1) e2 | otherwise = balanceGt e1 (K (Nat (b - a)) :+ e2) -} -------------------------------------------------------------------------------- -- | Eliminate `inf`, except at the top level. eNoInf :: Expr -> I Expr eNoInf expr = case expr of -- These are the interesting cases where we have to branch x :* y -> do x' <- eNoInf x y' <- eNoInf y case (x', y') of (K Inf, K Inf) -> return inf (K Inf, _) -> pIf (pEq y' zero) (return zero) (return inf) (_, K Inf) -> pIf (pEq x' zero) (return zero) (return inf) _ -> return (x' :* y') x :^^ y -> do x' <- eNoInf x y' <- eNoInf y case (x', y') of (K Inf, K Inf) -> return inf (K Inf, _) -> pIf (pEq y' zero) (return one) (return inf) (_, K Inf) -> pIf (pEq x' zero) (return zero) $ pIf (pEq x' one) (return one) $ return inf _ -> return (x' :^^ y') -- The rest just propagates K _ -> return expr Var _ -> return expr x :+ y -> do x' <- eNoInf x y' <- eNoInf y case (x', y') of (K Inf, _) -> return inf (_, K Inf) -> return inf _ -> return (x' :+ y') x :- y -> do x' <- eNoInf x y' <- eNoInf y case (x', y') of (_, K Inf) -> Impossible (K Inf, _) -> return inf _ -> return (x' :- y') Div x y -> do x' <- eNoInf x y' <- eNoInf y case (x', y') of (K Inf, _) -> Impossible (_, K Inf) -> return zero _ -> return (Div x' y') Mod x y -> do x' <- eNoInf x -- `Mod x y` is finite, even if `y` is `inf`, so first check -- for finiteness. pIf (pFin y) (do y' <- eNoInf y case (x',y') of (K Inf, _) -> Impossible (_, K Inf) -> Impossible _ -> return (Mod x' y') ) (return x') Min x y -> do x' <- eNoInf x y' <- eNoInf y case (x',y') of (K Inf, _) -> return y' (_, K Inf) -> return x' _ -> return (Min x' y') Max x y -> do x' <- eNoInf x y' <- eNoInf y case (x', y') of (K Inf, _) -> return inf (_, K Inf) -> return inf _ -> return (Max x' y') Width x -> do x' <- eNoInf x case x' of K Inf -> return inf _ -> return (Width x') LenFromThen x y w -> fun3 LenFromThen x y w LenFromThenTo x y z -> fun3 LenFromThenTo x y z where fun3 f x y z = do x' <- eNoInf x y' <- eNoInf y z' <- eNoInf z case (x',y',z') of (K Inf, _, _) -> Impossible (_, K Inf, _) -> Impossible (_, _, K Inf) -> Impossible _ -> return (f x' y' z')
ntc2/cryptol
src/Cryptol/TypeCheck/Solver/Numeric/Simplify1.hs
bsd-3-clause
13,571
0
19
5,289
5,195
2,536
2,659
294
35
-- -- Operation: -- * When one or more filenames are specified the program will look for audio -- tags in those files (and ignore files with no tag). If an option to -- modify a tag is used then the files will be modified. Otherwise all -- recognized tags are printed to stdout. -- * When no filenames are specified TSV formatted input is read from stdin -- (the first line must be a header). The use case is to first read tags -- from audio files and pipe the output to a filter (e.g. awk) and finally -- to pipe this to the program which reads the TSV from stdin. -- * The TSV header must follow the format specified in tsvHeader (this is not -- a limitation of the program, but rather an attempt to standardize scripts -- which use the program) -- -- Limitations: -- * TSV code only works for tags and filenames without tabs in them (the code -- does nothing to deal with tabs) -- {-# LANGUAGE OverloadedStrings #-} module Main where import Control.Applicative ((<$>), (<*>)) import Control.Monad (forM_, when) import Data.Char (ord) import Data.Csv import Data.Maybe (isJust, fromJust, maybe) import Data.Monoid ((<>)) import Data.Version (showVersion) import Paths_tag (version) import qualified Data.ByteString.Lazy as BL import qualified Data.Vector as V import qualified Options.Applicative as O import qualified Sound.TagLib as T data Args = Args { optAlbum :: Maybe String , optArtist :: Maybe String , optComment :: Maybe String , optGenre :: Maybe String , optTitle :: Maybe String , optTrack :: Maybe Integer , optYear :: Maybe Integer , optOutputFormat :: OutputFormat , optVerbose :: Bool , optPaths :: [FilePath] } data OutputFormat = FmtRec | FmtTsv deriving Eq data Info = Info { album :: String , artist :: String , comment :: String , genre :: String , title :: String , track :: Integer , year :: Integer } data TsvRecord = TsvRecord { tpath :: !FilePath , ttrack :: !Integer , ttitle :: !String , talbum :: !String , tartist :: !String , tgenre :: !String , tyear :: !Integer -- Don't include comment as it is not unlikely to contain tabs } deriving Show main :: IO () main = do opt <- O.execParser $ O.info (O.helper <*> parseArgs) $ O.fullDesc <> O.header hdrString run opt where hdrString = "tag v" ++ showVersion version ++ " - Command line editing of audio file tags" -- There appears to be no builtin way to parse an option which defaults to -- Nothing, so we need some custom code to deal with this. optionMaybe :: O.ReadM a -> O.Mod O.OptionFields (Maybe a) -> O.Parser (Maybe a) optionMaybe r x = O.option (fmap Just r) (O.value Nothing <> x) parseArgs :: O.Parser Args parseArgs = Args <$> parseStr 'a' "album" <*> parseStr 'b' "artist" <*> parseStr 'c' "comment" <*> parseStr 'g' "genre" <*> parseStr 't' "title" <*> parseNum 'n' "track" <*> parseNum 'y' "year" <*> O.flag FmtRec FmtTsv (O.long "tsv" <> O.help "Output tab-separated tags") <*> O.switch (O.long "verbose" <> O.help "Verbose output") <*> O.many (O.argument O.str (O.metavar "FILES")) where parseStr = parse O.str "STR" parseNum = parse O.auto "NUM" parse r meta short name = optionMaybe r ( O.long name <> O.short short <> O.metavar meta <> O.help ("Set " ++ name) ) run :: Args -> IO () run args | null (optPaths args) = runTsv args | otherwise = runTag args runTsv :: Args -> IO () runTsv args = do csvData <- BL.getContents case decodeByNameWith tsvopt csvData of Left err -> putStrLn err Right (_, v) -> V.forM_ v $ handleTsvRecord args where tsvopt = defaultDecodeOptions { decDelimiter = fromIntegral (ord '\t') } handleTsvRecord :: Args -> TsvRecord -> IO () handleTsvRecord args tsv = do mfile <- T.open (tpath tsv) mtag <- maybe (return Nothing) T.tag mfile case mtag of Nothing -> if optVerbose args then putStrLn ("missing tag: " ++ tpath tsv) else return () Just tag -> do modifyTag tag ( args { optTrack = Just $ ttrack tsv , optTitle = Just $ ttitle tsv , optAlbum = Just $ talbum tsv , optArtist = Just $ tartist tsv , optGenre = Just $ tgenre tsv , optYear = Just $ tyear tsv } ) T.save $ fromJust mfile return () runTag :: Args -> IO () runTag args = do when (optOutputFormat args == FmtTsv && (optVerbose args || not (anySetters args))) $ putStrLn tsvHeader forM_ (optPaths args) $ \fname -> do mfile <- T.open fname mtag <- maybe (return Nothing) T.tag mfile case mtag of Nothing -> if optVerbose args then putStrLn ("missing tag: " ++ fname) else return () Just tag -> handleTagFile fname (fromJust mfile) tag args handleTagFile :: FilePath -> T.TagFile -> T.Tag -> Args -> IO () handleTagFile path file tag args = do when (optVerbose args || not (anySetters args)) $ record (optOutputFormat args) path <$> parseInfo tag >>= putStrLn when (anySetters args) $ do modifyTag tag args T.save file return () where record FmtRec = prettyInfo record FmtTsv = tsvFromInfo modifyTag :: T.Tag -> Args -> IO () modifyTag tag args = do withJust (optAlbum args) (T.setAlbum tag) withJust (optArtist args) (T.setArtist tag) withJust (optComment args) (T.setComment tag) withJust (optGenre args) (T.setGenre tag) withJust (optTitle args) (T.setTitle tag) withJust (optTrack args) (T.setTrack tag) withJust (optYear args) (T.setYear tag) where withJust m a = maybe (return ()) a m anySetters :: Args -> Bool anySetters args = or $ (sopt ++ iopt) <*> [args] where sopt = map (isJust .) [optAlbum, optArtist, optComment, optGenre, optTitle] iopt = map (isJust .) [optTrack, optYear] parseInfo :: T.Tag -> IO Info parseInfo tag = Info <$> T.album tag <*> T.artist tag <*> T.comment tag <*> T.genre tag <*> T.title tag <*> T.track tag <*> T.year tag prettyInfo :: FilePath -> Info -> String prettyInfo path (Info alb art cmt gen tle trk yr) = concat [ line "path: " path , line "artist: " art , line "album: " alb , line "title: " tle , line "track: " $ show trk , line "year: " $ show yr , line "genre: " gen , line "comment: " cmt ] where line _ "" = "" line l s = l ++ s ++ "\n" tsvFromInfo :: FilePath -> Info -> String tsvFromInfo path (Info alb art _ gen tle trk yr) = path ++ "\t" ++ show trk ++ "\t" ++ tle ++ "\t" ++ alb ++ "\t" ++ art ++ "\t" ++ gen ++ "\t" ++ show yr tsvHeader = "path\ttrack\ttitle\talbum\tartist\tgenre\tyear" instance FromNamedRecord TsvRecord where parseNamedRecord r = TsvRecord <$> r .: "path" <*> r .: "track" <*> r .: "title" <*> r .: "album" <*> r .: "artist" <*> r .: "genre" <*> r .: "year"
b4winckler/tag
src/Main.hs
bsd-3-clause
7,112
0
19
1,914
2,209
1,123
1,086
185
3
{-# LANGUAGE EmptyCase #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# OPTIONS_GHC -freduction-depth=100 #-} {-# OPTIONS_GHC -fno-warn-deprecations #-} -- | Instances for 'Generic' and 'HasMetadata'. -- -- We define instances for datatypes from @generics-sop@ and -- @base@ that are supported. -- -- (There are only instances defined in this module, so the -- documentation is empty.) -- module Generics.SOP.Instances () where -- GHC versions and base versions: -- -- 7.6.3: 4.6.0.1 -- 7.8.3: 4.7.0.1 -- 7.8.4: 4.7.0.2 -- 7.10.3: 4.8.2.0 -- 8.0.2: 4.9.1.0 -- 8.2.2: 4.10.1.0 -- 8.4.3: 4.11.1.0 -- 8.6.1: 4.12.0.0 import Control.Exception import Data.Char import Data.Complex import Data.Data import Data.Fixed import Data.Functor.Compose -- new import qualified Data.Functor.Const -- new import Data.Functor.Identity -- new import Data.Functor.Product -- new import Data.Functor.Sum -- new import Data.List.NonEmpty -- new import qualified Data.Monoid import Data.Ord import qualified Data.Semigroup -- new import Data.Version import Data.Void -- new import Foreign.C.Error import Foreign.C.Types #if MIN_VERSION_base(4,11,0) import GHC.ByteOrder -- new #endif import GHC.Conc -- new import GHC.ExecutionStack -- new import GHC.Exts -- new -- import GHC.Events -- platform-specific, omitted import GHC.Fingerprint -- new import GHC.Float -- new import qualified GHC.Generics -- new import GHC.IO.Buffer -- new import GHC.IO.Device -- new import GHC.IO.Encoding -- new import GHC.IO.Encoding.Failure -- new import GHC.IO.Exception -- new import GHC.IO.Handle -- new import GHC.RTS.Flags -- new import qualified GHC.Stack -- new import GHC.StaticPtr -- new import GHC.Stats -- new import System.Console.GetOpt import System.IO import Text.Printf import Text.Read.Lex import Generics.SOP.BasicFunctors import Generics.SOP.Classes import Generics.SOP.TH -- Types from Generics.SOP: deriveGeneric ''I deriveGeneric ''K deriveGeneric ''(:.:) deriveGeneric ''(-.->) -- new -- Cannot derive instances for Sing -- Cannot derive instances for Shape -- Cannot derive instances for NP, NS, POP, SOP -- Cannot derive instances for metadata types -- Types from the Prelude: deriveGeneric ''Bool deriveGeneric ''Ordering deriveGeneric ''Maybe deriveGeneric ''Either deriveGeneric ''() deriveGeneric ''(,) -- 2 deriveGeneric ''(,,) deriveGeneric ''(,,,) deriveGeneric ''(,,,,) -- 5 deriveGeneric ''(,,,,,) deriveGeneric ''(,,,,,,) deriveGeneric ''(,,,,,,,) deriveGeneric ''(,,,,,,,,) deriveGeneric ''(,,,,,,,,,) -- 10 deriveGeneric ''(,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,,) -- 15 deriveGeneric ''(,,,,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,,,,,,,) -- 20 deriveGeneric ''(,,,,,,,,,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,,,,,,,,,,,,) -- 25 deriveGeneric ''(,,,,,,,,,,,,,,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,,,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,,,,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,,,,,,,,,,,,,,,,) deriveGeneric ''(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) -- 30 deriveGeneric ''[] -- Other types from base: -- From Control.Exception: deriveGeneric ''IOException deriveGeneric ''ArithException deriveGeneric ''ArrayException deriveGeneric ''AssertionFailed deriveGeneric ''AsyncException deriveGeneric ''NonTermination deriveGeneric ''NestedAtomically deriveGeneric ''BlockedIndefinitelyOnMVar deriveGeneric ''BlockedIndefinitelyOnSTM deriveGeneric ''AllocationLimitExceeded -- new deriveGeneric ''Deadlock deriveGeneric ''NoMethodError deriveGeneric ''PatternMatchFail deriveGeneric ''RecConError deriveGeneric ''RecSelError deriveGeneric ''RecUpdError deriveGeneric ''ErrorCall deriveGeneric ''TypeError -- new deriveGeneric ''MaskingState -- From Data.Char: deriveGeneric ''GeneralCategory -- From Data.Complex: deriveGeneric ''Complex -- From Data.Data: deriveGeneric ''DataRep deriveGeneric ''Fixity deriveGeneric ''ConstrRep -- From Data.Fixed: deriveGeneric ''Fixed deriveGeneric ''E0 deriveGeneric ''E1 deriveGeneric ''E2 deriveGeneric ''E3 deriveGeneric ''E6 deriveGeneric ''E9 deriveGeneric ''E12 -- From Data.Functor.Compose deriveGeneric ''Compose -- new -- From Data.Functor.Const deriveGeneric ''Data.Functor.Const.Const -- new -- From Data.Functor.Identity deriveGeneric ''Identity -- new -- From Data.Functor.Product deriveGeneric ''Product -- new -- From Data.Functor.Sum deriveGeneric ''Sum -- new -- From Data.List.NonEmpty deriveGeneric ''NonEmpty -- new -- From Data.Monoid: deriveGeneric ''Data.Monoid.Dual deriveGeneric ''Data.Monoid.Endo deriveGeneric ''Data.Monoid.All deriveGeneric ''Data.Monoid.Any deriveGeneric ''Data.Monoid.Sum deriveGeneric ''Data.Monoid.Product deriveGeneric ''Data.Monoid.First deriveGeneric ''Data.Monoid.Last deriveGeneric ''Data.Monoid.Alt -- new -- From Data.Ord: deriveGeneric ''Down -- From Data.Proxy: deriveGeneric ''Proxy -- From Data.Semigroup: deriveGeneric ''Data.Semigroup.Min -- new deriveGeneric ''Data.Semigroup.Max -- new deriveGeneric ''Data.Semigroup.First -- new deriveGeneric ''Data.Semigroup.Last -- new deriveGeneric ''Data.Semigroup.WrappedMonoid -- new #if !MIN_VERSION_base(4,16,0) deriveGeneric ''Data.Semigroup.Option -- new #endif deriveGeneric ''Data.Semigroup.Arg -- new -- From Data.Version: deriveGeneric ''Version -- From Data.Void: deriveGeneric ''Void -- new -- From Foreign.C.Error: deriveGeneric ''Errno -- From Foreign.C.Types: deriveGeneric ''CChar deriveGeneric ''CSChar deriveGeneric ''CUChar deriveGeneric ''CShort deriveGeneric ''CUShort deriveGeneric ''CInt deriveGeneric ''CUInt deriveGeneric ''CLong deriveGeneric ''CULong deriveGeneric ''CPtrdiff deriveGeneric ''CSize deriveGeneric ''CWchar deriveGeneric ''CSigAtomic deriveGeneric ''CLLong deriveGeneric ''CULLong deriveGeneric ''CIntPtr deriveGeneric ''CUIntPtr deriveGeneric ''CIntMax deriveGeneric ''CUIntMax deriveGeneric ''CClock deriveGeneric ''CTime deriveGeneric ''CUSeconds deriveGeneric ''CSUSeconds deriveGeneric ''CFloat deriveGeneric ''CDouble #if MIN_VERSION_base(4,11,0) -- From GHC.ByteOrder: deriveGeneric ''ByteOrder -- new #endif -- From GHC.Conc: deriveGeneric ''ThreadStatus -- new deriveGeneric ''BlockReason -- new -- From GHC.ExecutionStack: deriveGeneric ''Location -- new deriveGeneric ''SrcLoc -- new -- From GHC.Exts: deriveGeneric ''RuntimeRep -- new deriveGeneric ''VecCount -- new deriveGeneric ''VecElem -- new #if !MIN_VERSION_base(4,15,0) deriveGeneric ''SpecConstrAnnotation -- new #endif -- From GHC.Generics: deriveGeneric ''GHC.Generics.K1 -- new deriveGeneric ''GHC.Generics.U1 -- new deriveGeneric ''GHC.Generics.V1 -- new deriveGeneric ''GHC.Generics.Par1 -- new deriveGeneric ''GHC.Generics.M1 -- new deriveGeneric ''GHC.Generics.R -- new deriveGeneric ''GHC.Generics.S -- new deriveGeneric ''GHC.Generics.D -- new deriveGeneric ''GHC.Generics.C -- new deriveGeneric ''(GHC.Generics.:*:) -- new deriveGeneric ''(GHC.Generics.:+:) -- new deriveGeneric ''(GHC.Generics.:.:) -- new deriveGeneric ''GHC.Generics.Associativity -- new deriveGeneric ''GHC.Generics.DecidedStrictness -- new deriveGeneric ''GHC.Generics.SourceStrictness -- new deriveGeneric ''GHC.Generics.SourceUnpackedness -- new deriveGeneric ''GHC.Generics.Fixity -- new -- From GHC.IO.Buffer: deriveGeneric ''Buffer -- new deriveGeneric ''BufferState -- new -- From GHC.IO.Device: deriveGeneric ''IODeviceType -- new -- From GHC.IO.Encoding: deriveGeneric ''BufferCodec -- new deriveGeneric ''CodingProgress -- new -- From GHC.IO.Encoding.Failure: deriveGeneric ''CodingFailureMode -- new -- From GHC.Fingerprint deriveGeneric ''Fingerprint -- new -- From GHC.Float deriveGeneric ''FFFormat -- new -- From GHC.IO.Exception: #if MIN_VERSION_base(4,11,0) deriveGeneric ''FixIOException -- new deriveGeneric ''IOErrorType -- new #endif -- From GHC.IO.Handle: deriveGeneric ''HandlePosn -- new #if MIN_VERSION_base(4,10,0) deriveGeneric ''LockMode -- new #endif -- From GHC.RTS.Flags: deriveGeneric ''RTSFlags -- new deriveGeneric ''GiveGCStats -- new deriveGeneric ''GCFlags -- new deriveGeneric ''ConcFlags -- new deriveGeneric ''MiscFlags -- new deriveGeneric ''DebugFlags -- new deriveGeneric ''DoCostCentres -- new deriveGeneric ''CCFlags -- new deriveGeneric ''DoHeapProfile -- new deriveGeneric ''ProfFlags -- new deriveGeneric ''DoTrace -- new deriveGeneric ''TraceFlags -- new deriveGeneric ''TickyFlags -- new #if MIN_VERSION_base(4,10,0) deriveGeneric ''ParFlags -- new #endif -- From GHC.Stack: deriveGeneric ''GHC.Stack.SrcLoc -- new deriveGeneric ''GHC.Stack.CallStack -- new -- From GHC.StaticPtr: deriveGeneric ''StaticPtrInfo -- new -- From GHC.Stats: #if MIN_VERSION_base(4,10,0) deriveGeneric ''RTSStats -- new deriveGeneric ''GCDetails -- new #endif #if !MIN_VERSION_base(4,11,0) deriveGeneric ''GCStats -- new #endif -- From System.Console.GetOpt: deriveGeneric ''ArgOrder deriveGeneric ''OptDescr deriveGeneric ''ArgDescr -- From System.Exit: deriveGeneric ''ExitCode -- From System.IO: deriveGeneric ''IOMode deriveGeneric ''BufferMode deriveGeneric ''SeekMode deriveGeneric ''Newline deriveGeneric ''NewlineMode -- From Text.Printf: deriveGeneric ''FieldFormat deriveGeneric ''FormatAdjustment deriveGeneric ''FormatSign deriveGeneric ''FormatParse -- From Text.Read.Lex: deriveGeneric ''Lexeme deriveGeneric ''Number -- Abstract / primitive datatypes (we don't derive Generic for these): -- -- Ratio -- Integer -- ThreadId -- Chan -- MVar -- QSem -- QSemN -- DataType -- Dynamic -- IORef -- TypeRep -- TyCon -- TypeRepKey -- KProxy -- not abstract, but intended for kind-level use -- STRef -- Unique -- ForeignPtr -- CFile -- CFpos -- CJmpBuf -- Pool -- Ptr -- FunPtr -- IntPtr -- WordPtr -- StablePtr -- Char -- Double -- Float -- Int -- Int8 -- Int16 -- Int32 -- Int64 -- Word -- Word8 -- Word16 -- Word32 -- Word64 -- IO -- ST -- (->) -- RealWorld -- Handle -- HandlePosn -- TextEncoding -- StableName -- Weak -- ReadP -- ReadPrec -- STM -- TVar -- Natural -- Event -- EventManager -- CostCentre -- CostCentreStack -- -- Datatypes we cannot currently handle: -- -- SomeException -- SomeAsyncException -- Handler -- Coercion -- (:~:)
well-typed/generics-sop
generics-sop/src/Generics/SOP/Instances.hs
bsd-3-clause
10,468
0
7
1,232
2,695
1,561
1,134
236
0
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : dave.laing.80@gmail.com Stability : experimental Portability : non-portable -} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} module Fragment.Record.Rules.Type.Infer.Offline ( RecordInferTypeContext , recordInferTypeRules ) where import Rules.Type.Infer.Offline import qualified Fragment.Record.Rules.Type.Infer.Common as R type RecordInferTypeContext e w s r m ki ty pt tm a = R.RecordInferTypeContext e w s r m (UnifyT ki ty a m) ki ty pt tm a recordInferTypeRules :: RecordInferTypeContext e w s r m ki ty pt tm a => InferTypeInput e w s r m (UnifyT ki ty a m) ki ty pt tm a recordInferTypeRules = R.inferTypeInput
dalaing/type-systems
src/Fragment/Record/Rules/Type/Infer/Offline.hs
bsd-3-clause
749
0
8
151
165
99
66
13
1
-- Copyright 2021 Google LLC -- -- Use of this source code is governed by a BSD-style -- license that can be found in the LICENSE file or at -- https://developers.google.com/open-source/licenses/bsd {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE OverloadedStrings #-} -- NOTE: Use LLVM.JIT instead of this version-specific module! module LLVM.HEAD.JIT where import Control.Monad import Control.Exception import Foreign.Ptr import Data.IORef import Data.String import Data.List (sortBy) import System.IO import System.IO.Temp import qualified Data.ByteString.Char8 as C8BS import qualified Data.ByteString.Short as SBS import qualified Data.ByteString as BS import qualified LLVM.OrcJIT as OrcJIT import qualified LLVM.Target as T import qualified LLVM.AST import qualified LLVM.AST.Global as LLVM.AST import qualified LLVM.AST.Constant as C import qualified LLVM.Module as LLVM import qualified LLVM.Context as LLVM data JIT = JIT { session :: OrcJIT.ExecutionSession , objectLayer :: OrcJIT.RTDyldObjectLinkingLayer , compileLayer :: OrcJIT.IRCompileLayer , nextDylibId :: IORef Int } -- XXX: The target machine cannot be destroyed before JIT is destroyed createJIT :: T.TargetMachine -> IO JIT createJIT tm = do session <- OrcJIT.createExecutionSession objectLayer <- OrcJIT.createRTDyldObjectLinkingLayer session compileLayer <- OrcJIT.createIRCompileLayer session objectLayer tm nextDylibId <- newIORef 0 return JIT{..} destroyJIT :: JIT -> IO () destroyJIT JIT{..} = OrcJIT.disposeExecutionSession session withJIT :: T.TargetMachine -> (JIT -> IO a) -> IO a withJIT tm = bracket (createJIT tm) destroyJIT data NativeModule = NativeModule { moduleJIT :: JIT , moduleDylib :: OrcJIT.JITDylib , moduleDtors :: [FunPtr (IO ())] } type CompilationPipeline = LLVM.Module -> IO () type ObjectFileContents = BS.ByteString -- TODO: This leaks resources if we fail halfway compileModule :: JIT -> [ObjectFileContents] -> LLVM.AST.Module -> CompilationPipeline -> IO NativeModule compileModule moduleJIT@JIT{..} objFiles ast compilationPipeline = do tsModule <- LLVM.withContext \c -> LLVM.withModuleFromAST c ast \m -> do compilationPipeline m OrcJIT.cloneAsThreadSafeModule m moduleDylib <- newDylib moduleJIT mapM_ (loadObjectFile moduleJIT moduleDylib) objFiles OrcJIT.addDynamicLibrarySearchGeneratorForCurrentProcess compileLayer moduleDylib OrcJIT.addModule tsModule moduleDylib compileLayer moduleDtors <- forM dtorNames \dtorName -> do Right (OrcJIT.JITSymbol dtorAddr _) <- OrcJIT.lookupSymbol session compileLayer moduleDylib $ fromString dtorName return $ castPtrToFunPtr $ wordPtrToPtr dtorAddr return NativeModule{..} where -- Unfortunately the JIT layers we use here don't handle the destructors properly, -- so we have to find and call them ourselves. dtorNames = do let dtorStructs = flip foldMap (LLVM.AST.moduleDefinitions ast) \case LLVM.AST.GlobalDefinition LLVM.AST.GlobalVariable{ name="llvm.global_dtors", initializer=Just (C.Array _ elems)} -> elems _ -> [] -- Sort in the order of decreasing priority! fmap snd $ sortBy (flip compare) $ flip fmap dtorStructs $ \(C.Struct _ _ [C.Int _ n, C.GlobalReference _ (LLVM.AST.Name dname), _]) -> (n, C8BS.unpack $ SBS.fromShort dname) foreign import ccall "dynamic" callDtor :: FunPtr (IO ()) -> IO () -- TODO: This might not release everything if it fails halfway unloadNativeModule :: NativeModule -> IO () unloadNativeModule NativeModule{..} = do -- TODO: Clear the dylib forM_ moduleDtors callDtor withNativeModule :: JIT -> [ObjectFileContents] -> LLVM.AST.Module -> CompilationPipeline -> (NativeModule -> IO a) -> IO a withNativeModule jit objs m p = bracket (compileModule jit objs m p) unloadNativeModule getFunctionPtr :: NativeModule -> String -> IO (FunPtr a) getFunctionPtr NativeModule{..} funcName = do let JIT{..} = moduleJIT Right (OrcJIT.JITSymbol funcAddr _) <- OrcJIT.lookupSymbol session compileLayer moduleDylib (fromString funcName) return $ castPtrToFunPtr $ wordPtrToPtr funcAddr newDylib :: JIT -> IO OrcJIT.JITDylib newDylib jit = do let ref = nextDylibId jit dylibId <- readIORef ref <* modifyIORef' ref (+1) let name = fromString $ "module" ++ show dylibId OrcJIT.createJITDylib (session jit) name loadObjectFile :: JIT -> OrcJIT.JITDylib -> ObjectFileContents -> IO () loadObjectFile jit dylib objFileContents = do withSystemTempFile "objfile.o" \path h -> do BS.hPut h objFileContents hFlush h OrcJIT.addObjectFile (objectLayer jit) dylib path
google-research/dex-lang
src/lib/LLVM/HEAD/JIT.hs
bsd-3-clause
4,836
0
23
946
1,256
649
607
-1
-1
module Main where import Test.Hspec import Test.QuickCheck import Lib(fibs, buzz, isPrime) numFibs = 10000 main :: IO () main = hspec $ do describe "Fibonacci Numbers" $ do it "Numbers equal to the sum of the last two" $ lastTwoSum $ take numFibs fibs it "First 10 equal 0, 1, 1, 2, 3, 5, 8, 13, 21, 34" $ take 10 fibs `shouldBe` [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] it "15 prints FizzBuzz" $ buzz 15 `shouldBe` "FizzBuzz" it "6 prints Buzz" $ buzz 6 `shouldBe` "Buzz" it "10 prints Fizz" $ buzz 10 `shouldBe` "Fizz" it "7 prints BuzzFizz" $ buzz 7 `shouldBe` "BuzzFizz" it "8 prints 8" $ buzz 8 `shouldBe` "8" describe "isPrime" $ do it "1 is not prime" $ isPrime 1 `shouldBe` False it "2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 all prime" $ all isPrime [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] it "Two numbers > 1 multiplied together are not prime" $ property prop_TwoMultNotPrime lastTwoSum :: [Integer] -> Bool lastTwoSum (x:x2:x3:xs) = (x + x2 == x3) && lastTwoSum xs lastTwoSum _ = True prop_TwoMultNotPrime n m = (n > 1 && m > 1) ==> not $ isPrime (n * m)
DrewBarclay/fibbuzz
test/Spec.hs
bsd-3-clause
1,107
0
13
261
421
218
203
23
1
{- -} module HCParser where import HOCHC.Parser import HOCHC.Tokeniser import Text.Parsec.Prim import Text.Parsec.Combinator import Data.Char import Data.Maybe import Data.List(sortBy) import Data.Ord(comparing) import HOCHC.DataTypes import Control.Applicative((<**>)) lineParser :: MyParser [Term] lineParser = (formula >>= return.return) <|> parserReturn [] parser :: MyParser [Term] parser = do res <- chainl lineParser (tok "\n" >> return (++)) [] eof return res environmentLine :: MyParser DeltaEnv environmentLine = (do (Variable v) <- variable tok ":" s<-sort return [(v,s)]) <|> return [] separator = (tok ";" >> tok "\n") <|> tok "\n" <|> return "" file :: MyParser (DeltaEnv,[Term],Term) file = do tok "environment" >> tok "\n" d <- chainl1 environmentLine (tok "\n">>return (++)) separator >> tok "program" >> tok "\n" prog <- chainl1 lineParser (tok "\n" >> return (++)) separator >> tok "goal" >> tok "\n" goal <- formula eof <|> (tok ";" >> eof) return (d,prog,goal) parseFile :: String -> String -> Either String (DeltaEnv,[Term],Term) parseFile fname contents = fromParse (do ts <- tokeniseFromFile (["environment","program","goal"] ++ symbols ++ map fst cannonicals) fname contents let body = map cannonise ts runParser file () fname body) fromParse (Left x) = Left $ show x fromParse (Right x) = Right x --for testing --qp = (>>= (runParser formula () "" . map cannonise)) . tokeniseFromOps (symbols ++ map fst cannonicals)
penteract/HigherOrderHornRefinement
HOCHC/Refinement/HCParser.hs
bsd-3-clause
1,568
0
14
338
580
295
285
43
1
module RPF.State where import Data.IP import Network.DNS.Types (Domain) import Network.DomainAuth import RPF.Types type ConstName = String type ConstTable = [(ConstName, Constant)] data ParserState = ParserState { consttbl :: ConstTable , used :: [ConstName] , unused :: [ConstName] , iplol :: [[IPRange]] , ipcnt :: Int , domlol :: [[Domain]] , domcnt :: Int , reslol :: [[DAResult]] , rescnt :: Int , blocks :: [BlockName] } deriving Show initialState :: ParserState initialState = ParserState { consttbl = [] , used = [] , unused = [] , iplol = [] , ipcnt = 0 , domlol = [] , domcnt = 0 , reslol = [] , rescnt = 0 , blocks = [minBound..maxBound] }
kazu-yamamoto/rpf
RPF/State.hs
bsd-3-clause
748
0
10
212
241
155
86
31
1
module Language.BCoPL.DataLevel.EvalML1Err where -- import Debug.Trace import Data.Char (toLower) import Language.BCoPL.DataLevel.ML1 import Language.BCoPL.DataLevel.Derivation (Tree(..),Deducer,sessionGen,sessionGen') data Judge = EvalTo Exp (Maybe Val) | Plus {k,m,n :: Int} | Minus {k,m,n :: Int} | Times {k,m,n :: Int} | LessThan {p,q :: Int, r :: Bool} instance Show Judge where show (EvalTo e (Just v)) = unwords [show e,"evalto",show v] show (EvalTo e Nothing) = unwords [show e,"evalto","error"] show (Plus k m n) = unwords [show k,"plus", show m,"is",show n] show (Minus k m n) = unwords [show k,"minus",show m,"is",show n] show (Times k m n) = unwords [show k,"times",show m,"is",show n] show (LessThan p q r) = unwords [show p,"less than",show q,"is",map toLower (show r)] instance Read Judge where readsPrec _ s = case words s of ws -> case break ("evalto"==) ws of (xs,_:ys) -> if ys == ["error"] then [(EvalTo (read (concat xs)) Nothing,"")] else [(EvalTo (read (concat xs)) (Just (read (concat ys))),"")] _ -> case break ("plus"==) ws of ([k],_:m:"is":[n]) -> [(Plus (read k) (read m) (read n),"")] _ -> case break ("minus"==) ws of ([k],_:m:"is":[n]) -> [(Minus (read k) (read m) (read n),"")] _ -> case break ("times"==) ws of ([k],_:m:"is":[n]) -> [(Times (read k) (read m) (read n),"")] _ -> case break ("less"==) ws of ([p],_:_:q:"is":[r]) -> [(LessThan (read p) (read q) (read r),"")] _ -> error ("Syntax error!: " ++ s) deduce :: Deducer Judge deduce j = case j of EvalTo e Nothing -> case e of IF e1 e2 e3 -> take 1 $ [ Node ("E-IfError",j) [err] | err <- deduce (EvalTo e1 Nothing) ] ++ [ Node ("E-IfTError",j) [k,err] | k <- deduce (EvalTo e1 (Just (Bool True))) , err <- deduce (EvalTo e2 Nothing) ] ++ [ Node ("E-IfFError",j) [k,err] | k <- deduce (EvalTo e1 (Just (Bool False))) , err <- deduce (EvalTo e3 Nothing) ] ++ [ Node ("E-IfInt",j) [k] | i <- ints maxBound , k <- deduce (EvalTo e1 (Just (Int i))) ] e1 :+: e2 -> take 1 $ [ Node ("E-PlusBoolL",j) [k] | b <- [False,True] , k <- deduce (EvalTo e1 (Just (Bool b))) ] ++ [ Node ("E-PlusBoolR",j) [k] | b <- [False,True] , k <- deduce (EvalTo e2 (Just (Bool b))) ] ++ [ Node ("E-PlusErrorL",j) [err] | err <- deduce (EvalTo e1 Nothing) ] ++ [ Node ("E-PlusErrorR",j) [err] | err <- deduce (EvalTo e2 Nothing) ] e1 :-: e2 -> take 1 $ [ Node ("E-MinusBoolL",j) [k] | b <- [False,True] , k <- deduce (EvalTo e1 (Just (Bool b))) ] ++ [ Node ("E-MinusBoolR",j) [k] | b <- [False,True] , k <- deduce (EvalTo e2 (Just (Bool b))) ] ++ [ Node ("E-MinusErrorL",j) [err] | err <- deduce (EvalTo e1 Nothing) ] ++ [ Node ("E-MinusErrorR",j) [err] | err <- deduce (EvalTo e2 Nothing) ] e1 :*: e2 -> take 1 $ [ Node ("E-TimesBoolL",j) [k] | b <- [False,True] , k <- deduce (EvalTo e1 (Just (Bool b))) ] ++ [ Node ("E-TimesBoolR",j) [k] | b <- [False,True] , k <- deduce (EvalTo e2 (Just (Bool b))) ] ++ [ Node ("E-TimesErrorL",j) [err] | err <- deduce (EvalTo e1 Nothing) ] ++ [ Node ("E-TimesErrorR",j) [err] | err <- deduce (EvalTo e2 Nothing) ] e1 :<: e2 -> take 1 $ [ Node ("E-LtBoolL",j) [k] | b <- [False,True] , k <- deduce (EvalTo e1 (Just (Bool b))) ] ++ [ Node ("E-LtBoolR",j) [k] | b <- [False,True] , k <- deduce (EvalTo e2 (Just (Bool b))) ] ++ [ Node ("E-LtErrorL",j) [err] | err <- deduce (EvalTo e1 Nothing) ] ++ [ Node ("E-LtErrorR",j) [err] | err <- deduce (EvalTo e2 Nothing) ] Val _ -> [] EvalTo e (Just v) -> case v of Int n -> case e of Val (Int n') | n' == n -> [Node ("E-Int",j) []] | True -> [] IF e1 e2 e3 -> take 1 $ [ Node ("E-IfT",j) [j1,j2] | j1 <- deduce (EvalTo e1 (Just (Bool True))) , j2 <- deduce (EvalTo e2 (Just (Int n))) ] ++ [ Node ("E-IfF",j) [j1,j2] | j1 <- deduce (EvalTo e1 (Just (Bool False))) , j2 <- deduce (EvalTo e3 (Just (Int n))) ] e1 :+: e2 -> take 1 $ [ Node ("E-Plus",j) [j1,j2,j3] | n1 <- ints (n^2) , j1 <- deduce (EvalTo e1 (Just (Int n1))) , n2 <- ints (n^2) , j2 <- deduce (EvalTo e2 (Just (Int n2))) , j3 <- deduce (Plus n1 n2 n) ] e1 :-: e2 -> take 1 $ [ Node ("E-Minus",j) [j1,j2,j3] | n1 <- ints (n^2) , j1 <- deduce (EvalTo e1 (Just (Int n1))) , n2 <- ints (n^2) , j2 <- deduce (EvalTo e2 (Just (Int n2))) , j3 <- deduce (Minus n1 n2 n) ] e1 :*: e2 -> take 1 $ [ Node ("E-Times",j) [j1,j2,j3] | n1 <- ints (n^2) , j1 <- deduce (EvalTo e1 (Just (Int n1))) , n2 <- ints (n^2) , j2 <- deduce (EvalTo e2 (Just (Int n2))) , j3 <- deduce (Times n1 n2 n) ] _ -> [] Bool b -> case e of Val (Bool b') | b == b' -> [ Node ("E-Bool",j) []] | True -> [] e1 :<: e2 -> take 1 $ [ Node ("E-Lt",j) [j1,j2,j3] | n1 <- ints maxBound , j1 <- deduce (EvalTo e1 (Just (Int n1))) , n2 <- ints maxBound , j2 <- deduce (EvalTo e2 (Just (Int n2))) , j3 <- deduce (LessThan n1 n2 True) ] IF e1 e2 e3 -> take 1 $ [ Node ("E-IfT",j) [j1,j2] | j1 <- deduce (EvalTo e1 (Just (Bool True))) , j2 <- deduce (EvalTo e2 (Just (Bool b))) ] ++ [ Node ("E-IfF",j) [j1,j2] | j1 <- deduce (EvalTo e1 (Just (Bool False))) , j2 <- deduce (EvalTo e3 (Just (Bool b))) ] _ -> [] Plus k m n -> [ Node ("B-Plus",j) [] | k+m == n ] Minus k m n -> [ Node ("B-Minus",j) [] | k-m == n ] Times k m n -> [ Node ("B-Times",j) [] | k*m == n ] LessThan p q r -> [ Node ("B-Lt",j) [] | (p<q) == r ] ints :: Int -> [Int] ints m = takeWhile ((abs m >=) . abs) $ tail $ [0..] >>= \n -> [f n | f <- [id,negate]] session,session' :: IO () session = sessionGen ("EvalML1Err> ",deduce) session' = sessionGen' ("EvalML1Err> ",deduce)
nobsun/hs-bcopl
src/Language/BCoPL/DataLevel/EvalML1Err.hs
bsd-3-clause
8,283
1
30
3,950
3,557
1,855
1,702
169
20
{-# OPTIONS -XCPP -XDeriveDataTypeable #-} module SearchCart ( searchCart ) where import Data.TCache.DefaultPersistence import Data.TCache.DefaultPersistence import Data.TCache.IndexQuery as Q import Data.TCache.IndexText import Data.Maybe import qualified Data.Map as M import Control.Workflow.Configuration import Control.Workflow (Workflow) import qualified Data.Text.Lazy as T import Data.ByteString.Lazy.Char8 import Data.Typeable -- #define ALONE -- to execute it alone, uncomment this #ifdef ALONE import MFlow.Wai.Blaze.Html.All main= runNavigation "" searchCart #else import MFlow.Wai.Blaze.Html.All hiding(retry, page) import Menu #endif type ProductName= String type Quantity= Int type Price= Float type Cart= M.Map ProductName (Quantity, Price) showCart :: Cart -> String showCart = show data Product= Product{ namep :: String , typep :: [String] , descriptionp :: String , pricep :: Price , stock :: Int} deriving (Read,Show,Typeable) instance Indexable Product where key prod= "Prod "++ namep prod instance Serializable Product where serialize= pack . show deserialize= read . unpack setPersist= const $ Just filePersist createProducts= atomically $ mapM newDBRef [ Product "ipad 3G" ["gadget","pad"] "ipad 8GB RAM, 3G" 400 200 , Product "ipad" ["gadget","pad"] "ipad 8 GB RAM" 300 300 , Product "iphone 3" ["gadget","phone"] "iphone 3 nice and beatiful" 200 100 ] searchCart :: FlowM Html (Workflow IO) () searchCart = do liftIO $ runConfiguration "createprods" $ do -- better put this in main ever $ Q.index namep ever $ indexList typep (Prelude.map T.pack) ever $ indexText descriptionp T.pack once createProducts catalog where catalog = do bought <- step buyProduct shoppingCart bought catalog buyProduct :: FlowM Html IO ProductName buyProduct = do ttypes <- atomic $ allElemsOf typep let types= Prelude.map T.unpack ttypes r <- page $ h1 << "Product catalog" ++> p << "search" ++> (Left <$> getString Nothing) <|> p << "or choose product types" ++> (Right <$> showList types) prods <- case r of Left str -> atomic $ Q.select namep $ descriptionp `contains` str Right (Just type1) -> atomic $ Q.select namep $ typep `containsElem` type1 Right Nothing -> return [] if Prelude.null prods then do page $ b << "no match " ++> wlink () << b << "search again" buyProduct else do let search= case r of Left str -> "for search of the term " ++ str Right (Just type1) -> "of the type "++ type1 r <- page $ h1 << ("Products " ++ search) ++> showList prods case r of Nothing -> buyProduct Just prod -> breturn prod shoppingCart bought= do cart <- getSessionData `onNothing` return (M.empty :: Cart) let (n,price) = fromMaybe (0,undefined) $ M.lookup bought cart (n,price) <- step $ do if n /= 0 then return (n,price) else do [price] <- atomic $ Q.select pricep $ namep .==. bought return (n, price) setSessionData $ M.insert bought (n+1,price) cart step $ do r <- page $ do cart <- getSessionData `onNothing` return (M.empty :: Cart) h1 << "Shopping cart:" ++> p << showCart cart ++> wlink True << b << "continue shopping" <|> wlink False << p << "proceed to buy" if not r then page $ wlink () << "not implemented, click here" else breturn () atomic= liftIO . atomically showList []= wlink Nothing << p << "no results" showList xs= Just <$> firstOf [wlink x << p << x | x <- xs]
agocorona/MFlow
Demos/SearchCart.hs
bsd-3-clause
4,068
0
24
1,306
1,178
608
570
93
9
{-#LANGUAGE TypeOperators#-} {-#LANGUAGE DataKinds#-} module Problem700 where import Data.Array import Data.Modular import Data.Maybe type ModN = Integer / 4503599627370517 b = 4503599627370517 :: Integer a = 1504170715041707 :: ModN a' = fromJust $ inv (-a) bigOnes = take 16 $ iterate (\x -> head $ filter (< x) $ map (\n -> x + a * n) [1 ..]) a smallLim = last bigOnes convert :: ModN -> Int convert = fromIntegral . unMod deltas :: Array Int ModN deltas = listArray (1, convert smallLim) (scanl1 min $ iterate (+ a') a') smallOnes = tail $ takeWhile (> 0) $ iterate (\c -> c + a * (deltas ! convert c)) smallLim main :: IO () main = print $ sum (smallOnes ++ bigOnes) {- -} {- ak = bq + r 0 <= r <= x 0 <= ak - bq <= x 0 <= k - bq/a <= x/a bq/a <= k <= (bq+x)/a bq <= k <= bq+x also an in [-1, -2, ... -x] so n in [-a', -2a', ... -xa'] -} {- (1,1504170715041707) (3,8912517754604) (506,2044785486369) (2527,1311409677241) (4548,578033868113) (11117,422691927098) (17686,267349986083) (24255,112008045068) (55079,68674149121) (85903,25340253174) (202630,7346610401) (724617,4046188430) (1246604,745766459) (6755007,428410324) (12263410,111054189) (42298633,15806432) (326125654,15397267) (609952675,14988102) (893779696,14578937) (1177606717,14169772) (1461433738,13760607) 2 503 2021 2021 6569 6569 6569 30824 30824 116727 521987 521987 5508403 5508403 30035223 -}
adityagupta1089/Project-Euler-Haskell
src/problems/Problem700.hs
bsd-3-clause
1,391
0
14
236
286
158
128
20
1
------------------------------------------------------------------------------- ---- | ---- Module : Language.MUDA.PPrint ---- Copyright : (c) Syoyo Fujita ---- License : BSD-style ---- ---- Maintainer : syoyo@lighttransport.com ---- Stability : experimental ---- Portability : GHC 6.10 ---- ---- PPrint : Pretty Printer for MUDA AST. ---- ------------------------------------------------------------------------------- module Language.MUDA.PPrint where import Text.PrettyPrint.HughesPJ -- Import local modules import Language.MUDA.AST -- | Pretty printer class class Pretty p where pretty :: p -> Doc instance Pretty Func where pretty (Func name stms) = text name instance Pretty MUDAUnit where pretty (MUDAUnit funcs) = vcat (map pretty funcs)
syoyo/MUDA
Language/MUDA/PPrint.hs
bsd-3-clause
786
0
8
130
112
66
46
9
0
-- | This module reexports 'Data.ListTrie.RegExp.Weighted' for now. module Data.ListTrie.RegExp ( module Data.ListTrie.RegExp.Weighted ) where import Data.ListTrie.RegExp.Weighted
baldo/regexp-tries
src/Data/ListTrie/RegExp.hs
bsd-3-clause
191
0
5
28
25
18
7
3
0
module CodeWidget.CodeWidgetUtil where import qualified Graphics.UI.Gtk as G import Text.Parsec import Text.Parsec.Pos import Data.List import Util import CodeWidget.CodeWidgetTypes maybePrtStrLn :: Bool -> String -> IO () maybePrtStrLn b s = do if' (b == True) (putStrLn s) (return ()) dbgPrints :: Bool dbgPrints = False --dbgPrints = True mpStrLn :: String -> IO () mpStrLn = maybePrtStrLn dbgPrints apiDbgPrints :: Bool apiDbgPrints = False --apiDbgPrints = True; apiStrLn :: String -> IO () apiStrLn = maybePrtStrLn apiDbgPrints rgnBgColorTbl :: [String] rgnBgColorTbl = "#ffdead" --orange : "#d7f1ee" --lime green : "#ffcfca" --melon : "#c5e9bc" --yellow : [] rgnFgColorTbl :: String rgnFgColorTbl = "#0000ff" getRgnBgColor :: RegionID -> String getRgnBgColor r = rgnBgColorTbl !! (r `mod` 4) getRgnFgColor :: RegionID -> String getRgnFgColor _ = rgnFgColorTbl getPage :: CodeView -> PageID -> Maybe PageContext getPage cv p = let pgs = filter (\x -> p == (pgID x)) $ cvPages cv in case pgs of [] -> Nothing _ -> Just (head pgs) -- get the specified page and region contexts, maybe getContexts :: CodeView -> Region -> Maybe CwRef getContexts cv r = let pgs = filter (\x -> (pid r) == (pgID x)) $ cvPages cv in case pgs of [] -> Nothing _ -> let pc = head pgs rgs = filter (\x -> (rid r) == (rcRegion x)) (pgRegions pc) in case rgs of [] -> Nothing _ -> Just (pc, (head rgs)) -- get the specified region context, maybe getRegion :: PageContext -> RegionID -> Maybe RegionContext getRegion pg r = let rgs = filter (\x -> r == (rcRegion x)) $ pgRegions pg in case rgs of [] -> Nothing _ -> Just (head rgs) -- get a list of all regions except the specified one otherRegions :: PageContext -> RegionID -> [RegionContext] otherRegions pg r = sort $ filter (\x -> r /= (rcRegion x)) $ pgRegions pg -- get a list of all pages except the specified one otherPages :: CodeView -> PageID -> [PageContext] otherPages cv p = filter (\x -> p /= (pgID x)) $ cvPages cv -- get a list if all subregions of this region childRegions :: PageContext -> RegionContext -> [RegionContext] childRegions pg r = filter (\x -> rcRegion r == (rcParent x)) $ pgRegions pg -- return a list of all editable regions editableRgns :: PageContext -> [RegionContext] editableRgns pg = filter rcEditable (pgRegions pg) -- Get a list of regions which are nested in the specified region subRegions :: PageContext -> RegionContext -> [RegionContext] subRegions pg rc = sort $ childRegions pg rc nonRootRegions :: PageContext -> [RegionContext] nonRootRegions pg = otherRegions pg rootRegion eRgnNestDepth :: PageContext -> RegionID -> Int eRgnNestDepth pg par = if (noRegion /= par) then case getRegion pg par of Nothing -> 0 Just x -> eRgnNestDepth' pg x 0 else 0 eRgnNestDepth' pg rc n = if (noRegion /= rcParent rc) then case getRegion pg (rcParent rc) of Nothing -> n Just x -> eRgnNestDepth' pg x newn where newn = if' (rcEditable x) (n+1) n else n rgnBg :: PageContext -> RegionContext -> IO () rgnBg pg rc = do si <- rgnStart pg rc ei <- rgnEnd pg rc G.textBufferApplyTag (pgBuffer pg) (rcBgTag rc) si ei -- is specified region the rootRegion? isRoot :: RegionContext -> Bool isRoot rc = if' (rcRegion rc == rootRegion) True False -- create a new left-side mark newLeftMark :: IO G.TextMark newLeftMark = do mk <- G.textMarkNew Nothing True G.textMarkSetVisible mk False return mk -- create a new right-side mark newRightMark :: IO G.TextMark newRightMark = do mk <- G.textMarkNew Nothing False G.textMarkSetVisible mk False return mk -- Get a TextIter set to the start of the region rgnStart :: PageContext -> RegionContext -> IO G.TextIter rgnStart pg rc = do iter <- G.textBufferGetIterAtMark (pgBuffer pg) (rcStart rc) return iter -- Get a TextIter set to the end of the region rgnEnd :: PageContext -> RegionContext -> IO G.TextIter rgnEnd pg rc = do iter <- G.textBufferGetIterAtMark ( pgBuffer pg) (rcEnd rc) return iter -- convert a TextIter into a SourcePos posFromIter :: PageContext -> G.TextIter -> IO SourcePos posFromIter pg iter = do l <- G.textIterGetLine iter c <- G.textIterGetLineOffset iter return $ newPos (pgFileName pg) (l + 1) (c + 1) -- convert a root-relative position to a subregion-relative position mapPosToRgn :: PageContext -> RegionContext -> SourcePos -> IO SourcePos mapPosToRgn pg rc pos = do sp <- rgnStartPos pg rc return $ newPos (pgFileName pg) ((sourceLine pos) - (sourceLine sp) + 1) ((sourceColumn pos) - (sourceColumn sp) + 1) -- get region's current starting SourcePos - rgnStartPos :: PageContext -> RegionContext -> IO SourcePos rgnStartPos pg rc = do iter <- rgnStart pg rc posFromIter pg iter -- get region's initial position - may be different from current starting SourcePos due to edits to preceeding regions rgnInitPos :: PageContext -> RegionContext -> SourcePos rgnInitPos _ rc = rcStartPos rc -- get region's initial line rgnInitLine pg rc = sourceLine (rgnInitPos pg rc) -- get region's ending SourcePos rgnEndPos :: PageContext -> RegionContext -> IO SourcePos rgnEndPos pg rc = do iter <- rgnEnd pg rc posFromIter pg iter -- test if region has no text rgnEmpty :: PageContext -> RegionContext -> IO Bool rgnEmpty pg rc = do s <- rgnStartPos pg rc e <- rgnEndPos pg rc return $ if' (s == e) True False -- return the number of lines in a region rgnHeight :: PageContext -> RegionContext -> IO Line rgnHeight pg rc = do spos <- rgnStartPos pg rc epos <- rgnEndPos pg rc return $ (sourceLine epos) - (sourceLine spos) - (rcInitHeight rc) -- return the width of a region - the difference bewteen the region's position at creating and its current ending position column rgnWidth :: PageContext -> RegionContext -> IO Column rgnWidth pc rc = do spos <- rgnStartPos pc rc epos <- rgnEndPos pc rc return $ (sourceColumn epos) - (sourceColumn spos) - (rcInitWidth rc) -- Get a root-normalized TextIter for the given position rootIterFromPos :: PageContext -> SourcePos -> IO G.TextIter rootIterFromPos pg pos = do G.textBufferGetIterAtLineOffset (pgBuffer pg) (sourceLine pos - 1) (sourceColumn pos - 1)
termite2/code-widget
CodeWidget/CodeWidgetUtil.hs
bsd-3-clause
6,839
0
19
1,841
2,021
1,012
1,009
135
3
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} module Util where import Conduit import Control.Monad import Control.Monad.Primitive import qualified Data.Vector.Generic as V conduitVectorBounded :: ( MonadBase base m, V.Vector v a, PrimMonad base , Num size, Ord size) => (a -> size) -- ^ function to get element size -> size -- ^ maximum allowed vector size -> Int -- ^ maximum allowed length -> Conduit a m (v a) conduitVectorBounded f size len = loop where loop = do v <- sinkVectorN len unless (V.null v) $ do yieldMany $ splitBySize f size v loop {-# INLINE conduitVectorBounded #-} splitBySize :: (V.Vector v a, Num size, Ord size) => (a -> size) -> size -> v a -> [v a] splitBySize getSize maxSize v | V.null v = [] | V.null v1 = splitV (V.drop 1 v) | otherwise = v1 : splitV v2 where (v1, v2) = V.splitAt (maxSizeIndex getSize maxSize v) v splitV = splitBySize getSize maxSize {-# INLINE splitBySize #-} maxSizeIndex :: forall v a size. (V.Vector v a, Num size, Ord size) => (a -> size) -> size -> v a -> Int maxSizeIndex getSize maxSize = snd . V.ifoldl' f (0,0) where f :: (size, Int) -> Int -> a -> (size, Int) f acc i e = let s = fst acc + getSize e in (s,) (if s > maxSize then snd acc else i) {-# INLINE maxSizeIndex #-}
pavelkogan/es-reindex
src/Util.hs
bsd-3-clause
1,458
0
13
439
517
269
248
36
2
{-# OPTIONS_GHC -fno-warn-deprecations #-} module TagSoup.Test(test) where import Text.HTML.TagSoup import Text.HTML.TagSoup.Entity import Text.HTML.TagSoup.Match import Control.Monad import Data.List import Test.QuickCheck -- * The Test Monad type Test a = IO a pass :: Test () pass = return () runTest :: Test () -> IO () runTest x = x >> putStrLn "All tests passed" (===) :: (Show a, Eq a) => a -> a -> IO () a === b = if a == b then pass else fail $ "Does not equal: " ++ show a ++ " =/= " ++ show b check :: Testable prop => prop -> IO () check prop = do res <- quickCheckWithResult stdArgs{maxSuccess=1000} prop case res of Success{} -> pass _ -> fail "Property failed" newtype HTML = HTML String deriving Show instance Arbitrary HTML where arbitrary = fmap (HTML . concat) $ listOf $ elements frags where frags = map (:[]) " \n!-</>#&;xy01[]?'\"" ++ ["CDATA","amp","gt","lt"] shrink (HTML x) = map HTML $ zipWith (++) (inits x) (tail $ tails x) -- * The Main section test :: IO () test = runTest $ do warnTests parseTests optionsTests renderTests combiTests entityTests lazyTags == lazyTags `seq` pass matchCombinators {- | This routine tests the laziness of the TagSoup parser. For each critical part of the parser we provide a test input with a token of infinite size. Then the output must be infinite too. If the laziness is broken, then the output will stop early. We collect the thousandth character of the output of each test case. If computation of the list stops somewhere, you have found a laziness stopper. -} lazyTags :: [Char] lazyTags = map ((!!1000) . show . parseTags) [cycle "Rhabarber" ,repeat '&' ,"<"++cycle "html" ,"<html "++cycle "na!me=value " ,"<html name="++cycle "value" ,"<html name=\""++cycle "value" ,"<html name="++cycle "val!ue" ,"<html "++cycle "name" ,"</"++cycle "html" ,"<!-- "++cycle "comment" ,"<!"++cycle "doctype" ,"<!DOCTYPE"++cycle " description" ,cycle "1<2 " ,"&" ++ cycle "t" ,"<html name="++cycle "val&ue" ,"<html name="++cycle "va&l!ue" ,cycle "&amp; test" -- i don't see how this can work unless the junk gets into the AST? -- ,("</html "++cycle "junk") : ] matchCombinators :: Test () matchCombinators = do tagText (const True) (TagText "test") === True tagText ("test"==) (TagText "test") === True tagText ("soup"/=) (TagText "test") === True tagOpenNameLit "table" (TagOpen "table" [("id", "name")]) === True tagOpenLit "table" (anyAttrLit ("id", "name")) (TagOpen "table" [("id", "name")]) === True tagOpenLit "table" (anyAttrNameLit "id") (TagOpen "table" [("id", "name")]) === True tagOpenLit "table" (anyAttrLit ("id", "name")) (TagOpen "table" [("id", "other name")]) === False parseTests :: Test () parseTests = do parseTags "<!DOCTYPE TEST>" === [TagOpen "!DOCTYPE" [("TEST","")]] parseTags "<test \"foo bar\">" === [TagOpen "test" [("\"foo",""),("bar\"","")]] parseTags "<test baz \"foo\">" === [TagOpen "test" [("baz",""),("\"foo\"","")]] parseTags "<test 'foo bar'>" === [TagOpen "test" [("'foo",""),("bar'","")]] parseTags "<test bar=''' />" === [TagOpen "test" [("bar",""),("'","")], TagClose "test"] parseTags "<test2 a b>" === [TagOpen "test2" [("a",""),("b","")]] parseTags "<test2 ''>" === [TagOpen "test2" [("''","")]] parseTags "</test foo>" === [TagClose "test"] parseTags "<test/>" === [TagOpen "test" [], TagClose "test"] parseTags "<test1 a = b>" === [TagOpen "test1" [("a","b")]] parseTags "hello &amp; world" === [TagText "hello & world"] parseTags "hello &#64; world" === [TagText "hello @ world"] parseTags "hello &#x40; world" === [TagText "hello @ world"] parseTags "hello &haskell; world" === [TagText "hello &haskell; world"] parseTags "hello \n\t world" === [TagText "hello \n\t world"] parseTags "<a href=http://www.google.com>" === [TagOpen "a" [("href","http://www.google.com")]] parseTags "<foo bar=\"bar&#54;baz\">" === [TagOpen "foo" [("bar","bar6baz")]] parseTags "<foo bar=\"bar&amp;baz\">" === [TagOpen "foo" [("bar","bar&baz")]] parseTags "hey &how are you" === [TagText "hey &how are you"] parseTags "hey &how; are you" === [TagText "hey &how; are you"] parseTags "hey &amp are you" === [TagText "hey & are you"] parseTags "hey &amp; are you" === [TagText "hey & are you"] -- real cases reported by users parseTags "test &#10933649; test" === [TagText "test ? test"] parseTags "<a href=\"series.php?view=single&ID=72710\">" === [TagOpen "a" [("href","series.php?view=single&ID=72710")]] parseTags "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">" === [TagOpen "!DOCTYPE" [("HTML",""),("PUBLIC",""),("","-//W3C//DTD HTML 4.01//EN"),("","http://www.w3.org/TR/html4/strict.dtd")]] parseTags "<script src=\"http://edge.jobthread.com/feeds/jobroll/?s_user_id=100540&subtype=slashdot\">" === [TagOpen "script" [("src","http://edge.jobthread.com/feeds/jobroll/?s_user_id=100540&subtype=slashdot")]] parseTags "<a title='foo'bar' href=correct>text" === [TagOpen "a" [("title","foo"),("bar'",""),("href", "correct")],TagText "text"] parseTags "<test><![CDATA[Anything goes, <em>even hidden markup</em> &amp; entities]]> but this is outside</test>" === [TagOpen "test" [],TagText "Anything goes, <em>even hidden markup</em> &amp; entities but this is outside",TagClose "test"] parseTags "<a \r\n href=\"url\">" === [TagOpen "a" [("href","url")]] parseTags "<a href='random.php'><img src='strips/130307.jpg' alt='nukular bish'' title='' /></a>" === [TagOpen "a" [("href","random.php")],TagOpen "img" [("src","strips/130307.jpg"),("alt","nukular bish"),("'",""),("title","")],TagClose "img",TagClose "a"] parseTags "<p>some text</p\n<img alt='&lt; &yyy; &gt;' src=\"abc.gif\">" === [TagOpen "p" [],TagText "some text",TagClose "p"] optionsTests :: Test () optionsTests = check $ \(HTML x) -> all (f x) $ replicateM 3 [False,True] where f str [pos,warn,merge] = bool "merge" (not merge || adjacentTagText tags) && bool "warn" (warn || all (not . isTagWarning) tags) && bool "pos" (if pos then alternatePos tags else all (not . isTagPosition) tags) where tags = parseTagsOptions parseOptions{optTagPosition=pos,optTagWarning=warn,optTagTextMerge=merge} str bool x b = b || error ("optionsTests failed with " ++ x ++ " on " ++ show (pos,warn,merge,str,tags)) -- optTagTextMerge implies no adjacent TagText cells -- and none separated by only warnings or positions adjacentTagText = g True -- can the next be a tag text where g i (x:xs) | isTagText x = i && g False xs | isTagPosition x || isTagWarning x = g i xs | otherwise = g True xs g i [] = True -- optTagPosition implies every element must be followed -- by a position node, no two position nodes must be adjacent -- and all positions must be increasing alternatePos (TagPosition l1 c1 : x : TagPosition l2 c2 : xs) | (l1,c1) <= (l2,c2) && not (isTagPosition x) = alternatePos $ TagPosition l2 c2 : xs alternatePos [TagPosition l1 c1, x] | not $ isTagPosition x = True alternatePos [] = True alternatePos _ = False renderTests :: Test () renderTests = do let rp = renderTags . parseTags rp "<test>" === "<test>" rp "<br></br>" === "<br />" rp "<script></script>" === "<script></script>" rp "hello & world" === "hello &amp; world" rp "<a href=test>" === "<a href=\"test\">" rp "<a href>" === "<a href>" rp "<a href?>" === "<a href?>" rp "<?xml foo?>" === "<?xml foo ?>" rp "<?xml foo?>" === "<?xml foo ?>" rp "<!-- neil -->" === "<!-- neil -->" rp "<a test=\"a&apos;b\">" === "<a test=\"a'b\">" escapeHTML "this is a &\" <test> '" === "this is a &amp;&quot; &lt;test&gt; '" check $ \(HTML x) -> let y = rp x in rp y == (y :: String) entityTests :: Test () entityTests = do lookupNumericEntity "65" === Just 'A' lookupNumericEntity "x41" === Just 'A' lookupNumericEntity "x4E" === Just 'N' lookupNumericEntity "x4e" === Just 'N' lookupNumericEntity "Haskell" === Nothing lookupNumericEntity "" === Nothing lookupNumericEntity "89439085908539082" === Nothing lookupNamedEntity "amp" === Just '&' lookupNamedEntity "haskell" === Nothing escapeXMLChar 'a' === Nothing escapeXMLChar '&' === Just "amp" combiTests :: Test () combiTests = do (TagText "test" ~== TagText "" ) === True (TagText "test" ~== TagText "test") === True (TagText "test" ~== TagText "soup") === False (TagText "test" ~== "test") === True (TagOpen "test" [] ~== "<test>") === True (TagOpen "test" [] ~== "<soup>") === False (TagOpen "test" [] ~/= "<soup>") === True (TagComment "foo" ~== "<!--foo-->") === True (TagComment "bar" ~== "<!--bar-->") === True warnTests :: Test () warnTests = do let p = parseTagsOptions parseOptions{optTagPosition=True,optTagWarning=True} wt x = [(msg,c) | TagWarning msg:TagPosition _ c:_ <- tails $ p x] wt "neil &foo bar" === [("Unknown entity: foo",10)]
silkapp/tagsoup
TagSoup/Test.hs
bsd-3-clause
9,462
0
15
2,040
2,873
1,445
1,428
165
6
-- Copyright (c) 2017, Travis Bemann -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- o Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- -- o 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. -- -- o Neither the name of the copyright holder nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 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. {-# LANGUAGE OverloadedStrings, OverloadedLists #-} module Robots.Genetic.HunterKiller.Intrinsics (specialConsts, specialValueCount, specialConstEntries) where import Robots.Genetic.HunterKiller.Types import Robots.Genetic.HunterKiller.VM import qualified Control.Monad.State.Strict as State import qualified Data.Sequence as Seq import Data.Sequence ((><), (<|), (|>), ViewL(..), ViewR(..)) import Control.Monad (mapM) import Data.Foldable (foldlM, foldrM) import Data.Bits (xor) import qualified Data.Text as Text import Data.Functor (fmap) -- | Constants specialConsts :: Seq.Seq RobotValue specialConsts = fmap (\(RobotConstEntry value _) -> value) specialConstEntries -- | Special value count specialValueCount = Seq.length specialValues -- | Special constants specialConstEntries = specialValues >< intrinsics -- | Special values specialValues :: Seq.Seq RobotConstEntry specialValues = [RobotConstEntry (RobotInt 0) "0", RobotConstEntry (RobotInt 1) "1", RobotConstEntry (RobotBool False) "false", RobotConstEntry (RobotBool True) "true", RobotConstEntry (RobotInt (-1)) "-1", RobotConstEntry (RobotInt 2) "2", RobotConstEntry (RobotInt (-2)) "-2", RobotConstEntry (RobotFloat 0.5) "0.5", RobotConstEntry (RobotFloat (-0.5)) "-0.5", RobotConstEntry RobotNull "null", RobotConstEntry (RobotVector Seq.empty) "empty", RobotConstEntry (RobotFloat pi) "pi", RobotConstEntry (RobotFloat (exp 1)) "e", RobotConstEntry (RobotFloat (pi * 2.0)) "pi2"] -- | Intrinsics intrinsics :: Seq.Seq RobotConstEntry intrinsics = [RobotConstEntry (RobotIntrinsic intrinsicEquals) "equals", RobotConstEntry (RobotIntrinsic intrinsicNotEquals) "notEquals", RobotConstEntry (RobotIntrinsic intrinsicGet) "get", RobotConstEntry (RobotIntrinsic intrinsicSet) "set", RobotConstEntry (RobotIntrinsic intrinsicLength) "length", RobotConstEntry (RobotIntrinsic intrinsicCons) "cons", RobotConstEntry (RobotIntrinsic intrinsicSnoc) "snoc", RobotConstEntry (RobotIntrinsic intrinsicLHead) "lHead", RobotConstEntry (RobotIntrinsic intrinsicLTail) "lTail", RobotConstEntry (RobotIntrinsic intrinsicRHead) "rHead", RobotConstEntry (RobotIntrinsic intrinsicRTail) "rTail", RobotConstEntry (RobotIntrinsic intrinsicMap) "map", RobotConstEntry (RobotIntrinsic intrinsicFoldl) "foldl", RobotConstEntry (RobotIntrinsic intrinsicFoldr) "foldr", RobotConstEntry (RobotIntrinsic intrinsicNot) "not", RobotConstEntry (RobotIntrinsic intrinsicAnd) "and", RobotConstEntry (RobotIntrinsic intrinsicOr) "or", RobotConstEntry (RobotIntrinsic intrinsicXor) "xor", RobotConstEntry (RobotIntrinsic intrinsicGT) "gt", RobotConstEntry (RobotIntrinsic intrinsicLT) "lt", RobotConstEntry (RobotIntrinsic intrinsicGTE) "gte", RobotConstEntry (RobotIntrinsic intrinsicLTE) "lte", RobotConstEntry (RobotIntrinsic intrinsicFire) "fire", RobotConstEntry (RobotIntrinsic intrinsicThrust) "thrust", RobotConstEntry (RobotIntrinsic intrinsicTurn) "turn", RobotConstEntry (RobotIntrinsic intrinsicAdd) "add", RobotConstEntry (RobotIntrinsic intrinsicSub) "sub", RobotConstEntry (RobotIntrinsic intrinsicMul) "mul", RobotConstEntry (RobotIntrinsic intrinsicDiv) "div", RobotConstEntry (RobotIntrinsic intrinsicMod) "mod", RobotConstEntry (RobotIntrinsic intrinsicPow) "pow", RobotConstEntry (RobotIntrinsic intrinsicSqrt) "sqrt", RobotConstEntry (RobotIntrinsic intrinsicAbs) "abs", RobotConstEntry (RobotIntrinsic intrinsicExp) "exp", RobotConstEntry (RobotIntrinsic intrinsicLog) "log", RobotConstEntry (RobotIntrinsic intrinsicSin) "sin", RobotConstEntry (RobotIntrinsic intrinsicCos) "cos", RobotConstEntry (RobotIntrinsic intrinsicTan) "tan", RobotConstEntry (RobotIntrinsic intrinsicAsin) "asin", RobotConstEntry (RobotIntrinsic intrinsicAcos) "acos", RobotConstEntry (RobotIntrinsic intrinsicAtan) "atan", RobotConstEntry (RobotIntrinsic intrinsicSinh) "sinh", RobotConstEntry (RobotIntrinsic intrinsicCosh) "cosh", RobotConstEntry (RobotIntrinsic intrinsicTanh) "tanh", RobotConstEntry (RobotIntrinsic intrinsicAsinh) "asinh", RobotConstEntry (RobotIntrinsic intrinsicAcosh) "acosh", RobotConstEntry (RobotIntrinsic intrinsicAtanh) "atanh"] -- | The equals intrinsic intrinsicEquals :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicEquals args = do updateStateFinish case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just x, Just y) -> return . RobotBool $ valueEqual x y _ -> return . RobotBool $ False -- | The not equals intrinsic intrinsicNotEquals :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicNotEquals args = do updateStateFinish case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just x, Just y) -> return . RobotBool $ valueNotEqual x y _ -> return . RobotBool $ True -- | Get whether two values are equal valueEqual :: RobotValue -> RobotValue -> Bool valueEqual RobotNull RobotNull = True valueEqual (RobotBool x) (RobotBool y) = x == y valueEqual (RobotInt x) (RobotInt y) = x == y valueEqual (RobotFloat x) (RobotFloat y) = x == y valueEqual (RobotInt x) (RobotFloat y) = fromIntegral x == y valueEqual (RobotFloat x) (RobotInt y) = x == fromIntegral y valueEqual (RobotVector x) (RobotVector y) = if Seq.length x == Seq.length y then case Seq.elemIndexL False (fmap (\(x, y) -> valueEqual x y) (Seq.zip x y)) of Just _ -> False Nothing -> True else False valueEqual _ _ = False -- | Get whether two values are not equal valueNotEqual :: RobotValue -> RobotValue -> Bool valueNotEqual RobotNull RobotNull = False valueNotEqual (RobotBool x) (RobotBool y) = x /= y valueNotEqual (RobotInt x) (RobotInt y) = x /= y valueNotEqual (RobotFloat x) (RobotFloat y) = x /= y valueNotEqual (RobotInt x) (RobotFloat y) = fromIntegral x /= y valueNotEqual (RobotFloat x) (RobotInt y) = x /= fromIntegral y valueNotEqual (RobotVector x) (RobotVector y) = if Seq.length x == Seq.length y then case Seq.elemIndexL True (fmap (\(x, y) -> valueNotEqual x y) (Seq.zip x y)) of Just _ -> True Nothing -> False else True valueNotEqual _ _ = True -- | The vector get intrinsic intrinsicGet :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicGet args = do updateStateFinish case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just index, Just (RobotVector vector)) -> case Seq.lookup (castToInt index) vector of Just value -> return value Nothing -> return RobotNull _ -> return RobotNull -- | The vector set intrinsic intrinsicSet :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicSet args = do updateStateFinish case (Seq.lookup 0 args, Seq.lookup 1 args, Seq.lookup 2 args) of (Just index, Just value, Just (RobotVector vector)) -> let index' = castToInt index in let vector' = if index' < Seq.length vector then vector else vector >< (Seq.replicate ((index' + 1) - (Seq.length vector)) RobotNull) in return . RobotVector $ Seq.update index' value vector' _ -> return RobotNull -- | The vector cons intrinsic intrinsicCons :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicCons args = do updateStateFinish case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just value, Just (RobotVector vector)) -> return . RobotVector $ value <| vector (Just value0, Just value1) -> return $ RobotVector [value0, value1] (Just value, Nothing) -> return . RobotVector $ Seq.singleton value _ -> return . RobotVector $ Seq.empty -- | The vector snoc intrinsic intrinsicSnoc :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicSnoc args = do updateStateFinish case (Seq.lookup 0 args, Seq.lookup 2 args) of (Just (RobotVector vector), Just value) -> return . RobotVector $ vector |> value (Just value0, Just value1) -> return $ RobotVector [value0, value1] (Just (RobotVector vector), Nothing) -> return . RobotVector $ vector (Just value, Nothing) -> return . RobotVector . Seq.singleton $ value _ -> return . RobotVector $ Seq.empty -- | The vector length intrinsic intrinsicLength :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicLength args = do updateStateFinish case Seq.lookup 0 args of Just (RobotVector value) -> return . RobotInt . fromIntegral $ Seq.length value _ -> return . RobotInt $ 0 -- | The vector left head intrinsic intrinsicLHead :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicLHead args = do updateStateFinish case Seq.lookup 0 args of Just (RobotVector value) -> case Seq.viewl value of headValue :< _ -> return headValue _ -> return RobotNull _ -> return RobotNull -- | The vector left tail intrinsic intrinsicLTail :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicLTail args = do updateStateFinish case Seq.lookup 0 args of Just (RobotVector value) -> case Seq.viewl value of _ :< vector -> return . RobotVector $ vector _ -> return . RobotVector $ Seq.empty _ -> return . RobotVector $ Seq.empty -- | The vector right head intrinsic intrinsicRHead :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicRHead args = do updateStateFinish case Seq.lookup 0 args of Just (RobotVector value) -> case Seq.viewr value of _ :> headValue -> return headValue _ -> return RobotNull _ -> return RobotNull -- | The vector right tail intrinsic intrinsicRTail :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicRTail args = do updateStateFinish case Seq.lookup 0 args of Just (RobotVector value) -> case Seq.viewr value of vector :> _ -> return . RobotVector $ vector _ -> return . RobotVector $ Seq.empty _ -> return . RobotVector $ Seq.empty -- | The vector map intrinsic intrinsicMap :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicMap args = do case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just func, Just (RobotVector vector)) -> do vector' <- mapM (\value -> apply (Seq.singleton value) func) vector updateStateFinish return . RobotVector $ vector' _ -> do updateStateFinish return . RobotVector $ Seq.empty -- | The vector foldl intrinsic intrinsicFoldl :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicFoldl args = case (Seq.lookup 0 args, Seq.lookup 1 args, Seq.lookup 2 args) of (Just func, Just start, Just (RobotVector vector)) -> do value <- foldlM (\current value -> apply [current, value] func) start vector updateStateFinish return value _ -> do updateStateFinish return RobotNull -- | The vector foldr intrinsic intrinsicFoldr :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicFoldr args = case (Seq.lookup 0 args, Seq.lookup 1 args, Seq.lookup 2 args) of (Just func, Just start, Just (RobotVector vector)) -> do value <- foldrM (\value current -> apply [value, current] func) start vector updateStateFinish return value _ -> do updateStateFinish return RobotNull -- | The not intrinsic intrinsicNot :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicNot args = do updateStateFinish return . RobotBool $ case Seq.lookup 0 args of Just value -> not . castToBool $ value _ -> False -- | The and intrinsic intrinsicAnd :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicAnd args = do updateStateFinish return . RobotBool $ case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just value0, Just value1) -> castToBool value0 && castToBool value1 _ -> False -- | The or intrinsic intrinsicOr :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicOr args = do updateStateFinish return . RobotBool $ case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just value0, Just value1) -> castToBool value0 || castToBool value1 _ -> True -- | The xor intrinsic intrinsicXor :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicXor args = do updateStateFinish return . RobotBool $ case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just value0, Just value1) -> castToBool value0 `xor` castToBool value1 _ -> True -- | The greater than intrinsic intrinsicGT :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicGT args = do updateStateFinish return . RobotBool $ case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just (RobotFloat value0), Just value1) -> value0 > castToDouble value1 (Just value0, Just (RobotFloat value1)) -> castToDouble value0 > value1 (Just value0, Just value1) -> castToInteger value0 > castToInteger value1 _ -> False -- | The less than intrinsic intrinsicLT :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicLT args = do updateStateFinish return . RobotBool $ case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just (RobotFloat value0), Just value1) -> value0 < castToDouble value1 (Just value0, Just (RobotFloat value1)) -> castToDouble value0 < value1 (Just value0, Just value1) -> castToInteger value0 < castToInteger value1 _ -> False -- | The greater than or equal to intrinsic intrinsicGTE :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicGTE args = do updateStateFinish return . RobotBool $ case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just (RobotFloat value0), Just value1) -> value0 >= castToDouble value1 (Just value0, Just (RobotFloat value1)) -> castToDouble value0 >= value1 (Just value0, Just value1) -> castToInteger value0 >= castToInteger value1 _ -> False -- | The less than or equal to intrinsic intrinsicLTE :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicLTE args = do updateStateFinish return . RobotBool $ case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just (RobotFloat value0), Just value1) -> value0 <= castToDouble value1 (Just value0, Just (RobotFloat value1)) -> castToDouble value0 <= value1 (Just value0, Just value1) -> castToInteger value0 <= castToInteger value1 _ -> False -- | The fire intrinsic intrinsicFire :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicFire args = do updateStateFinish return $ case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just value, Just power) -> case value of RobotOutput value action -> RobotOutput value (action { robotActionFirePower = robotActionFirePower action + castToDouble power }) value -> RobotOutput value (RobotAction { robotActionFirePower = castToDouble power, robotActionThrustPower = 0.0, robotActionTurnPower = 0.0 }) (Just value, Nothing) -> value _ -> RobotNull -- | The thrust intrinsic intrinsicThrust :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicThrust args = do updateStateFinish return $ case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just value, Just power) -> case value of RobotOutput value action -> RobotOutput value (action { robotActionThrustPower = robotActionThrustPower action + castToDouble power }) value -> RobotOutput value (RobotAction { robotActionFirePower = 0.0, robotActionThrustPower = castToDouble power, robotActionTurnPower = 0.0 }) (Just value, Nothing) -> value _ -> RobotNull -- | The turn intrinsic intrinsicTurn :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicTurn args = do updateStateFinish return $ case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just value, Just power) -> case value of RobotOutput value action -> RobotOutput value (action { robotActionTurnPower = robotActionTurnPower action + castToDouble power }) value -> RobotOutput value (RobotAction { robotActionFirePower = 0.0, robotActionThrustPower = 0.0, robotActionTurnPower = castToDouble power }) (Just value, Nothing) -> value _ -> RobotNull -- | The add intrinsic intrinsicAdd :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicAdd args = do updateStateFinish case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just (RobotFloat value0), Just value1) -> return . RobotFloat $ value0 + castToDouble value1 (Just value0, Just (RobotFloat value1)) -> return . RobotFloat $ castToDouble value0 + value1 (Just value0, Just value1) -> return . RobotInt $ castToInteger value0 + castToInteger value1 _ -> return . RobotInt $ 0 -- | The subtract intrinsic intrinsicSub :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicSub args = do updateStateFinish case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just (RobotFloat value0), Just value1) -> return . RobotFloat $ value0 - castToDouble value1 (Just value0, Just (RobotFloat value1)) -> return . RobotFloat $ castToDouble value0 - value1 (Just value0, Just value1) -> return . RobotInt $ castToInteger value0 - castToInteger value1 _ -> return . RobotInt $ 0 -- | The multiply intrinsic intrinsicMul :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicMul args = do updateStateFinish case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just (RobotFloat value0), Just value1) -> return . RobotFloat $ value0 * castToDouble value1 (Just value0, Just (RobotFloat value1)) -> return . RobotFloat $ castToDouble value0 * value1 (Just value0, Just value1) -> return . RobotInt $ castToInteger value0 * castToInteger value1 _ -> return . RobotInt $ 1 -- | The divide intrinsic intrinsicDiv :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicDiv args = do updateStateFinish case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just (RobotFloat value0), Just value1) -> if castToDouble value1 /= 0.0 then return . RobotFloat $ value0 / castToDouble value1 else return RobotNull (Just value0, Just (RobotFloat value1)) -> if value1 /= 0.0 then return . RobotFloat $ castToDouble value0 / value1 else return RobotNull (Just value0, Just value1) -> let value0' = castToInteger value0 value1' = castToInteger value1 in if value1' /= 0 then if (value0' `mod` value1') == 0 then return . RobotInt $ value0' `div` value1' else return . RobotFloat $ castToDouble value0 / castToDouble value1 else return RobotNull _ -> return . RobotInt $ 1 -- | The modulus intrinsic intrinsicMod :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicMod args = do updateStateFinish case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just (RobotFloat value0), Just value1) -> let value1' = castToDouble value1 in if value1' /= 0.0 then let quotient = value0 / value1' in return . RobotFloat $ value0 - ((fromIntegral $ floor quotient) * value1') else return RobotNull (Just value0, Just (RobotFloat value1)) -> if value1 /= 0.0 then let value0' = castToDouble value0 in let quotient = value0' / value1 in return . RobotFloat $ value0' - ((fromIntegral $ floor quotient) * value1) else return RobotNull (Just value0, Just value1) -> if castToInteger value1 /= 0 then return . RobotInt $ castToInteger value0 `mod` castToInteger value1 else return RobotNull _ -> return . RobotInt $ 0 -- | The power intrinsic intrinsicPow :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicPow args = do updateStateFinish case (Seq.lookup 0 args, Seq.lookup 1 args) of (Just value0, Just (RobotFloat value1)) -> return . RobotFloat $ castToDouble value0 ** value1 (Just (RobotFloat value0), Just value1) -> return . RobotFloat $ value0 ** castToDouble value1 (Just (RobotInt value0), Just (RobotInt value1)) -> if value1 >= 0 then return . RobotInt $ value0 ^ value1 else return . RobotFloat $ fromIntegral value0 ** fromIntegral value1 (Just value0, Just value1) -> let value0' = castToInteger value0 value1' = castToInteger value1 in if value1' >= 0 then return . RobotInt $ value0' ^ value1' else return . RobotFloat $ fromIntegral value0' ** fromIntegral value1' _ -> return . RobotInt $ 1 -- | The sqrt intrinsic intrinsicSqrt :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicSqrt args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . sqrt . castToDouble $ value _ -> return . RobotFloat $ 0.0 -- | The abs intrinsic intrinsicAbs :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicAbs args = do updateStateFinish case Seq.lookup 0 args of Just (RobotFloat value) -> return . RobotFloat . abs $ value Just value -> return . RobotInt . abs . castToInteger $ value _ -> return . RobotInt $ 0 -- | The exp intrinsic intrinsicExp :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicExp args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . exp . castToDouble $ value _ -> return . RobotFloat $ 1.0 -- | Infinity inf :: Double inf = 1.0 / 0.0 -- | The log intrinsic intrinsicLog :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicLog args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . log . castToDouble $ value _ -> return . RobotFloat $ -inf -- | The sin intrinsic intrinsicSin :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicSin args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . sin . castToDouble $ value _ -> return . RobotFloat . sin $ 0.0 -- | The cos intrinsic intrinsicCos :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicCos args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . cos . castToDouble $ value _ -> return . RobotFloat . cos $ 0.0 -- | The tan intrinsic intrinsicTan :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicTan args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . tan . castToDouble $ value _ -> return . RobotFloat . tan $ 0.0 -- | The asin intrinsic intrinsicAsin :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicAsin args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . asin . castToDouble $ value _ -> return . RobotFloat . asin $ 0.0 -- | The acos intrinsic intrinsicAcos :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicAcos args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . acos . castToDouble $ value _ -> return . RobotFloat . acos $ 0.0 -- | The atan intrinsic intrinsicAtan :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicAtan args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . atan . castToDouble $ value _ -> return . RobotFloat . atan $ 0.0 -- | The sinh intrinsic intrinsicSinh :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicSinh args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . sinh . castToDouble $ value _ -> return . RobotFloat . sinh $ 0.0 -- | The cosh intrinsic intrinsicCosh :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicCosh args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . cosh . castToDouble $ value _ -> return . RobotFloat . cosh $ 0.0 -- | The tanh intrinsic intrinsicTanh :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicTanh args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . tanh . castToDouble $ value _ -> return . RobotFloat . tanh $ 0.0 -- | The asinh intrinsic intrinsicAsinh :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicAsinh args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . asinh . castToDouble $ value _ -> return . RobotFloat . asinh $ 0.0 -- | The acosh intrinsic intrinsicAcosh :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicAcosh args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . acosh . castToDouble $ value _ -> return . RobotFloat . acosh $ 0.0 -- | The atanh intrinsic intrinsicAtanh :: Seq.Seq RobotValue -> State.State RobotState RobotValue intrinsicAtanh args = do updateStateFinish case Seq.lookup 0 args of Just value -> return . RobotFloat . atanh . castToDouble $ value _ -> return . RobotFloat . atanh $ 0.0
tabemann/botwars
src/Robots/Genetic/HunterKiller/Intrinsics.hs
bsd-3-clause
28,153
0
24
6,806
8,141
4,028
4,113
562
8
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Data.Conduit.Network.Stream.Internal where import Control.Applicative import Control.Concurrent.MVar import Control.Monad.Reader --import Control.Monad.Trans import Control.Monad.Trans.Resource import Data.Conduit import Data.Conduit.Network import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import qualified Data.Conduit.Binary as CB import Data.Conduit.Network.Stream.Exceptions import Data.Conduit.Network.Stream.Header data StreamSource m = NewSource (AppData m) | OpenSource (ResumableSource m ByteString) | ClosedSource data StreamData m = StreamData { streamDataSource :: MVar (StreamSource m) , streamDataSink :: Sink ByteString m () } -- | 'BL.ByteString' stream newtype StreamT m a = StreamT { stream_base :: ReaderT (StreamData m) m a } deriving (Monad, MonadIO, Functor, Applicative) instance MonadTrans StreamT where lift f = StreamT $ lift f instance (MonadThrow m) => MonadThrow (StreamT m) where monadThrow e = lift $ monadThrow e instance (MonadResource m, MonadIO m) => MonadResource (StreamT m) where liftResourceT t = lift $ liftResourceT t -------------------------------------------------------------------------------- -- Stream encoding encodeBS :: Monad m => Conduit ByteString m ByteString encodeBS = awaitForever $ \bs -> do yield $ BS.pack (varint $ BS.length bs) mapM_ yield $ blocks bs where blocks bs | BS.null bs = [] | otherwise = let (f,r) = BS.splitAt 4096 bs in f : blocks r encodeLazyBS :: Monad m => Conduit (Int, BL.ByteString) m ByteString encodeLazyBS = awaitForever $ \(l,bs) -> do yield $ BS.pack (varint l) mapM_ yield $ BL.toChunks bs -------------------------------------------------------------------------------- -- Stream decoding -- | Get the next package from the stream (whether it's a single 'BL.ByteString' or -- a list) decodeCondBlock :: MonadResource m => Conduit ByteString m BL.ByteString decodeCondBlock = do h <- decodeHeader case h of VarInt l -> single l ConduitSTART -> list EndOfInput -> return () _ -> monadThrow $ UnexpectedHeader h where single l = CB.take l >>= yield list = do h <- decodeHeader case h of VarInt l -> single l >> list ConduitEND -> return () _ -> monadThrow $ UnexpectedHeader h
mcmaniac/conduit-network-stream
src/Data/Conduit/Network/Stream/Internal.hs
bsd-3-clause
2,483
0
14
514
703
372
331
56
6
{-| Description : Abstract syntax tree. Representation of Uroboro programs as abstract syntax tree with type annotations. This is the "internal" program representation produced by the type checker. -} module Uroboro.Tree.Internal ( -- * Common parts -- $common Identifier , Type (Type) -- * Typed syntax tree , Exp (VarExp, AppExp, ConExp, DesExp) , Pat (VarPat, ConPat) , Cop (AppCop, DesCop) , Rule , Rules ) where import Uroboro.Tree.Common -- $common -- Reexported from "Uroboro.Tree.Common". -- |Expression with type annotations. data Exp -- |Variable. = VarExp Type Identifier -- |Function application. | AppExp Type Identifier [Exp] -- |Constructor application. | ConExp Type Identifier [Exp] -- |Destructor application. | DesExp Type Identifier [Exp] Exp deriving (Show, Eq) -- |Pattern with type annotations. data Pat = VarPat Type Identifier | ConPat Type Identifier [Pat] deriving (Show, Eq) -- |Copattern with type annotations. data Cop = AppCop Type Identifier [Pat] | DesCop Type Identifier [Pat] Cop deriving (Show, Eq) -- |One rule of a function definition. type Rule = (Cop, Exp) -- |A complete program. type Rules = [(Identifier, [Rule])]
tewe/uroboro
src/Uroboro/Tree/Internal.hs
mit
1,299
0
7
319
242
157
85
29
0
{-# LANGUAGE DeriveDataTypeable #-} module InnerEar.Exercises.BoostOrCut (boostOrCutExercise) where import Reflex import Reflex.Dom import Data.Map import Text.JSON import Text.JSON.Generic import Sound.MusicW import InnerEar.Exercises.MultipleChoice import InnerEar.Types.ExerciseId import InnerEar.Types.Exercise import InnerEar.Types.Score import InnerEar.Types.MultipleChoiceStore import InnerEar.Widgets.Config import InnerEar.Widgets.SpecEval import InnerEar.Widgets.AnswerButton import InnerEar.Types.Data hiding (Time) import InnerEar.Types.Sound type Config = Double -- representing amount of gain that is applied (or not) configs :: [Config] configs = [10,6,3,2,1,0.5,0.25,-0.25,-0.5,-1,-2,-3,-6,-10] configMap:: Map Int (String,Config) configMap = fromList $ zip [0::Int,1..] $ fmap (\x -> (show x ++" dB", x)) configs data Answer = Answer Bool deriving (Eq,Ord,Data,Typeable) instance Show Answer where show (Answer True) = "Boosted/Cut" show (Answer False) = "No Change" instance Buttonable Answer where makeButton = showAnswerButton answers = [Answer False,Answer True] instructions :: MonadWidget t m => m () instructions = el "div" $ do elClass "div" "instructionsText" $ text "In this exercise you are either played a sound at an original/reference level, or a version of the sound that has been increased (boosted) or decreased (cut/attenuated) in level by a certain amount of dB of gain (positive dB for boost, negative dB for cut). When the amount of boost or cut is great, it is easier to tell the difference between the boosted/cut and reference/unchanged sound. The object of the exercise is to see how small you can make the difference while still being able to tell the two conditions apart." elClass "div" "instructionsText" $ text "Hint: before or after pressing Listen to hear the question, press 'Listen to Reference Sound' to hear the sound to which you are comparing the question sound." renderAnswer :: Map String AudioBuffer -> Config -> (SourceNodeSpec,Maybe Time) -> Maybe Answer -> Synth () renderAnswer _ db (src, dur) (Just (Answer True)) = buildSynth $ do let env = maybe (return EmptyGraph) (unitRectEnv (Millis 1)) dur synthSource src >> gain (Db $ -10 + db) >> env >> destination maybeDelete (fmap (+Sec 0.2) dur) renderAnswer _ _ (src, dur) _ = buildSynth $ do let env = maybe (return EmptyGraph) (unitRectEnv (Millis 1)) dur synthSource src >> gain (Db $ -10) >> env >> destination maybeDelete (fmap (+Sec 0.2) dur) displayEval :: MonadWidget t m => Dynamic t (Map Answer Score) -> Dynamic t (MultipleChoiceStore Config Answer) -> m () displayEval e _ = displayMultipleChoiceEvaluationGraph ("scoreBarWrapper","svgBarContainer","svgFaintedLine", "xLabel") "Session Performance" "" answers e generateQ :: Config -> [ExerciseDatum] -> IO ([Answer],Answer) generateQ _ _ = randomMultipleChoiceQuestion answers sourcesMap:: Map Int (String,SoundSourceConfigOption) sourcesMap = fromList $ [ (0, ("300hz sine wave", Spec (Oscillator Sine (Hz 300)) (Just $ Sec 2))), (1, ("Load a sound file", UserProvidedResource)) ] boostOrCutExercise :: MonadWidget t m => Exercise t m Config [Answer] Answer (Map Answer Score) (MultipleChoiceStore Config Answer) boostOrCutExercise = multipleChoiceExercise 1 answers instructions (configWidget "boostOrCutExercise" sourcesMap 0 "Boost/Cut amount: " configMap) -- (dynRadioConfigWidget "fiveBandBoostCutExercise" sourcesMap 0 configMap) renderAnswer -- c -> b->a->Sound BoostOrCut 10 displayEval generateQ (const (0,2))
JamieBeverley/InnerEar
src/InnerEar/Exercises/BoostOrCut.hs
gpl-3.0
3,566
0
15
547
996
533
463
63
1
-- | Text.Tabular.AsciiArt from tabular-0.2.2.7, modified to treat -- wide characters as double width. module Text.Tabular.AsciiWide where import Data.List (intersperse, transpose) import Text.Tabular import Hledger.Utils.String -- | for simplicity, we assume that each cell is rendered -- on a single line render :: Bool -- ^ pretty tables -> (rh -> String) -> (ch -> String) -> (a -> String) -> Table rh ch a -> String render pretty fr fc f (Table rh ch cells) = unlines $ [ bar SingleLine -- +--------------------------------------+ , renderColumns pretty sizes ch2 , bar DoubleLine -- +======================================+ ] ++ (renderRs $ fmap renderR $ zipHeader [] cells $ fmap fr rh) ++ [ bar SingleLine ] -- +--------------------------------------+ where bar = concat . renderHLine pretty sizes ch2 -- ch2 and cell2 include the row and column labels ch2 = Group DoubleLine [Header "", fmap fc ch] cells2 = headerContents ch2 : zipWith (\h cs -> h : map f cs) rhStrings cells -- renderR (cs,h) = renderColumns pretty sizes $ Group DoubleLine [ Header h , fmap fst $ zipHeader "" (map f cs) ch] rhStrings = map fr $ headerContents rh -- maximum width for each column sizes = map (maximum . map strWidth) . transpose $ cells2 renderRs (Header s) = [s] renderRs (Group p hs) = concat . intersperse sep . map renderRs $ hs where sep = renderHLine pretty sizes ch2 p verticalBar :: Bool -> Char verticalBar pretty = if pretty then '│' else '|' leftBar :: Bool -> String leftBar pretty = verticalBar pretty : " " rightBar :: Bool -> String rightBar pretty = " " ++ [verticalBar pretty] midBar :: Bool -> String midBar pretty = " " ++ verticalBar pretty : " " doubleMidBar :: Bool -> String doubleMidBar pretty = if pretty then " ║ " else " || " horizontalBar :: Bool -> Char horizontalBar pretty = if pretty then '─' else '-' doubleHorizontalBar :: Bool -> Char doubleHorizontalBar pretty = if pretty then '═' else '=' -- | We stop rendering on the shortest list! renderColumns :: Bool -- ^ pretty -> [Int] -- ^ max width for each column -> Header String -> String renderColumns pretty is h = leftBar pretty ++ coreLine ++ rightBar pretty where coreLine = concatMap helper $ flattenHeader $ zipHeader 0 is h helper = either hsep (uncurry padLeftWide) hsep :: Properties -> String hsep NoLine = " " hsep SingleLine = midBar pretty hsep DoubleLine = doubleMidBar pretty renderHLine :: Bool -- ^ pretty -> [Int] -- ^ width specifications -> Header String -> Properties -> [String] renderHLine _ _ _ NoLine = [] renderHLine pretty w h SingleLine = [renderHLine' pretty SingleLine w (horizontalBar pretty) h] renderHLine pretty w h DoubleLine = [renderHLine' pretty DoubleLine w (doubleHorizontalBar pretty) h] doubleCross :: Bool -> String doubleCross pretty = if pretty then "╬" else "++" doubleVerticalCross :: Bool -> String doubleVerticalCross pretty = if pretty then "╫" else "++" cross :: Bool -> Char cross pretty = if pretty then '┼' else '+' renderHLine' :: Bool -> Properties -> [Int] -> Char -> Header String -> String renderHLine' pretty prop is sep h = [ cross pretty, sep ] ++ coreLine ++ [sep, cross pretty] where coreLine = concatMap helper $ flattenHeader $ zipHeader 0 is h helper = either vsep dashes dashes (i,_) = replicate i sep vsep NoLine = replicate 2 sep -- match the double space sep in renderColumns vsep SingleLine = sep : cross pretty : [sep] vsep DoubleLine = sep : cross' ++ [sep] cross' = case prop of DoubleLine -> doubleCross pretty _ -> doubleVerticalCross pretty -- padLeft :: Int -> String -> String -- padLeft l s = padding ++ s -- where padding = replicate (l - length s) ' '
mstksg/hledger
hledger/Text/Tabular/AsciiWide.hs
gpl-3.0
3,991
0
13
994
1,152
601
551
79
4
{-# 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.EC2.DescribeVolumes -- 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) -- -- Describes the specified EBS volumes. -- -- If you are describing a long list of volumes, you can paginate the -- output to make the list more manageable. The 'MaxResults' parameter sets -- the maximum number of results returned in a single page. If the list of -- results exceeds your 'MaxResults' value, then that number of results is -- returned along with a 'NextToken' value that can be passed to a -- subsequent 'DescribeVolumes' request to retrieve the remaining results. -- -- For more information about EBS volumes, see -- <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumes.html Amazon EBS Volumes> -- in the /Amazon Elastic Compute Cloud User Guide/. -- -- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumes.html AWS API Reference> for DescribeVolumes. module Network.AWS.EC2.DescribeVolumes ( -- * Creating a Request describeVolumes , DescribeVolumes -- * Request Lenses , desFilters , desVolumeIds , desNextToken , desDryRun , desMaxResults -- * Destructuring the Response , describeVolumesResponse , DescribeVolumesResponse -- * Response Lenses , dvvrsNextToken , dvvrsVolumes , dvvrsResponseStatus ) where import Network.AWS.EC2.Types import Network.AWS.EC2.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'describeVolumes' smart constructor. data DescribeVolumes = DescribeVolumes' { _desFilters :: !(Maybe [Filter]) , _desVolumeIds :: !(Maybe [Text]) , _desNextToken :: !(Maybe Text) , _desDryRun :: !(Maybe Bool) , _desMaxResults :: !(Maybe Int) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeVolumes' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'desFilters' -- -- * 'desVolumeIds' -- -- * 'desNextToken' -- -- * 'desDryRun' -- -- * 'desMaxResults' describeVolumes :: DescribeVolumes describeVolumes = DescribeVolumes' { _desFilters = Nothing , _desVolumeIds = Nothing , _desNextToken = Nothing , _desDryRun = Nothing , _desMaxResults = Nothing } -- | One or more filters. -- -- - 'attachment.attach-time' - The time stamp when the attachment -- initiated. -- -- - 'attachment.delete-on-termination' - Whether the volume is deleted -- on instance termination. -- -- - 'attachment.device' - The device name that is exposed to the -- instance (for example, '\/dev\/sda1'). -- -- - 'attachment.instance-id' - The ID of the instance the volume is -- attached to. -- -- - 'attachment.status' - The attachment state ('attaching' | 'attached' -- | 'detaching' | 'detached'). -- -- - 'availability-zone' - The Availability Zone in which the volume was -- created. -- -- - 'create-time' - The time stamp when the volume was created. -- -- - 'encrypted' - The encryption status of the volume. -- -- - 'size' - The size of the volume, in GiB. -- -- - 'snapshot-id' - The snapshot from which the volume was created. -- -- - 'status' - The status of the volume ('creating' | 'available' | -- 'in-use' | 'deleting' | 'deleted' | 'error'). -- -- - 'tag':/key/=/value/ - The key\/value combination of a tag assigned -- to the resource. -- -- - 'tag-key' - The key of a tag assigned to the resource. This filter -- is independent of the 'tag-value' filter. For example, if you use -- both the filter \"tag-key=Purpose\" and the filter \"tag-value=X\", -- you get any resources assigned both the tag key Purpose (regardless -- of what the tag\'s value is), and the tag value X (regardless of -- what the tag\'s key is). If you want to list only resources where -- Purpose is X, see the 'tag':/key/=/value/ filter. -- -- - 'tag-value' - The value of a tag assigned to the resource. This -- filter is independent of the 'tag-key' filter. -- -- - 'volume-id' - The volume ID. -- -- - 'volume-type' - The Amazon EBS volume type. This can be 'gp2' for -- General Purpose (SSD) volumes, 'io1' for Provisioned IOPS (SSD) -- volumes, or 'standard' for Magnetic volumes. -- desFilters :: Lens' DescribeVolumes [Filter] desFilters = lens _desFilters (\ s a -> s{_desFilters = a}) . _Default . _Coerce; -- | One or more volume IDs. desVolumeIds :: Lens' DescribeVolumes [Text] desVolumeIds = lens _desVolumeIds (\ s a -> s{_desVolumeIds = a}) . _Default . _Coerce; -- | The 'NextToken' value returned from a previous paginated -- 'DescribeVolumes' request where 'MaxResults' was used and the results -- exceeded the value of that parameter. Pagination continues from the end -- of the previous results that returned the 'NextToken' value. This value -- is 'null' when there are no more results to return. desNextToken :: Lens' DescribeVolumes (Maybe Text) desNextToken = lens _desNextToken (\ s a -> s{_desNextToken = a}); -- | Checks whether you have the required permissions for the action, without -- actually making the request, and provides an error response. If you have -- the required permissions, the error response is 'DryRunOperation'. -- Otherwise, it is 'UnauthorizedOperation'. desDryRun :: Lens' DescribeVolumes (Maybe Bool) desDryRun = lens _desDryRun (\ s a -> s{_desDryRun = a}); -- | The maximum number of volume results returned by 'DescribeVolumes' in -- paginated output. When this parameter is used, 'DescribeVolumes' only -- returns 'MaxResults' results in a single page along with a 'NextToken' -- response element. The remaining results of the initial request can be -- seen by sending another 'DescribeVolumes' request with the returned -- 'NextToken' value. This value can be between 5 and 1000; if 'MaxResults' -- is given a value larger than 1000, only 1000 results are returned. If -- this parameter is not used, then 'DescribeVolumes' returns all results. -- You cannot specify this parameter and the volume IDs parameter in the -- same request. desMaxResults :: Lens' DescribeVolumes (Maybe Int) desMaxResults = lens _desMaxResults (\ s a -> s{_desMaxResults = a}); instance AWSRequest DescribeVolumes where type Rs DescribeVolumes = DescribeVolumesResponse request = postQuery eC2 response = receiveXML (\ s h x -> DescribeVolumesResponse' <$> (x .@? "nextToken") <*> (x .@? "volumeSet" .!@ mempty >>= may (parseXMLList "item")) <*> (pure (fromEnum s))) instance ToHeaders DescribeVolumes where toHeaders = const mempty instance ToPath DescribeVolumes where toPath = const "/" instance ToQuery DescribeVolumes where toQuery DescribeVolumes'{..} = mconcat ["Action" =: ("DescribeVolumes" :: ByteString), "Version" =: ("2015-04-15" :: ByteString), toQuery (toQueryList "Filter" <$> _desFilters), toQuery (toQueryList "VolumeId" <$> _desVolumeIds), "NextToken" =: _desNextToken, "DryRun" =: _desDryRun, "MaxResults" =: _desMaxResults] -- | /See:/ 'describeVolumesResponse' smart constructor. data DescribeVolumesResponse = DescribeVolumesResponse' { _dvvrsNextToken :: !(Maybe Text) , _dvvrsVolumes :: !(Maybe [Volume]) , _dvvrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeVolumesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dvvrsNextToken' -- -- * 'dvvrsVolumes' -- -- * 'dvvrsResponseStatus' describeVolumesResponse :: Int -- ^ 'dvvrsResponseStatus' -> DescribeVolumesResponse describeVolumesResponse pResponseStatus_ = DescribeVolumesResponse' { _dvvrsNextToken = Nothing , _dvvrsVolumes = Nothing , _dvvrsResponseStatus = pResponseStatus_ } -- | The 'NextToken' value to include in a future 'DescribeVolumes' request. -- When the results of a 'DescribeVolumes' request exceed 'MaxResults', -- this value can be used to retrieve the next page of results. This value -- is 'null' when there are no more results to return. dvvrsNextToken :: Lens' DescribeVolumesResponse (Maybe Text) dvvrsNextToken = lens _dvvrsNextToken (\ s a -> s{_dvvrsNextToken = a}); -- | Information about the volumes. dvvrsVolumes :: Lens' DescribeVolumesResponse [Volume] dvvrsVolumes = lens _dvvrsVolumes (\ s a -> s{_dvvrsVolumes = a}) . _Default . _Coerce; -- | The response status code. dvvrsResponseStatus :: Lens' DescribeVolumesResponse Int dvvrsResponseStatus = lens _dvvrsResponseStatus (\ s a -> s{_dvvrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-ec2/gen/Network/AWS/EC2/DescribeVolumes.hs
mpl-2.0
9,539
0
15
1,972
1,079
667
412
112
1
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Network.Riak.Protocol.BucketProps.ReplMode (ReplMode(..)) where import Prelude ((+), (/), (.)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified GHC.Generics as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data ReplMode = FALSE | REALTIME | FULLSYNC | TRUE deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic) instance P'.Mergeable ReplMode instance Prelude'.Bounded ReplMode where minBound = FALSE maxBound = TRUE instance P'.Default ReplMode where defaultValue = FALSE toMaybe'Enum :: Prelude'.Int -> P'.Maybe ReplMode toMaybe'Enum 0 = Prelude'.Just FALSE toMaybe'Enum 1 = Prelude'.Just REALTIME toMaybe'Enum 2 = Prelude'.Just FULLSYNC toMaybe'Enum 3 = Prelude'.Just TRUE toMaybe'Enum _ = Prelude'.Nothing instance Prelude'.Enum ReplMode where fromEnum FALSE = 0 fromEnum REALTIME = 1 fromEnum FULLSYNC = 2 fromEnum TRUE = 3 toEnum = P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Network.Riak.Protocol.BucketProps.ReplMode") . toMaybe'Enum succ FALSE = REALTIME succ REALTIME = FULLSYNC succ FULLSYNC = TRUE succ _ = Prelude'.error "hprotoc generated code: succ failure for type Network.Riak.Protocol.BucketProps.ReplMode" pred REALTIME = FALSE pred FULLSYNC = REALTIME pred TRUE = FULLSYNC pred _ = Prelude'.error "hprotoc generated code: pred failure for type Network.Riak.Protocol.BucketProps.ReplMode" instance P'.Wire ReplMode where wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum) wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum) wireGet 14 = P'.wireGetEnum toMaybe'Enum wireGet ft' = P'.wireGetErr ft' wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum wireGetPacked ft' = P'.wireGetErr ft' instance P'.GPB ReplMode instance P'.MessageAPI msg' (msg' -> ReplMode) ReplMode where getVal m' f' = f' m' instance P'.ReflectEnum ReplMode where reflectEnum = [(0, "FALSE", FALSE), (1, "REALTIME", REALTIME), (2, "FULLSYNC", FULLSYNC), (3, "TRUE", TRUE)] reflectEnumInfo _ = P'.EnumInfo (P'.makePNF (P'.pack ".Protocol.BucketProps.ReplMode") ["Network", "Riak"] ["Protocol", "BucketProps"] "ReplMode") ["Network", "Riak", "Protocol", "BucketProps", "ReplMode.hs"] [(0, "FALSE"), (1, "REALTIME"), (2, "FULLSYNC"), (3, "TRUE")] Prelude'.False instance P'.TextType ReplMode where tellT = P'.tellShow getT = P'.getRead
tmcgilchrist/riak-haskell-client
protobuf/src/Network/Riak/Protocol/BucketProps/ReplMode.hs
apache-2.0
2,796
0
11
487
748
411
337
63
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} #ifdef UNSAFETRICKS {-# LANGUAGE MagicHash #-} #endif module Data.HashTable.Weak.Internal.UnsafeTricks ( Key , toKey , fromKey , emptyRecord , deletedRecord , keyIsEmpty , keyIsDeleted , writeDeletedElement , makeEmptyVector ) where import Control.Monad.Primitive import Data.Vector.Mutable (MVector) import qualified Data.Vector.Mutable as M #ifdef UNSAFETRICKS import GHC.Exts import Unsafe.Coerce #if __GLASGOW_HASKELL__ >= 707 import GHC.Exts (isTrue#) #else isTrue# :: Bool -> Bool isTrue# = id #endif #endif ------------------------------------------------------------------------------ #ifdef UNSAFETRICKS type Key a = Any #else data Key a = Key !a | EmptyElement | DeletedElement deriving (Show) #endif ------------------------------------------------------------------------------ -- Type signatures emptyRecord :: Key a deletedRecord :: Key a keyIsEmpty :: Key a -> Bool keyIsDeleted :: Key a -> Bool makeEmptyVector :: PrimMonad m => Int -> m (MVector (PrimState m) (Key a)) writeDeletedElement :: PrimMonad m => MVector (PrimState m) (Key a) -> Int -> m () toKey :: a -> Key a fromKey :: Key a -> a #ifdef UNSAFETRICKS data TombStone = EmptyElement | DeletedElement {-# NOINLINE emptyRecord #-} emptyRecord = unsafeCoerce EmptyElement {-# NOINLINE deletedRecord #-} deletedRecord = unsafeCoerce DeletedElement {-# INLINE keyIsEmpty #-} keyIsEmpty a = isTrue# (x# ==# 1#) where !x# = reallyUnsafePtrEquality# a emptyRecord {-# INLINE keyIsDeleted #-} keyIsDeleted a = isTrue# (x# ==# 1#) where !x# = reallyUnsafePtrEquality# a deletedRecord {-# INLINE toKey #-} toKey = unsafeCoerce {-# INLINE fromKey #-} fromKey = unsafeCoerce #else emptyRecord = EmptyElement deletedRecord = DeletedElement keyIsEmpty EmptyElement = True keyIsEmpty _ = False keyIsDeleted DeletedElement = True keyIsDeleted _ = False toKey = Key fromKey (Key x) = x fromKey _ = error "impossible" #endif ------------------------------------------------------------------------------ {-# INLINE makeEmptyVector #-} makeEmptyVector m = M.replicate m emptyRecord ------------------------------------------------------------------------------ {-# INLINE writeDeletedElement #-} writeDeletedElement v i = M.unsafeWrite v i deletedRecord
cornell-pl/HsAdapton
weak-hashtables/src/Data/HashTable/Weak/Internal/UnsafeTricks.hs
bsd-3-clause
2,496
0
11
523
399
227
172
43
1
-- Copyright (c) 2013 Eric McCorkle. All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the name of the author nor the names of any contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS -- 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. {-# OPTIONS_GHC -Wall -Werror -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances, FlexibleContexts, UndecidableInstances #-} -- | This module contains extra instances for prelude-extras. module Prelude.Extras.ExtraInstances where import Data.Array(Array) import Data.List import Data.Map(Map) import Prelude.Extras import qualified Data.Array as Array import qualified Data.HashMap.Strict as Strict instance Eq2 Map instance Eq k => Eq1 (Map k) instance Eq2 Strict.HashMap instance Eq k => Eq1 (Strict.HashMap k) instance (Eq i, Array.Ix i) => Eq1 (Array i) instance Ord2 Map instance Ord k => Ord1 (Map k) instance Ord2 Strict.HashMap instance Ord k => Ord1 (Strict.HashMap k) instance (Ord i, Array.Ix i) => Ord1 (Array i) instance (Ord k, Ord v) => Ord (Strict.HashMap k v) where compare m1 m2 = let list1 = sort (Strict.toList m1) list2 = sort (Strict.toList m2) in compare1 list1 list2
saltlang/compiler-toolbox
src/Prelude/Extras/ExtraInstances.hs
bsd-3-clause
2,483
0
13
431
348
192
156
25
0
module Perceptron where type Gate = Float -> Float -> Float makeGate :: Float -> Float -> Float -> Gate makeGate w1 w2 b x1 x2 | x1 * w1 + x2 * w2 + b <= 0 = 0 | otherwise = 1 -- | -- >>> andGate 0 0 -- 0.0 -- >>> andGate 0 1 -- 0.0 -- >>> andGate 1 0 -- 0.0 -- >>> andGate 1 1 -- 1.0 andGate :: Gate andGate = makeGate 0.5 0.5 (negate 0.7) -- | -- >>> nandGate 0 0 -- 1.0 -- >>> nandGate 0 1 -- 1.0 -- >>> nandGate 1 0 -- 1.0 -- >>> nandGate 1 1 -- 0.0 nandGate :: Gate nandGate = makeGate (negate 0.5) (negate 0.5) 0.7 -- | -- >>> orGate 0 0 -- 0.0 -- >>> orGate 0 1 -- 1.0 -- >>> orGate 1 0 -- 1.0 -- >>> orGate 1 1 -- 1.0 orGate :: Gate orGate = makeGate 0.5 0.5 (negate 0.2) -- | -- >>> xorGate 0 0 -- 0.0 -- >>> xorGate 0 1 -- 1.0 -- >>> xorGate 1 0 -- 1.0 -- >>> xorGate 1 1 -- 0.0 xorGate :: Gate xorGate x1 x2 = andGate (nandGate x1 x2) (orGate x1 x2)
kayhide/deep-learning-from-scratch
src/Perceptron.hs
bsd-3-clause
871
0
12
219
233
137
96
14
1
{-# LANGUAGE TypeFamilies #-} module Tuura.Concurrency ( ConcurrencyOracle, oracleMokhovCarmona, reduce, reduceLog ) where import Data.List import Tuura.Log import Tuura.Graph type ConcurrencyOracle a = a -> a -> Bool -- Given a log determine if two events are concurrent oracleMokhovCarmona :: Ord e => Log e -> ConcurrencyOracle e oracleMokhovCarmona log a b = not (null logAB || null logBA) && persistentEvents logAB == persistentEvents logBA && events logAB == events logBA where logAB = filter ([a, b] `isSubsequenceOf`) log logBA = filter ([b, a] `isSubsequenceOf`) log -- Reduce a given trace to a partial order using a concurrency oracle -- The resulting partial order is represented by a Graph in a canonical way reduce :: (Graph g, Ord e, Vertex g ~ e) => ConcurrencyOracle e -> Trace e -> g reduce co trace | null singles = fromList arcs | null arcs = vertices singles | otherwise = vertices singles `overlay` fromList arcs where x >< y = not (x `co` y) totals = blocks (><) trace spine = concatMap (\xs -> zip xs (tail xs)) totals extra = concat [ cross (><) x y | (x:xs) <- tails totals, y <- xs ] arcs = sort $ spine ++ extra singles = sort $ trace \\ (uncurry (++) $ unzip arcs) -- Split a list into blocks where neighboring elements are in a given relation blocks :: (a -> a -> Bool) -> [a] -> [[a]] blocks _ [] = [] blocks _ [x] = [[x]] blocks r (x:y:rest) = if r x y then (x:b):bs else [x]:b:bs where (b:bs) = blocks r (y:rest) -- Given a relation and two total orders, compute the transitive reduction of -- the relation w.r.t. to the total orders cross :: (a -> b -> Bool) -> [a] -> [b] -> [(a, b)] cross r as = reverse . go (reverse as) where go [] _ = [] go _ [] = [] go (x:xs) ys | null rest = go xs ys | otherwise = (x, head rest) : go xs notr where (notr, rest) = span (not . r x) ys -- Reduce concurrency in each trace and drop repetitions in the result reduceLog :: (Graph g, Ord e, Ord g, Vertex g ~ e) => ConcurrencyOracle e -> Log e -> [g] reduceLog co = canonicalise . map (reduce co)
tuura/process-mining
src/Tuura/Concurrency.hs
bsd-3-clause
2,191
0
12
566
845
442
403
42
3
{-# LANGUAGE BangPatterns, ScopedTypeVariables, RecordWildCards, FlexibleContexts, TypeFamilies #-} -- | -- Module : AI.HNN.FF.Network -- Copyright : (c) 2012 Alp Mestanogullari -- License : BSD3 -- Maintainer : alpmestan@gmail.com -- Stability : experimental -- Portability : GHC -- -- An implementation of feed-forward neural networks in pure Haskell. -- -- It uses weight matrices between each layer to represent the connections between neurons from -- a layer to the next and exports only the useful bits for a user of the library. -- -- Here is an example of using this module to create a feed-forward neural network with 2 inputs, -- 2 neurons in a hidden layer and one neuron in the output layer, with random weights, and compute -- its output for [1,2] using the sigmoid function for activation for all the neurons. -- -- > import AI.HNN.FF.Network -- > import Numeric.LinearAlgebra -- > -- > main = do -- > n <- createNetwork 2 [2] 1 :: IO (Network Double) -- > print $ output n sigmoid (fromList [1, 1]) -- -- /Note/: Here, I create a @Network Double@, but you can replace 'Double' with any number type -- that implements the appropriate typeclasses you can see in the signatures of this module. -- Having your number type implement the @Floating@ typeclass too is a good idea, since that's what most of the -- common activation functions require. -- -- /Note 2/: You can also give some precise weights to initialize the neural network with, with -- 'fromWeightMatrices'. You can also restore a neural network you had saved using 'loadNetwork'. -- -- Here is an example of how to train a neural network to learn the XOR function. -- ( for reference: XOR(0, 0) = 0, XOR(0, 1) = 1, XOR(1, 0) = 1, XOR(1, 1) = 0 ) -- -- First, let's import hnn's feedforward neural net module, and hmatrix's vector types. -- -- > import AI.HNN.FF.Network -- > import Numeric.LinearAlgebra -- -- Now, we will specify our training set (what the net should try to learn). -- -- > samples :: Samples Double -- > samples = [ fromList [0, 0] --> fromList [0] -- > , fromList [0, 1] --> fromList [1] -- > , fromList [1, 0] --> fromList [1] -- > , fromList [1, 1] --> fromList [0] -- > ] -- -- You can see that this is basically a list of pairs of vectors, the first vector being -- the input given to the network, the second one being the expected output. Of course, -- this imply working on a neural network with 2 inputs, and a single neuron on the output layer. Then, -- let's create one! -- -- > main = do -- > net <- createNetwork 2 [2] 1 -- -- You may have noticed we haven't specified a signature this time, unlike in the earlier snippet. -- Since we gave a signature to samples, specifying we're working with 'Double' numbers, and since -- we are going to tie 'net' and 'samples' by a call to a learning function, GHC will gladly figure out -- that 'net' is working with 'Double'. -- -- Now, it's time to train our champion. But first, let's see how bad he is now. The weights are most likely -- not close to those that will give a good result for simulating XOR. Let's compute the output of the net on -- the input vectors of our samples, using 'tanh' as the activation function. -- -- > mapM_ (print . output net tanh . fst) samples -- -- Ok, you've tested this, and it gives terrible results. Let's fix this by letting 'trainNTimes' teach our neural net -- how to behave. Since we're using 'tanh' as our activation function, we will tell it to the training function, -- and also specify its derivative. -- -- > let smartNet = trainNTimes 1000 0.8 tanh tanh' net samples -- -- So, this tiny piece of code will run the backpropagation algorithm on the samples 1000 times, with a learning rate -- of 0.8. The learning rate is basically how strongly we should modify the weights when we try to correct the error the net makes -- on our samples. The bigger it is, the more the weights are going to change significantly. Depending on the case, it can be good, -- but sometimes it can make the backprop algorithm oscillate around good weight values without actually getting to them. -- You usually want to test several values and see which ones get you the nicest neural net, which generalizes well to samples -- that are not in the training set while giving decent results on the training set. -- -- Now, let's see how that worked out for us: -- -- > mapM_ (print . output smartNet tanh . fst) samples -- -- You could even save that neural network's weights to a file, so that you don't need to train it again in the future, using 'saveNetwork': -- -- > saveNetwork "smartNet.nn" smartNet -- -- Please note that 'saveNetwork' is just a wrapper around zlib compression + serialization using the binary package. -- AI.HNN.FF.Network also provides a 'Data.Binary.Binary' instance for 'Network', which means you can also simply use -- 'Data.Binary.encode' and 'Data.Binary.decode' to have your own saving/restoring routines, or to simply get a bytestring -- we can send over the network, for example. -- -- Here's a run of the program we described on my machine (with the timing): first set of -- fromList's is the output of the initial neural network, the second one is the output of -- 'smartNet' :-) -- -- > fromList [0.574915179613429] -- > fromList [0.767589097192215] -- > fromList [0.7277396607146663] -- > fromList [0.8227114080561128] -- > ------------------ -- > fromList [6.763498312099933e-2] -- > fromList [0.9775186355284375] -- > fromList [0.9350823296850516] -- > fromList [-4.400205702560454e-2] -- > -- > real 0m0.365s -- > user 0m0.072s -- > sys 0m0.016s -- -- Rejoyce! Feel free to play around with the library and report any bug, feature request and whatnot to us on -- our github repository <https://github.com/alpmestan/hnn/issues> using the appropriate tags. Also, you can -- see the simple program we studied here with pretty colors at <https://github.com/alpmestan/hnn/blob/master/examples/ff/xor.hs> -- and other ones at <https://github.com/alpmestan/hnn/tree/master/examples/ff>. module AI.HNN.FF.Network ( -- * Types Network(..) , ActivationFunction , ActivationFunctionDerivative , Sample , Samples , (-->) -- * Creating a neural network , createNetwork , fromWeightMatrices -- * Computing a neural network's output , output , tanh , tanh' , sigmoid , sigmoid' -- * Training a neural network , trainUntil , trainNTimes , trainUntilErrorBelow , quadError -- * Loading and saving a neural network , loadNetwork , saveNetwork ) where import Codec.Compression.Zlib (compress, decompress) import Data.Binary (Binary(..), encode, decode) import Data.List (foldl') import Foreign.Storable (Storable) import qualified Data.ByteString.Lazy as B import qualified Data.Vector as V import System.Random.MWC import Numeric.LinearAlgebra -- | Our feed-forward neural network type. Note the 'Binary' instance, which means you can use -- 'encode' and 'decode' in case you need to serialize your neural nets somewhere else than -- in a file (e.g over the network) newtype Network a = Network { matrices :: V.Vector (Matrix a) -- ^ the weight matrices } deriving Show instance (Element a, Binary a) => Binary (Network a) where put (Network ms) = put . V.toList $ ms get = (Network . V.fromList) `fmap` get -- | The type of an activation function, mostly used for clarity in signatures type ActivationFunction a = a -> a -- | The type of an activation function's derivative, mostly used for clarity in signatures type ActivationFunctionDerivative a = a -> a -- | The following creates a neural network with 'n' inputs and if 'l' is [n1, n2, ...] -- the net will have n1 neurons on the first layer, n2 neurons on the second, and so on -- ending with k neurons on the output layer, with random weight matrices as a courtesy of -- 'System.Random.MWC.uniformVector'. -- -- > createNetwork n l k createNetwork :: (Variate a, Storable a) => Int -> [Int] -> Int -> IO (Network a) createNetwork nInputs hiddens nOutputs = fmap Network $ withSystemRandom . asGenST $ \gen -> go gen dimensions V.empty where go _ [] !ms = return ms go gen ((!n,!m):ds) ms = do !mat <- randomMat n m gen go gen ds (ms `V.snoc` mat) randomMat n m g = reshape m `fmap` uniformVector g (n*m) dimensions = zip (hiddens ++ [nOutputs]) $ (nInputs+1 : hiddens) {-# INLINE createNetwork #-} -- | Creates a neural network with exactly the weight matrices given as input here. -- We don't check that the numbers of rows/columns are compatible, etc. fromWeightMatrices :: Storable a => V.Vector (Matrix a) -> Network a fromWeightMatrices ws = Network ws {-# INLINE fromWeightMatrices #-} -- The `join [input, 1]' trick below is a courtesy of Alberto Ruiz -- <http://dis.um.es/~alberto/>. Per his words: -- -- "The idea is that the constant input in the first layer can be automatically transferred to the following layers -- by the learning algorithm (by setting the weights of a neuron to 1,0,0,0,...). This allows for a simpler -- implementation and in my experiments those networks are able to easily solve non linearly separable problems." -- | Computes the output of the network on the given input vector with the given activation function output :: (Floating (Vector a), Product a, Storable a, Num (Vector a)) => Network a -> ActivationFunction a -> Vector a -> Vector a output (Network{..}) act input = V.foldl' f (vjoin [input, 1]) matrices where f !inp m = mapVector act $ m <> inp {-# INLINE output #-} -- | Computes and keeps the output of all the layers of the neural network with the given activation function outputs :: (Floating (Vector a), Product a, Storable a, Num (Vector a)) => Network a -> ActivationFunction a -> Vector a -> V.Vector (Vector a) outputs (Network{..}) act input = V.scanl f (vjoin [input, 1]) matrices where f !inp m = mapVector act $ m <> inp {-# INLINE outputs #-} deltas :: (Floating (Vector a), Floating a, Product a, Storable a, Num (Vector a)) => Network a -> ActivationFunctionDerivative a -> V.Vector (Vector a) -> Vector a -> V.Vector (Matrix a) deltas (Network{..}) act' os expected = V.zipWith outer (V.tail ds) (V.init os) where !dl = (V.last os - expected) * (deriv $ V.last os) !ds = V.scanr f dl (V.zip os matrices) f (!o, m) !del = deriv o * (trans m <> del) deriv = mapVector act' {-# INLINE deltas #-} updateNetwork :: (Floating (Vector a), Floating a, Product a, Storable a, Num (Vector a), Container Vector a) => a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Sample a -> Network a updateNetwork alpha act act' n@(Network{..}) (input, expectedOutput) = Network $ V.zipWith (+) matrices corr where !xs = outputs n act input !ds = deltas n act' xs expectedOutput !corr = V.map (scale (-alpha)) ds {-# INLINE updateNetwork #-} -- | Input vector and expected output vector type Sample a = (Vector a, Vector a) -- | List of 'Sample's type Samples a = [Sample a] -- | Handy operator to describe your learning set, avoiding unnecessary parentheses. It's just a synonym for '(,)'. -- Generally you'll load your learning set from a file, a database or something like that, but it can be nice for -- quickly playing with hnn or for simple problems where you manually specify your learning set. -- That is, instead of writing: -- -- > samples :: Samples Double -- > samples = [ (fromList [0, 0], fromList [0]) -- > , (fromList [0, 1], fromList [1]) -- > , (fromList [1, 0], fromList [1]) -- > , (fromList [1, 1], fromList [0]) -- > ] -- -- You can write: -- -- > samples :: Samples Double -- > samples = [ fromList [0, 0] --> fromList [0] -- > , fromList [0, 1] --> fromList [1] -- > , fromList [1, 0] --> fromList [1] -- > , fromList [1, 1] --> fromList [0] -- > ] (-->) :: Vector a -> Vector a -> Sample a (-->) = (,) backpropOnce :: (Floating (Vector a), Floating a, Product a, Num (Vector a), Container Vector a) => a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a backpropOnce rate act act' n samples = foldl' (updateNetwork rate act act') n samples {-# INLINE backpropOnce #-} -- | Generic training function. -- -- The first argument is a predicate that will tell the backpropagation algorithm when to stop. -- The first argument to the predicate is the epoch, i.e the number of times the backprop has been -- executed on the samples. The second argument is /the current network/, and the third is the list of samples. -- You can thus combine these arguments to create your own criterion. -- -- For example, if you want to stop learning either when the network's quadratic error on the samples, -- using the tanh function, is below 0.01, or after 1000 epochs, whichever comes first, you could -- use the following predicate: -- -- > pred epochs net samples = if epochs == 1000 then True else quadError tanh net samples < 0.01 -- -- You could even use 'Debug.Trace.trace' to print the error, to see how the error evolves while it's learning, -- or redirect this to a file from your shell in order to generate a pretty graphics and what not. -- -- The second argument (after the predicate) is the learning rate. Then come the activation function you want, -- its derivative, the initial neural network, and your training set. -- Note that we provide 'trainNTimes' and 'trainUntilErrorBelow' for common use cases. trainUntil :: (Floating (Vector a), Floating a, Product a, Num (Vector a), Container Vector a) => (Int -> Network a -> Samples a -> Bool) -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a trainUntil pr learningRate act act' net samples = go net 0 where go n !k | pr k n samples = n | otherwise = case backpropOnce learningRate act act' n samples of n' -> go n' (k+1) {-# INLINE trainUntil #-} -- | Trains the neural network with backpropagation the number of times specified by the 'Int' argument, -- using the given learning rate (second argument). trainNTimes :: (Floating (Vector a), Floating a, Product a, Num (Vector a), Container Vector a) => Int -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a trainNTimes n = trainUntil (\k _ _ -> k > n) {-# INLINE trainNTimes #-} -- | Quadratic error on the given training set using the given activation function. Useful to create -- your own predicates for 'trainUntil'. quadError :: (Floating (Vector a), Floating a, Num (Vector a), Num (RealOf a), Product a) => ActivationFunction a -> Network a -> Samples a -> RealOf a quadError act net samples = foldl' (\err (inp, out) -> err + (norm2 $ output net act inp - out)) 0 samples {-# INLINE quadError #-} -- | Trains the neural network until the quadratic error ('quadError') comes below the given value (first argument), -- using the given learning rate (second argument). -- -- /Note/: this can loop pretty much forever when you're using a bad architecture for the problem, or inappropriate activation -- functions. trainUntilErrorBelow :: (Floating (Vector a), Floating a, Product a, Num (Vector a), Ord a, Container Vector a, Num (RealOf a), a ~ RealOf a, Show a) => a -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a trainUntilErrorBelow x rate act = trainUntil (\_ n s -> quadError act n s < x) rate act {-# INLINE trainUntilErrorBelow #-} -- | The sigmoid function: 1 / (1 + exp (-x)) sigmoid :: Floating a => a -> a sigmoid !x = 1 / (1 + exp (-x)) {-# INLINE sigmoid #-} -- | Derivative of the sigmoid function: sigmoid x * (1 - sigmoid x) sigmoid' :: Floating a => a -> a sigmoid' !x = case sigmoid x of s -> s * (1 - s) {-# INLINE sigmoid' #-} -- | Derivative of the 'tanh' function from the Prelude. tanh' :: Floating a => a -> a tanh' !x = case tanh x of s -> 1 - s**2 {-# INLINE tanh' #-} -- | Loading a neural network from a file (uses zlib compression on top of serialization using the binary package). -- Will throw an exception if the file isn't there. loadNetwork :: (Storable a, Element a, Binary a) => FilePath -> IO (Network a) loadNetwork fp = return . decode . decompress =<< B.readFile fp {-# INLINE loadNetwork #-} -- | Saving a neural network to a file (uses zlib compression on top of serialization using the binary package). saveNetwork :: (Storable a, Element a, Binary a) => FilePath -> Network a -> IO () saveNetwork fp net = B.writeFile fp . compress $ encode net {-# INLINE saveNetwork #-}
fffej/hnn
AI/HNN/FF/Network.hs
bsd-3-clause
17,075
0
13
3,668
2,578
1,417
1,161
116
2
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Network/Wai/Handler/Warp/SendFile.hs" #-} {-# LANGUAGE CPP, ForeignFunctionInterface #-} module Network.Wai.Handler.Warp.SendFile ( sendFile , readSendFile , packHeader -- for testing , positionRead ) where import Control.Monad (void, when) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Network.Socket (Socket) import Network.Wai.Handler.Warp.Buffer import Network.Wai.Handler.Warp.Types import Control.Exception import Foreign.C.Error (throwErrno) import Foreign.C.Types import Foreign.Ptr (Ptr, castPtr, plusPtr) import Network.Sendfile import Network.Wai.Handler.Warp.FdCache (openFile, closeFile) import System.Posix.Types ---------------------------------------------------------------- -- | Function to send a file based on sendfile() for Linux\/Mac\/FreeBSD. -- This makes use of the file descriptor cache. -- For other OSes, this is identical to 'readSendFile'. -- -- Since: 3.1.0 sendFile :: Socket -> Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile sendFile s _ _ _ fid off len act hdr = case mfid of -- settingsFdCacheDuration is 0 Nothing -> sendfileWithHeader s path (PartOfFile off len) act hdr Just fd -> sendfileFdWithHeader s fd (PartOfFile off len) act hdr where mfid = fileIdFd fid path = fileIdPath fid ---------------------------------------------------------------- packHeader :: Buffer -> BufSize -> (ByteString -> IO ()) -> IO () -> [ByteString] -> Int -> IO Int packHeader _ _ _ _ [] n = return n packHeader buf siz send hook (bs:bss) n | len < room = do let dst = buf `plusPtr` n void $ copy dst bs packHeader buf siz send hook bss (n + len) | otherwise = do let dst = buf `plusPtr` n (bs1, bs2) = BS.splitAt room bs void $ copy dst bs1 bufferIO buf siz send hook packHeader buf siz send hook (bs2:bss) 0 where len = BS.length bs room = siz - n mini :: Int -> Integer -> Int mini i n | fromIntegral i < n = i | otherwise = fromIntegral n -- | Function to send a file based on pread()\/send() for Unix. -- This makes use of the file descriptor cache. -- For Windows, this is emulated by 'Handle'. -- -- Since: 3.1.0 readSendFile :: Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile readSendFile buf siz send fid off0 len0 hook headers = bracket setup teardown $ \fd -> do hn <- packHeader buf siz send hook headers 0 let room = siz - hn buf' = buf `plusPtr` hn n <- positionRead fd buf' (mini room len0) off0 bufferIO buf (hn + n) send hook let n' = fromIntegral n loop fd (len0 - n') (off0 + n') where path = fileIdPath fid setup = case fileIdFd fid of Just fd -> return fd Nothing -> openFile path teardown fd = case fileIdFd fid of Just _ -> return () Nothing -> closeFile fd loop fd len off | len <= 0 = return () | otherwise = do n <- positionRead fd buf (mini siz len) off bufferIO buf n send let n' = fromIntegral n hook loop fd (len - n') (off + n') positionRead :: Fd -> Buffer -> BufSize -> Integer -> IO Int positionRead fd buf siz off = do bytes <- fromIntegral <$> c_pread fd (castPtr buf) (fromIntegral siz) (fromIntegral off) when (bytes < 0) $ throwErrno "positionRead" return bytes foreign import ccall unsafe "pread" c_pread :: Fd -> Ptr CChar -> ByteCount -> FileOffset -> IO CSsize
phischu/fragnix
tests/packages/scotty/Network.Wai.Handler.Warp.SendFile.hs
bsd-3-clause
3,680
0
13
1,007
1,131
576
555
83
3
{-# LANGUAGE DeriveDataTypeable, MagicHash, PolymorphicComponents, RoleAnnotations, UnboxedTuples #-} ----------------------------------------------------------------------------- -- | -- Module : Language.Haskell.Syntax -- Copyright : (c) The University of Glasgow 2003 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : portable -- -- Abstract syntax definitions for Template Haskell. -- ----------------------------------------------------------------------------- module Language.Haskell.TH.Syntax where import GHC.Exts import Data.Data (Data(..), Typeable, mkConstr, mkDataType, constrIndex) import qualified Data.Data as Data import Control.Applicative( Applicative(..) ) import Data.IORef import System.IO.Unsafe ( unsafePerformIO ) import Control.Monad (liftM) import System.IO ( hPutStrLn, stderr ) import Data.Char ( isAlpha, isAlphaNum, isUpper ) import Data.Word ( Word8 ) ----------------------------------------------------- -- -- The Quasi class -- ----------------------------------------------------- class (Monad m, Applicative m) => Quasi m where qNewName :: String -> m Name -- ^ Fresh names -- Error reporting and recovery qReport :: Bool -> String -> m () -- ^ Report an error (True) or warning (False) -- ...but carry on; use 'fail' to stop qRecover :: m a -- ^ the error handler -> m a -- ^ action which may fail -> m a -- ^ Recover from the monadic 'fail' -- Inspect the type-checker's environment qLookupName :: Bool -> String -> m (Maybe Name) -- True <=> type namespace, False <=> value namespace qReify :: Name -> m Info qReifyInstances :: Name -> [Type] -> m [Dec] -- Is (n tys) an instance? -- Returns list of matching instance Decs -- (with empty sub-Decs) -- Works for classes and type functions qReifyRoles :: Name -> m [Role] qReifyAnnotations :: Data a => AnnLookup -> m [a] qReifyModule :: Module -> m ModuleInfo qLocation :: m Loc qRunIO :: IO a -> m a -- ^ Input/output (dangerous) qAddDependentFile :: FilePath -> m () qAddTopDecls :: [Dec] -> m () qAddModFinalizer :: Q () -> m () qGetQ :: Typeable a => m (Maybe a) qPutQ :: Typeable a => a -> m () ----------------------------------------------------- -- The IO instance of Quasi -- -- This instance is used only when running a Q -- computation in the IO monad, usually just to -- print the result. There is no interesting -- type environment, so reification isn't going to -- work. -- ----------------------------------------------------- instance Quasi IO where qNewName s = do { n <- readIORef counter ; writeIORef counter (n+1) ; return (mkNameU s n) } qReport True msg = hPutStrLn stderr ("Template Haskell error: " ++ msg) qReport False msg = hPutStrLn stderr ("Template Haskell error: " ++ msg) qLookupName _ _ = badIO "lookupName" qReify _ = badIO "reify" qReifyInstances _ _ = badIO "reifyInstances" qReifyRoles _ = badIO "reifyRoles" qReifyAnnotations _ = badIO "reifyAnnotations" qReifyModule _ = badIO "reifyModule" qLocation = badIO "currentLocation" qRecover _ _ = badIO "recover" -- Maybe we could fix this? qAddDependentFile _ = badIO "addDependentFile" qAddTopDecls _ = badIO "addTopDecls" qAddModFinalizer _ = badIO "addModFinalizer" qGetQ = badIO "getQ" qPutQ _ = badIO "putQ" qRunIO m = m badIO :: String -> IO a badIO op = do { qReport True ("Can't do `" ++ op ++ "' in the IO monad") ; fail "Template Haskell failure" } -- Global variable to generate unique symbols counter :: IORef Int {-# NOINLINE counter #-} counter = unsafePerformIO (newIORef 0) ----------------------------------------------------- -- -- The Q monad -- ----------------------------------------------------- newtype Q a = Q { unQ :: forall m. Quasi m => m a } -- \"Runs\" the 'Q' monad. Normal users of Template Haskell -- should not need this function, as the splice brackets @$( ... )@ -- are the usual way of running a 'Q' computation. -- -- This function is primarily used in GHC internals, and for debugging -- splices by running them in 'IO'. -- -- Note that many functions in 'Q', such as 'reify' and other compiler -- queries, are not supported when running 'Q' in 'IO'; these operations -- simply fail at runtime. Indeed, the only operations guaranteed to succeed -- are 'newName', 'runIO', 'reportError' and 'reportWarning'. runQ :: Quasi m => Q a -> m a runQ (Q m) = m instance Monad Q where return x = Q (return x) Q m >>= k = Q (m >>= \x -> unQ (k x)) Q m >> Q n = Q (m >> n) fail s = report True s >> Q (fail "Q monad failure") instance Functor Q where fmap f (Q x) = Q (fmap f x) instance Applicative Q where pure x = Q (pure x) Q f <*> Q x = Q (f <*> x) ----------------------------------------------------- -- -- The TExp type -- ----------------------------------------------------- type role TExp nominal -- See Note [Role of TExp] newtype TExp a = TExp { unType :: Exp } unTypeQ :: Q (TExp a) -> Q Exp unTypeQ m = do { TExp e <- m ; return e } unsafeTExpCoerce :: Q Exp -> Q (TExp a) unsafeTExpCoerce m = do { e <- m ; return (TExp e) } {- Note [Role of TExp] ~~~~~~~~~~~~~~~~~~~~~~ TExp's argument must have a nominal role, not phantom as would be inferred (Trac #8459). Consider e :: TExp Age e = MkAge 3 foo = $(coerce e) + 4::Int The splice will evaluate to (MkAge 3) and you can't add that to 4::Int. So you can't coerce a (TExp Age) to a (TExp Int). -} ---------------------------------------------------- -- Packaged versions for the programmer, hiding the Quasi-ness {- | Generate a fresh name, which cannot be captured. For example, this: @f = $(do nm1 <- newName \"x\" let nm2 = 'mkName' \"x\" return ('LamE' ['VarP' nm1] (LamE [VarP nm2] ('VarE' nm1))) )@ will produce the splice >f = \x0 -> \x -> x0 In particular, the occurrence @VarE nm1@ refers to the binding @VarP nm1@, and is not captured by the binding @VarP nm2@. Although names generated by @newName@ cannot /be captured/, they can /capture/ other names. For example, this: >g = $(do > nm1 <- newName "x" > let nm2 = mkName "x" > return (LamE [VarP nm2] (LamE [VarP nm1] (VarE nm2))) > ) will produce the splice >g = \x -> \x0 -> x0 since the occurrence @VarE nm2@ is captured by the innermost binding of @x@, namely @VarP nm1@. -} newName :: String -> Q Name newName s = Q (qNewName s) -- | Report an error (True) or warning (False), -- but carry on; use 'fail' to stop. report :: Bool -> String -> Q () report b s = Q (qReport b s) {-# DEPRECATED report "Use reportError or reportWarning instead" #-} -- deprecated in 7.6 -- | Report an error to the user, but allow the current splice's computation to carry on. To abort the computation, use 'fail'. reportError :: String -> Q () reportError = report True -- | Report a warning to the user, and carry on. reportWarning :: String -> Q () reportWarning = report False -- | Recover from errors raised by 'reportError' or 'fail'. recover :: Q a -- ^ handler to invoke on failure -> Q a -- ^ computation to run -> Q a recover (Q r) (Q m) = Q (qRecover r m) -- We don't export lookupName; the Bool isn't a great API -- Instead we export lookupTypeName, lookupValueName lookupName :: Bool -> String -> Q (Maybe Name) lookupName ns s = Q (qLookupName ns s) -- | Look up the given name in the (type namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details. lookupTypeName :: String -> Q (Maybe Name) lookupTypeName s = Q (qLookupName True s) -- | Look up the given name in the (value namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details. lookupValueName :: String -> Q (Maybe Name) lookupValueName s = Q (qLookupName False s) {- Note [Name lookup] ~~~~~~~~~~~~~~~~~~ -} {- $namelookup #namelookup# The functions 'lookupTypeName' and 'lookupValueName' provide a way to query the current splice's context for what names are in scope. The function 'lookupTypeName' queries the type namespace, whereas 'lookupValueName' queries the value namespace, but the functions are otherwise identical. A call @lookupValueName s@ will check if there is a value with name @s@ in scope at the current splice's location. If there is, the @Name@ of this value is returned; if not, then @Nothing@ is returned. The returned name cannot be \"captured\". For example: > f = "global" > g = $( do > Just nm <- lookupValueName "f" > [| let f = "local" in $( varE nm ) |] In this case, @g = \"global\"@; the call to @lookupValueName@ returned the global @f@, and this name was /not/ captured by the local definition of @f@. The lookup is performed in the context of the /top-level/ splice being run. For example: > f = "global" > g = $( [| let f = "local" in > $(do > Just nm <- lookupValueName "f" > varE nm > ) |] ) Again in this example, @g = \"global\"@, because the call to @lookupValueName@ queries the context of the outer-most @$(...)@. Operators should be queried without any surrounding parentheses, like so: > lookupValueName "+" Qualified names are also supported, like so: > lookupValueName "Prelude.+" > lookupValueName "Prelude.map" -} {- | 'reify' looks up information about the 'Name'. It is sometimes useful to construct the argument name using 'lookupTypeName' or 'lookupValueName' to ensure that we are reifying from the right namespace. For instance, in this context: > data D = D which @D@ does @reify (mkName \"D\")@ return information about? (Answer: @D@-the-type, but don't rely on it.) To ensure we get information about @D@-the-value, use 'lookupValueName': > do > Just nm <- lookupValueName "D" > reify nm and to get information about @D@-the-type, use 'lookupTypeName'. -} reify :: Name -> Q Info reify v = Q (qReify v) {- | @reifyInstances nm tys@ returns a list of visible instances of @nm tys@. That is, if @nm@ is the name of a type class, then all instances of this class at the types @tys@ are returned. Alternatively, if @nm@ is the name of a data family or type family, all instances of this family at the types @tys@ are returned. -} reifyInstances :: Name -> [Type] -> Q [InstanceDec] reifyInstances cls tys = Q (qReifyInstances cls tys) {- | @reifyRoles nm@ returns the list of roles associated with the parameters of the tycon @nm@. Fails if @nm@ cannot be found or is not a tycon. The returned list should never contain 'InferR'. -} reifyRoles :: Name -> Q [Role] reifyRoles nm = Q (qReifyRoles nm) -- | @reifyAnnotations target@ returns the list of annotations -- associated with @target@. Only the annotations that are -- appropriately typed is returned. So if you have @Int@ and @String@ -- annotations for the same target, you have to call this function twice. reifyAnnotations :: Data a => AnnLookup -> Q [a] reifyAnnotations an = Q (qReifyAnnotations an) -- | @reifyModule mod@ looks up information about module @mod@. To -- look up the current module, call this function with the return -- value of @thisModule@. reifyModule :: Module -> Q ModuleInfo reifyModule m = Q (qReifyModule m) -- | Is the list of instances returned by 'reifyInstances' nonempty? isInstance :: Name -> [Type] -> Q Bool isInstance nm tys = do { decs <- reifyInstances nm tys ; return (not (null decs)) } -- | The location at which this computation is spliced. location :: Q Loc location = Q qLocation -- |The 'runIO' function lets you run an I\/O computation in the 'Q' monad. -- Take care: you are guaranteed the ordering of calls to 'runIO' within -- a single 'Q' computation, but not about the order in which splices are run. -- -- Note: for various murky reasons, stdout and stderr handles are not -- necesarily flushed when the compiler finishes running, so you should -- flush them yourself. runIO :: IO a -> Q a runIO m = Q (qRunIO m) -- | Record external files that runIO is using (dependent upon). -- The compiler can then recognize that it should re-compile the file using this TH when the external file changes. -- Note that ghc -M will still not know about these dependencies - it does not execute TH. -- Expects an absolute file path. addDependentFile :: FilePath -> Q () addDependentFile fp = Q (qAddDependentFile fp) -- | Add additional top-level declarations. The added declarations will be type -- checked along with the current declaration group. addTopDecls :: [Dec] -> Q () addTopDecls ds = Q (qAddTopDecls ds) -- | Add a finalizer that will run in the Q monad after the current module has -- been type checked. This only makes sense when run within a top-level splice. addModFinalizer :: Q () -> Q () addModFinalizer act = Q (qAddModFinalizer (unQ act)) -- | Get state from the Q monad. getQ :: Typeable a => Q (Maybe a) getQ = Q qGetQ -- | Replace the state in the Q monad. putQ :: Typeable a => a -> Q () putQ x = Q (qPutQ x) instance Quasi Q where qNewName = newName qReport = report qRecover = recover qReify = reify qReifyInstances = reifyInstances qReifyRoles = reifyRoles qReifyAnnotations = reifyAnnotations qReifyModule = reifyModule qLookupName = lookupName qLocation = location qRunIO = runIO qAddDependentFile = addDependentFile qAddTopDecls = addTopDecls qAddModFinalizer = addModFinalizer qGetQ = getQ qPutQ = putQ ---------------------------------------------------- -- The following operations are used solely in DsMeta when desugaring brackets -- They are not necessary for the user, who can use ordinary return and (>>=) etc returnQ :: a -> Q a returnQ = return bindQ :: Q a -> (a -> Q b) -> Q b bindQ = (>>=) sequenceQ :: [Q a] -> Q [a] sequenceQ = sequence ----------------------------------------------------- -- -- The Lift class -- ----------------------------------------------------- class Lift t where lift :: t -> Q Exp instance Lift Integer where lift x = return (LitE (IntegerL x)) instance Lift Int where lift x= return (LitE (IntegerL (fromIntegral x))) instance Lift Char where lift x = return (LitE (CharL x)) instance Lift Bool where lift True = return (ConE trueName) lift False = return (ConE falseName) instance Lift a => Lift (Maybe a) where lift Nothing = return (ConE nothingName) lift (Just x) = liftM (ConE justName `AppE`) (lift x) instance (Lift a, Lift b) => Lift (Either a b) where lift (Left x) = liftM (ConE leftName `AppE`) (lift x) lift (Right y) = liftM (ConE rightName `AppE`) (lift y) instance Lift a => Lift [a] where lift xs = do { xs' <- mapM lift xs; return (ListE xs') } liftString :: String -> Q Exp -- Used in TcExpr to short-circuit the lifting for strings liftString s = return (LitE (StringL s)) instance (Lift a, Lift b) => Lift (a, b) where lift (a, b) = liftM TupE $ sequence [lift a, lift b] instance (Lift a, Lift b, Lift c) => Lift (a, b, c) where lift (a, b, c) = liftM TupE $ sequence [lift a, lift b, lift c] instance (Lift a, Lift b, Lift c, Lift d) => Lift (a, b, c, d) where lift (a, b, c, d) = liftM TupE $ sequence [lift a, lift b, lift c, lift d] instance (Lift a, Lift b, Lift c, Lift d, Lift e) => Lift (a, b, c, d, e) where lift (a, b, c, d, e) = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e] instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f) => Lift (a, b, c, d, e, f) where lift (a, b, c, d, e, f) = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f] instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f, Lift g) => Lift (a, b, c, d, e, f, g) where lift (a, b, c, d, e, f, g) = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f, lift g] -- TH has a special form for literal strings, -- which we should take advantage of. -- NB: the lhs of the rule has no args, so that -- the rule will apply to a 'lift' all on its own -- which happens to be the way the type checker -- creates it. {-# RULES "TH:liftString" lift = \s -> return (LitE (StringL s)) #-} trueName, falseName :: Name trueName = mkNameG DataName "ghc-prim" "GHC.Types" "True" falseName = mkNameG DataName "ghc-prim" "GHC.Types" "False" nothingName, justName :: Name nothingName = mkNameG DataName "base" "Data.Maybe" "Nothing" justName = mkNameG DataName "base" "Data.Maybe" "Just" leftName, rightName :: Name leftName = mkNameG DataName "base" "Data.Either" "Left" rightName = mkNameG DataName "base" "Data.Either" "Right" ----------------------------------------------------- -- Names and uniques ----------------------------------------------------- newtype ModName = ModName String -- Module name deriving (Show,Eq,Ord,Typeable,Data) newtype PkgName = PkgName String -- package name deriving (Show,Eq,Ord,Typeable,Data) -- | Obtained from 'reifyModule' and 'thisModule'. data Module = Module PkgName ModName -- package qualified module name deriving (Show,Eq,Ord,Typeable,Data) newtype OccName = OccName String deriving (Show,Eq,Ord,Typeable,Data) mkModName :: String -> ModName mkModName s = ModName s modString :: ModName -> String modString (ModName m) = m mkPkgName :: String -> PkgName mkPkgName s = PkgName s pkgString :: PkgName -> String pkgString (PkgName m) = m ----------------------------------------------------- -- OccName ----------------------------------------------------- mkOccName :: String -> OccName mkOccName s = OccName s occString :: OccName -> String occString (OccName occ) = occ ----------------------------------------------------- -- Names ----------------------------------------------------- -- -- For "global" names ('NameG') we need a totally unique name, -- so we must include the name-space of the thing -- -- For unique-numbered things ('NameU'), we've got a unique reference -- anyway, so no need for name space -- -- For dynamically bound thing ('NameS') we probably want them to -- in a context-dependent way, so again we don't want the name -- space. For example: -- -- > let v = mkName "T" in [| data $v = $v |] -- -- Here we use the same Name for both type constructor and data constructor -- -- -- NameL and NameG are bound *outside* the TH syntax tree -- either globally (NameG) or locally (NameL). Ex: -- -- > f x = $(h [| (map, x) |]) -- -- The 'map' will be a NameG, and 'x' wil be a NameL -- -- These Names should never appear in a binding position in a TH syntax tree {- $namecapture #namecapture# Much of 'Name' API is concerned with the problem of /name capture/, which can be seen in the following example. > f expr = [| let x = 0 in $expr |] > ... > g x = $( f [| x |] ) > h y = $( f [| y |] ) A naive desugaring of this would yield: > g x = let x = 0 in x > h y = let x = 0 in y All of a sudden, @g@ and @h@ have different meanings! In this case, we say that the @x@ in the RHS of @g@ has been /captured/ by the binding of @x@ in @f@. What we actually want is for the @x@ in @f@ to be distinct from the @x@ in @g@, so we get the following desugaring: > g x = let x' = 0 in x > h y = let x' = 0 in y which avoids name capture as desired. In the general case, we say that a @Name@ can be captured if the thing it refers to can be changed by adding new declarations. -} {- | An abstract type representing names in the syntax tree. 'Name's can be constructed in several ways, which come with different name-capture guarantees (see "Language.Haskell.TH.Syntax#namecapture" for an explanation of name capture): * the built-in syntax @'f@ and @''T@ can be used to construct names, The expression @'f@ gives a @Name@ which refers to the value @f@ currently in scope, and @''T@ gives a @Name@ which refers to the type @T@ currently in scope. These names can never be captured. * 'lookupValueName' and 'lookupTypeName' are similar to @'f@ and @''T@ respectively, but the @Name@s are looked up at the point where the current splice is being run. These names can never be captured. * 'newName' monadically generates a new name, which can never be captured. * 'mkName' generates a capturable name. Names constructed using @newName@ and @mkName@ may be used in bindings (such as @let x = ...@ or @\x -> ...@), but names constructed using @lookupValueName@, @lookupTypeName@, @'f@, @''T@ may not. -} data Name = Name OccName NameFlavour deriving (Typeable, Data) data NameFlavour = NameS -- ^ An unqualified name; dynamically bound | NameQ ModName -- ^ A qualified name; dynamically bound | NameU Int# -- ^ A unique local name | NameL Int# -- ^ Local name bound outside of the TH AST | NameG NameSpace PkgName ModName -- ^ Global name bound outside of the TH AST: -- An original name (occurrences only, not binders) -- Need the namespace too to be sure which -- thing we are naming deriving ( Typeable ) -- | -- Although the NameFlavour type is abstract, the Data instance is not. The reason for this -- is that currently we use Data to serialize values in annotations, and in order for that to -- work for Template Haskell names introduced via the 'x syntax we need gunfold on NameFlavour -- to work. Bleh! -- -- The long term solution to this is to use the binary package for annotation serialization and -- then remove this instance. However, to do _that_ we need to wait on binary to become stable, since -- boot libraries cannot be upgraded separately from GHC itself. -- -- This instance cannot be derived automatically due to bug #2701 instance Data NameFlavour where gfoldl _ z NameS = z NameS gfoldl k z (NameQ mn) = z NameQ `k` mn gfoldl k z (NameU i) = z (\(I# i') -> NameU i') `k` (I# i) gfoldl k z (NameL i) = z (\(I# i') -> NameL i') `k` (I# i) gfoldl k z (NameG ns p m) = z NameG `k` ns `k` p `k` m gunfold k z c = case constrIndex c of 1 -> z NameS 2 -> k $ z NameQ 3 -> k $ z (\(I# i) -> NameU i) 4 -> k $ z (\(I# i) -> NameL i) 5 -> k $ k $ k $ z NameG _ -> error "gunfold: NameFlavour" toConstr NameS = con_NameS toConstr (NameQ _) = con_NameQ toConstr (NameU _) = con_NameU toConstr (NameL _) = con_NameL toConstr (NameG _ _ _) = con_NameG dataTypeOf _ = ty_NameFlavour con_NameS, con_NameQ, con_NameU, con_NameL, con_NameG :: Data.Constr con_NameS = mkConstr ty_NameFlavour "NameS" [] Data.Prefix con_NameQ = mkConstr ty_NameFlavour "NameQ" [] Data.Prefix con_NameU = mkConstr ty_NameFlavour "NameU" [] Data.Prefix con_NameL = mkConstr ty_NameFlavour "NameL" [] Data.Prefix con_NameG = mkConstr ty_NameFlavour "NameG" [] Data.Prefix ty_NameFlavour :: Data.DataType ty_NameFlavour = mkDataType "Language.Haskell.TH.Syntax.NameFlavour" [con_NameS, con_NameQ, con_NameU, con_NameL, con_NameG] data NameSpace = VarName -- ^ Variables | DataName -- ^ Data constructors | TcClsName -- ^ Type constructors and classes; Haskell has them -- in the same name space for now. deriving( Eq, Ord, Data, Typeable ) type Uniq = Int -- | The name without its module prefix nameBase :: Name -> String nameBase (Name occ _) = occString occ -- | Module prefix of a name, if it exists nameModule :: Name -> Maybe String nameModule (Name _ (NameQ m)) = Just (modString m) nameModule (Name _ (NameG _ _ m)) = Just (modString m) nameModule _ = Nothing {- | Generate a capturable name. Occurrences of such names will be resolved according to the Haskell scoping rules at the occurrence site. For example: > f = [| pi + $(varE (mkName "pi")) |] > ... > g = let pi = 3 in $f In this case, @g@ is desugared to > g = Prelude.pi + 3 Note that @mkName@ may be used with qualified names: > mkName "Prelude.pi" See also 'Language.Haskell.TH.Lib.dyn' for a useful combinator. The above example could be rewritten using 'dyn' as > f = [| pi + $(dyn "pi") |] -} mkName :: String -> Name -- The string can have a '.', thus "Foo.baz", -- giving a dynamically-bound qualified name, -- in which case we want to generate a NameQ -- -- Parse the string to see if it has a "." in it -- so we know whether to generate a qualified or unqualified name -- It's a bit tricky because we need to parse -- -- > Foo.Baz.x as Qual Foo.Baz x -- -- So we parse it from back to front mkName str = split [] (reverse str) where split occ [] = Name (mkOccName occ) NameS split occ ('.':rev) | not (null occ) , is_rev_mod_name rev = Name (mkOccName occ) (NameQ (mkModName (reverse rev))) -- The 'not (null occ)' guard ensures that -- mkName "&." = Name "&." NameS -- The 'is_rev_mod' guards ensure that -- mkName ".&" = Name ".&" NameS -- mkName "^.." = Name "^.." NameS -- Trac #8633 -- mkName "Data.Bits..&" = Name ".&" (NameQ "Data.Bits") -- This rather bizarre case actually happened; (.&.) is in Data.Bits split occ (c:rev) = split (c:occ) rev -- Recognises a reversed module name xA.yB.C, -- with at least one component, -- and each component looks like a module name -- (i.e. non-empty, starts with capital, all alpha) is_rev_mod_name rev_mod_str | (compt, rest) <- break (== '.') rev_mod_str , not (null compt), isUpper (last compt), all is_mod_char compt = case rest of [] -> True (_dot : rest') -> is_rev_mod_name rest' | otherwise = False is_mod_char c = isAlphaNum c || c == '_' || c == '\'' -- | Only used internally mkNameU :: String -> Uniq -> Name mkNameU s (I# u) = Name (mkOccName s) (NameU u) -- | Only used internally mkNameL :: String -> Uniq -> Name mkNameL s (I# u) = Name (mkOccName s) (NameL u) -- | Used for 'x etc, but not available to the programmer mkNameG :: NameSpace -> String -> String -> String -> Name mkNameG ns pkg modu occ = Name (mkOccName occ) (NameG ns (mkPkgName pkg) (mkModName modu)) mkNameG_v, mkNameG_tc, mkNameG_d :: String -> String -> String -> Name mkNameG_v = mkNameG VarName mkNameG_tc = mkNameG TcClsName mkNameG_d = mkNameG DataName instance Eq Name where v1 == v2 = cmpEq (v1 `compare` v2) instance Ord Name where (Name o1 f1) `compare` (Name o2 f2) = (f1 `compare` f2) `thenCmp` (o1 `compare` o2) instance Eq NameFlavour where f1 == f2 = cmpEq (f1 `compare` f2) instance Ord NameFlavour where -- NameS < NameQ < NameU < NameL < NameG NameS `compare` NameS = EQ NameS `compare` _ = LT (NameQ _) `compare` NameS = GT (NameQ m1) `compare` (NameQ m2) = m1 `compare` m2 (NameQ _) `compare` _ = LT (NameU _) `compare` NameS = GT (NameU _) `compare` (NameQ _) = GT (NameU u1) `compare` (NameU u2) | isTrue# (u1 <# u2) = LT | isTrue# (u1 ==# u2) = EQ | otherwise = GT (NameU _) `compare` _ = LT (NameL _) `compare` NameS = GT (NameL _) `compare` (NameQ _) = GT (NameL _) `compare` (NameU _) = GT (NameL u1) `compare` (NameL u2) | isTrue# (u1 <# u2) = LT | isTrue# (u1 ==# u2) = EQ | otherwise = GT (NameL _) `compare` _ = LT (NameG ns1 p1 m1) `compare` (NameG ns2 p2 m2) = (ns1 `compare` ns2) `thenCmp` (p1 `compare` p2) `thenCmp` (m1 `compare` m2) (NameG _ _ _) `compare` _ = GT data NameIs = Alone | Applied | Infix showName :: Name -> String showName = showName' Alone showName' :: NameIs -> Name -> String showName' ni nm = case ni of Alone -> nms Applied | pnam -> nms | otherwise -> "(" ++ nms ++ ")" Infix | pnam -> "`" ++ nms ++ "`" | otherwise -> nms where -- For now, we make the NameQ and NameG print the same, even though -- NameQ is a qualified name (so what it means depends on what the -- current scope is), and NameG is an original name (so its meaning -- should be independent of what's in scope. -- We may well want to distinguish them in the end. -- Ditto NameU and NameL nms = case nm of Name occ NameS -> occString occ Name occ (NameQ m) -> modString m ++ "." ++ occString occ Name occ (NameG _ _ m) -> modString m ++ "." ++ occString occ Name occ (NameU u) -> occString occ ++ "_" ++ show (I# u) Name occ (NameL u) -> occString occ ++ "_" ++ show (I# u) pnam = classify nms -- True if we are function style, e.g. f, [], (,) -- False if we are operator style, e.g. +, :+ classify "" = False -- shouldn't happen; . operator is handled below classify (x:xs) | isAlpha x || (x `elem` "_[]()") = case dropWhile (/='.') xs of (_:xs') -> classify xs' [] -> True | otherwise = False instance Show Name where show = showName -- Tuple data and type constructors -- | Tuple data constructor tupleDataName :: Int -> Name -- | Tuple type constructor tupleTypeName :: Int -> Name tupleDataName 0 = mk_tup_name 0 DataName tupleDataName 1 = error "tupleDataName 1" tupleDataName n = mk_tup_name (n-1) DataName tupleTypeName 0 = mk_tup_name 0 TcClsName tupleTypeName 1 = error "tupleTypeName 1" tupleTypeName n = mk_tup_name (n-1) TcClsName mk_tup_name :: Int -> NameSpace -> Name mk_tup_name n_commas space = Name occ (NameG space (mkPkgName "ghc-prim") tup_mod) where occ = mkOccName ('(' : replicate n_commas ',' ++ ")") tup_mod = mkModName "GHC.Tuple" -- Unboxed tuple data and type constructors -- | Unboxed tuple data constructor unboxedTupleDataName :: Int -> Name -- | Unboxed tuple type constructor unboxedTupleTypeName :: Int -> Name unboxedTupleDataName 0 = error "unboxedTupleDataName 0" unboxedTupleDataName 1 = error "unboxedTupleDataName 1" unboxedTupleDataName n = mk_unboxed_tup_name (n-1) DataName unboxedTupleTypeName 0 = error "unboxedTupleTypeName 0" unboxedTupleTypeName 1 = error "unboxedTupleTypeName 1" unboxedTupleTypeName n = mk_unboxed_tup_name (n-1) TcClsName mk_unboxed_tup_name :: Int -> NameSpace -> Name mk_unboxed_tup_name n_commas space = Name occ (NameG space (mkPkgName "ghc-prim") tup_mod) where occ = mkOccName ("(#" ++ replicate n_commas ',' ++ "#)") tup_mod = mkModName "GHC.Tuple" ----------------------------------------------------- -- Locations ----------------------------------------------------- data Loc = Loc { loc_filename :: String , loc_package :: String , loc_module :: String , loc_start :: CharPos , loc_end :: CharPos } type CharPos = (Int, Int) -- ^ Line and character position ----------------------------------------------------- -- -- The Info returned by reification -- ----------------------------------------------------- -- | Obtained from 'reify' in the 'Q' Monad. data Info = -- | A class, with a list of its visible instances ClassI Dec [InstanceDec] -- | A class method | ClassOpI Name Type ParentName Fixity -- | A \"plain\" type constructor. \"Fancier\" type constructors are returned using 'PrimTyConI' or 'FamilyI' as appropriate | TyConI Dec -- | A type or data family, with a list of its visible instances. A closed -- type family is returned with 0 instances. | FamilyI Dec [InstanceDec] -- | A \"primitive\" type constructor, which can't be expressed with a 'Dec'. Examples: @(->)@, @Int#@. | PrimTyConI Name Arity Unlifted -- | A data constructor | DataConI Name Type ParentName Fixity {- | A \"value\" variable (as opposed to a type variable, see 'TyVarI'). The @Maybe Dec@ field contains @Just@ the declaration which defined the variable -- including the RHS of the declaration -- or else @Nothing@, in the case where the RHS is unavailable to the compiler. At present, this value is _always_ @Nothing@: returning the RHS has not yet been implemented because of lack of interest. -} | VarI Name Type (Maybe Dec) Fixity {- | A type variable. The @Type@ field contains the type which underlies the variable. At present, this is always @'VarT' theName@, but future changes may permit refinement of this. -} | TyVarI -- Scoped type variable Name Type -- What it is bound to deriving( Show, Data, Typeable ) -- | Obtained from 'reifyModule' in the 'Q' Monad. data ModuleInfo = -- | Contains the import list of the module. ModuleInfo [Module] deriving( Show, Data, Typeable ) {- | In 'ClassOpI' and 'DataConI', name of the parent class or type -} type ParentName = Name -- | In 'PrimTyConI', arity of the type constructor type Arity = Int -- | In 'PrimTyConI', is the type constructor unlifted? type Unlifted = Bool -- | 'InstanceDec' desribes a single instance of a class or type function. -- It is just a 'Dec', but guaranteed to be one of the following: -- -- * 'InstanceD' (with empty @['Dec']@) -- -- * 'DataInstD' or 'NewtypeInstD' (with empty derived @['Name']@) -- -- * 'TySynInstD' type InstanceDec = Dec data Fixity = Fixity Int FixityDirection deriving( Eq, Show, Data, Typeable ) data FixityDirection = InfixL | InfixR | InfixN deriving( Eq, Show, Data, Typeable ) -- | Highest allowed operator precedence for 'Fixity' constructor (answer: 9) maxPrecedence :: Int maxPrecedence = (9::Int) -- | Default fixity: @infixl 9@ defaultFixity :: Fixity defaultFixity = Fixity maxPrecedence InfixL {- Note [Unresolved infix] ~~~~~~~~~~~~~~~~~~~~~~~ -} {- $infix #infix# When implementing antiquotation for quasiquoters, one often wants to parse strings into expressions: > parse :: String -> Maybe Exp But how should we parse @a + b * c@? If we don't know the fixities of @+@ and @*@, we don't know whether to parse it as @a + (b * c)@ or @(a + b) * c@. In cases like this, use 'UInfixE' or 'UInfixP', which stand for \"unresolved infix expression\" and \"unresolved infix pattern\". When the compiler is given a splice containing a tree of @UInfixE@ applications such as > UInfixE > (UInfixE e1 op1 e2) > op2 > (UInfixE e3 op3 e4) it will look up and the fixities of the relevant operators and reassociate the tree as necessary. * trees will not be reassociated across 'ParensE' or 'ParensP', which are of use for parsing expressions like > (a + b * c) + d * e * 'InfixE' and 'InfixP' expressions are never reassociated. * The 'UInfixE' constructor doesn't support sections. Sections such as @(a *)@ have no ambiguity, so 'InfixE' suffices. For longer sections such as @(a + b * c -)@, use an 'InfixE' constructor for the outer-most section, and use 'UInfixE' constructors for all other operators: > InfixE > Just (UInfixE ...a + b * c...) > op > Nothing Sections such as @(a + b +)@ and @((a + b) +)@ should be rendered into 'Exp's differently: > (+ a + b) ---> InfixE Nothing + (Just $ UInfixE a + b) > -- will result in a fixity error if (+) is left-infix > (+ (a + b)) ---> InfixE Nothing + (Just $ ParensE $ UInfixE a + b) > -- no fixity errors * Quoted expressions such as > [| a * b + c |] :: Q Exp > [p| a : b : c |] :: Q Pat will never contain 'UInfixE', 'UInfixP', 'ParensE', or 'ParensP' constructors. -} ----------------------------------------------------- -- -- The main syntax data types -- ----------------------------------------------------- data Lit = CharL Char | StringL String | IntegerL Integer -- ^ Used for overloaded and non-overloaded -- literals. We don't have a good way to -- represent non-overloaded literals at -- the moment. Maybe that doesn't matter? | RationalL Rational -- Ditto | IntPrimL Integer | WordPrimL Integer | FloatPrimL Rational | DoublePrimL Rational | StringPrimL [Word8] -- ^ A primitive C-style string, type Addr# deriving( Show, Eq, Data, Typeable ) -- We could add Int, Float, Double etc, as we do in HsLit, -- but that could complicate the -- suppposedly-simple TH.Syntax literal type -- | Pattern in Haskell given in @{}@ data Pat = LitP Lit -- ^ @{ 5 or 'c' }@ | VarP Name -- ^ @{ x }@ | TupP [Pat] -- ^ @{ (p1,p2) }@ | UnboxedTupP [Pat] -- ^ @{ (# p1,p2 #) }@ | ConP Name [Pat] -- ^ @data T1 = C1 t1 t2; {C1 p1 p1} = e@ | InfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@ | UInfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@ -- -- See "Language.Haskell.TH.Syntax#infix" | ParensP Pat -- ^ @{(p)}@ -- -- See "Language.Haskell.TH.Syntax#infix" | TildeP Pat -- ^ @{ ~p }@ | BangP Pat -- ^ @{ !p }@ | AsP Name Pat -- ^ @{ x \@ p }@ | WildP -- ^ @{ _ }@ | RecP Name [FieldPat] -- ^ @f (Pt { pointx = x }) = g x@ | ListP [ Pat ] -- ^ @{ [1,2,3] }@ | SigP Pat Type -- ^ @{ p :: t }@ | ViewP Exp Pat -- ^ @{ e -> p }@ deriving( Show, Eq, Data, Typeable ) type FieldPat = (Name,Pat) data Match = Match Pat Body [Dec] -- ^ @case e of { pat -> body where decs }@ deriving( Show, Eq, Data, Typeable ) data Clause = Clause [Pat] Body [Dec] -- ^ @f { p1 p2 = body where decs }@ deriving( Show, Eq, Data, Typeable ) data Exp = VarE Name -- ^ @{ x }@ | ConE Name -- ^ @data T1 = C1 t1 t2; p = {C1} e1 e2 @ | LitE Lit -- ^ @{ 5 or 'c'}@ | AppE Exp Exp -- ^ @{ f x }@ | InfixE (Maybe Exp) Exp (Maybe Exp) -- ^ @{x + y} or {(x+)} or {(+ x)} or {(+)}@ -- It's a bit gruesome to use an Exp as the -- operator, but how else can we distinguish -- constructors from non-constructors? -- Maybe there should be a var-or-con type? -- Or maybe we should leave it to the String itself? | UInfixE Exp Exp Exp -- ^ @{x + y}@ -- -- See "Language.Haskell.TH.Syntax#infix" | ParensE Exp -- ^ @{ (e) }@ -- -- See "Language.Haskell.TH.Syntax#infix" | LamE [Pat] Exp -- ^ @{ \ p1 p2 -> e }@ | LamCaseE [Match] -- ^ @{ \case m1; m2 }@ | TupE [Exp] -- ^ @{ (e1,e2) } @ | UnboxedTupE [Exp] -- ^ @{ (# e1,e2 #) } @ | CondE Exp Exp Exp -- ^ @{ if e1 then e2 else e3 }@ | MultiIfE [(Guard, Exp)] -- ^ @{ if | g1 -> e1 | g2 -> e2 }@ | LetE [Dec] Exp -- ^ @{ let x=e1; y=e2 in e3 }@ | CaseE Exp [Match] -- ^ @{ case e of m1; m2 }@ | DoE [Stmt] -- ^ @{ do { p <- e1; e2 } }@ | CompE [Stmt] -- ^ @{ [ (x,y) | x <- xs, y <- ys ] }@ -- -- The result expression of the comprehension is -- the /last/ of the @'Stmt'@s, and should be a 'NoBindS'. -- -- E.g. translation: -- -- > [ f x | x <- xs ] -- -- > CompE [BindS (VarP x) (VarE xs), NoBindS (AppE (VarE f) (VarE x))] | ArithSeqE Range -- ^ @{ [ 1 ,2 .. 10 ] }@ | ListE [ Exp ] -- ^ @{ [1,2,3] }@ | SigE Exp Type -- ^ @{ e :: t }@ | RecConE Name [FieldExp] -- ^ @{ T { x = y, z = w } }@ | RecUpdE Exp [FieldExp] -- ^ @{ (f x) { z = w } }@ deriving( Show, Eq, Data, Typeable ) type FieldExp = (Name,Exp) -- Omitted: implicit parameters data Body = GuardedB [(Guard,Exp)] -- ^ @f p { | e1 = e2 -- | e3 = e4 } -- where ds@ | NormalB Exp -- ^ @f p { = e } where ds@ deriving( Show, Eq, Data, Typeable ) data Guard = NormalG Exp -- ^ @f x { | odd x } = x@ | PatG [Stmt] -- ^ @f x { | Just y <- x, Just z <- y } = z@ deriving( Show, Eq, Data, Typeable ) data Stmt = BindS Pat Exp | LetS [ Dec ] | NoBindS Exp | ParS [[Stmt]] deriving( Show, Eq, Data, Typeable ) data Range = FromR Exp | FromThenR Exp Exp | FromToR Exp Exp | FromThenToR Exp Exp Exp deriving( Show, Eq, Data, Typeable ) data Dec = FunD Name [Clause] -- ^ @{ f p1 p2 = b where decs }@ | ValD Pat Body [Dec] -- ^ @{ p = b where decs }@ | DataD Cxt Name [TyVarBndr] [Con] [Name] -- ^ @{ data Cxt x => T x = A x | B (T x) -- deriving (Z,W)}@ | NewtypeD Cxt Name [TyVarBndr] Con [Name] -- ^ @{ newtype Cxt x => T x = A (B x) -- deriving (Z,W)}@ | TySynD Name [TyVarBndr] Type -- ^ @{ type T x = (x,x) }@ | ClassD Cxt Name [TyVarBndr] [FunDep] [Dec] -- ^ @{ class Eq a => Ord a where ds }@ | InstanceD Cxt Type [Dec] -- ^ @{ instance Show w => Show [w] -- where ds }@ | SigD Name Type -- ^ @{ length :: [a] -> Int }@ | ForeignD Foreign -- ^ @{ foreign import ... } --{ foreign export ... }@ | InfixD Fixity Name -- ^ @{ infix 3 foo }@ -- | pragmas | PragmaD Pragma -- ^ @{ {\-# INLINE [1] foo #-\} }@ -- | type families (may also appear in [Dec] of 'ClassD' and 'InstanceD') | FamilyD FamFlavour Name [TyVarBndr] (Maybe Kind) -- ^ @{ type family T a b c :: * }@ | DataInstD Cxt Name [Type] [Con] [Name] -- ^ @{ data instance Cxt x => T [x] = A x -- | B (T x) -- deriving (Z,W)}@ | NewtypeInstD Cxt Name [Type] Con [Name] -- ^ @{ newtype instance Cxt x => T [x] = A (B x) -- deriving (Z,W)}@ | TySynInstD Name TySynEqn -- ^ @{ type instance ... }@ | ClosedTypeFamilyD Name [TyVarBndr] (Maybe Kind) [TySynEqn] -- ^ @{ type family F a b :: * where ... }@ | RoleAnnotD Name [Role] -- ^ @{ type role T nominal representational }@ deriving( Show, Eq, Data, Typeable ) -- | One equation of a type family instance or closed type family. The -- arguments are the left-hand-side type patterns and the right-hand-side -- result. data TySynEqn = TySynEqn [Type] Type deriving( Show, Eq, Data, Typeable ) data FunDep = FunDep [Name] [Name] deriving( Show, Eq, Data, Typeable ) data FamFlavour = TypeFam | DataFam deriving( Show, Eq, Data, Typeable ) data Foreign = ImportF Callconv Safety String Name Type | ExportF Callconv String Name Type deriving( Show, Eq, Data, Typeable ) data Callconv = CCall | StdCall deriving( Show, Eq, Data, Typeable ) data Safety = Unsafe | Safe | Interruptible deriving( Show, Eq, Data, Typeable ) data Pragma = InlineP Name Inline RuleMatch Phases | SpecialiseP Name Type (Maybe Inline) Phases | SpecialiseInstP Type | RuleP String [RuleBndr] Exp Exp Phases | AnnP AnnTarget Exp deriving( Show, Eq, Data, Typeable ) data Inline = NoInline | Inline | Inlinable deriving (Show, Eq, Data, Typeable) data RuleMatch = ConLike | FunLike deriving (Show, Eq, Data, Typeable) data Phases = AllPhases | FromPhase Int | BeforePhase Int deriving (Show, Eq, Data, Typeable) data RuleBndr = RuleVar Name | TypedRuleVar Name Type deriving (Show, Eq, Data, Typeable) data AnnTarget = ModuleAnnotation | TypeAnnotation Name | ValueAnnotation Name deriving (Show, Eq, Data, Typeable) type Cxt = [Pred] -- ^ @(Eq a, Ord b)@ -- | Since the advent of @ConstraintKinds@, constraints are really just types. -- Equality constraints use the 'EqualityT' constructor. Constraints may also -- be tuples of other constraints. type Pred = Type data Strict = IsStrict | NotStrict | Unpacked deriving( Show, Eq, Data, Typeable ) data Con = NormalC Name [StrictType] -- ^ @C Int a@ | RecC Name [VarStrictType] -- ^ @C { v :: Int, w :: a }@ | InfixC StrictType Name StrictType -- ^ @Int :+ a@ | ForallC [TyVarBndr] Cxt Con -- ^ @forall a. Eq a => C [a]@ deriving( Show, Eq, Data, Typeable ) type StrictType = (Strict, Type) type VarStrictType = (Name, Strict, Type) data Type = ForallT [TyVarBndr] Cxt Type -- ^ @forall \<vars\>. \<ctxt\> -> \<type\>@ | AppT Type Type -- ^ @T a b@ | SigT Type Kind -- ^ @t :: k@ | VarT Name -- ^ @a@ | ConT Name -- ^ @T@ | PromotedT Name -- ^ @'T@ -- See Note [Representing concrete syntax in types] | TupleT Int -- ^ @(,), (,,), etc.@ | UnboxedTupleT Int -- ^ @(#,#), (#,,#), etc.@ | ArrowT -- ^ @->@ | EqualityT -- ^ @~@ | ListT -- ^ @[]@ | PromotedTupleT Int -- ^ @'(), '(,), '(,,), etc.@ | PromotedNilT -- ^ @'[]@ | PromotedConsT -- ^ @(':)@ | StarT -- ^ @*@ | ConstraintT -- ^ @Constraint@ | LitT TyLit -- ^ @0,1,2, etc.@ deriving( Show, Eq, Data, Typeable ) data TyVarBndr = PlainTV Name -- ^ @a@ | KindedTV Name Kind -- ^ @(a :: k)@ deriving( Show, Eq, Data, Typeable ) data TyLit = NumTyLit Integer -- ^ @2@ | StrTyLit String -- ^ @"Hello"@ deriving ( Show, Eq, Data, Typeable ) -- | Role annotations data Role = NominalR -- ^ @nominal@ | RepresentationalR -- ^ @representational@ | PhantomR -- ^ @phantom@ | InferR -- ^ @_@ deriving( Show, Eq, Data, Typeable ) -- | Annotation target for reifyAnnotations data AnnLookup = AnnLookupModule Module | AnnLookupName Name deriving( Show, Eq, Data, Typeable ) -- | To avoid duplication between kinds and types, they -- are defined to be the same. Naturally, you would never -- have a type be 'StarT' and you would never have a kind -- be 'SigT', but many of the other constructors are shared. -- Note that the kind @Bool@ is denoted with 'ConT', not -- 'PromotedT'. Similarly, tuple kinds are made with 'TupleT', -- not 'PromotedTupleT'. type Kind = Type {- Note [Representing concrete syntax in types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Haskell has a rich concrete syntax for types, including t1 -> t2, (t1,t2), [t], and so on In TH we represent all of this using AppT, with a distinguished type constructor at the head. So, Type TH representation ----------------------------------------------- t1 -> t2 ArrowT `AppT` t2 `AppT` t2 [t] ListT `AppT` t (t1,t2) TupleT 2 `AppT` t1 `AppT` t2 '(t1,t2) PromotedTupleT 2 `AppT` t1 `AppT` t2 But if the original HsSyn used prefix application, we won't use these special TH constructors. For example [] t ConT "[]" `AppT` t (->) t ConT "->" `AppT` t In this way we can faithfully represent in TH whether the original HsType used concrete syntax or not. The one case that doesn't fit this pattern is that of promoted lists '[ Maybe, IO ] PromotedListT 2 `AppT` t1 `AppT` t2 but it's very smelly because there really is no type constructor corresponding to PromotedListT. So we encode HsExplicitListTy with PromotedConsT and PromotedNilT (which *do* have underlying type constructors): '[ Maybe, IO ] PromotedConsT `AppT` Maybe `AppT` (PromotedConsT `AppT` IO `AppT` PromotedNilT) -} ----------------------------------------------------- -- Internal helper functions ----------------------------------------------------- cmpEq :: Ordering -> Bool cmpEq EQ = True cmpEq _ = False thenCmp :: Ordering -> Ordering -> Ordering thenCmp EQ o2 = o2 thenCmp o1 _ = o1
ryantm/ghc
libraries/template-haskell/Language/Haskell/TH/Syntax.hs
bsd-3-clause
49,614
36
14
13,678
8,709
4,791
3,918
622
9
{-+ PrettyM redefines the combinators in Pretty, so that they pass an environment around. This can be used to adust the behaviour of the layout, spacing etc., without parameterising the whole pretty printer. To the user it all appears the same. May be useful to rewrite this as a state transformer, rather than a state reader monad. Could then set different display conditions for subsections of the Parser. See Pretty.lhs for description of the combinators. -} module PrettyM (module PrettyM, module PrettyEnv, P.Mode, P.TextDetails) where import qualified Pretty as P import Data.Ratio import Control.Monad(liftM2,liftM) import MUtils import PrettyEnv -- So that pp code still looks the same -- this means we lose some generality though type Doc = DocM P.Doc -- The pretty printing combinators empty :: Doc empty = return P.empty isEmpty :: Doc -> Bool isEmpty d = P.isEmpty $ unDocM d defaultMode nest :: Int -> Doc -> Doc nest i m = fmap (P.nest i) m classNest, doNest, caseNest, letNest, funNest, dataNest :: Printable a => a -> Doc classNest = nest' classIndent doNest = nest' doIndent caseNest = nest' caseIndent letNest = nest' letIndent funNest = nest' funIndent dataNest = nest' dataIndent nest' p d = do { e <- getPPEnv ; nest (p e) (ppi d) } -- Literals text, ptext :: String -> Doc text = return . P.text ptext = return . P.text char :: Char -> Doc char = return . P.char litChar :: Char -> Doc litChar = return . P.litChar litString :: String -> Doc litString = return . P.litString int :: Int -> Doc int = return . P.int integer :: Integer -> Doc integer = return . P.integer float :: Float -> Doc float = return . P.float double :: Double -> Doc double = return . P.double rational :: Integral a => Ratio a -> Doc rational = return . P.rational -- Simple Combining Forms quotes, charQuotes, backQuotes, doubleQuotes, parens, brackets, curlies, braces :: Printable a => a -> Doc quotes = lift1 P.quotes charQuotes = lift1 P.charQuotes backQuotes = lift1 P.backQuotes doubleQuotes = lift1 P.doubleQuotes parens = lift1 P.parens brackets = lift1 P.brackets curlies = lift1 P.curlies braces = curlies lift1 f d = fmap f (ppi d) -- Constants quote, backQuote, doubleQuote :: Doc quote = return P.quote backQuote = return P.backQuote doubleQuote = return P.doubleQuote semi, comma, colon, space, equals :: Doc semi = return P.semi comma = return P.comma colon = return P.colon space = return P.space equals = return P.equals lparen, rparen, lbrack, rbrack, lcurly, rcurly :: Doc lparen = return P.lparen rparen = return P.rparen lbrack = return P.lbrack rbrack = return P.rbrack lcurly = return P.lcurly rcurly = return P.rcurly -- Combinators (<>), (<+>), ($$), ($+$) :: (Printable a,Printable b) => a -> b -> Doc (<>) = lift2 (P.<>) (<+>) = lift2 (P.<+>) ($$) = lift2 (P.$$) ($+$) = lift2 (P.$+$) lift2 op m1 m2 = liftM2 op (ppi m1) (ppi m2) hcat, hsep, vcat, sep, cat, fsep, fcat :: Printable a => [a] -> Doc hcat = liftList P.hcat hsep = liftList P.hsep vcat = liftList P.vcat sep = liftList P.sep cat = liftList P.cat fsep = liftList P.fsep fcat = liftList P.fcat liftList f ds = fmap f (mapM ppi ds) -- Some More hang :: Doc -> Int -> Doc -> Doc hang dM i rM = do { d <- dM ; r <- rM ; return $ P.hang d i r } -- Yuk, had to cut-n-paste this one from Pretty.hs --punctuate :: Doc -> [Doc] -> [Doc] punctuate p [] = [] punctuate p (d:ds) = go d ds where go d [] = [ppi d] go d (e:es) = (d <> p) : go e es -- this is the equivalent of runM now. renderWithMode :: PPHsMode -> Doc -> String renderWithMode ppMode d = P.render . unDocM d $ ppMode render :: Doc -> String render = renderWithMode defaultMode fullRenderWithMode :: PPHsMode -> P.Mode -> Int -> Float -> (P.TextDetails -> a -> a) -> a -> Doc -> a fullRenderWithMode ppMode m i f fn e mD = P.fullRender m i f fn e $ (unDocM mD) ppMode fullRender :: P.Mode -> Int -> Float -> (P.TextDetails -> a -> a) -> a -> Doc -> a fullRender = fullRenderWithMode defaultMode withPPEnv :: PPHsMode -> Doc -> Doc withPPEnv mode d = return $ (unDocM d) mode updPPEnv f d = do e <- getPPEnv; withPPEnv (f e) d doNotation :: Doc -> Doc doNotation = updPPEnv (\e->e { insideDo = True }) doElseNest d = do e <- getPPEnv if insideDo e then nest (doElseIndent e) (ppi d) else ppi d -- An attempt at intelligent recovery of parentheses in applications (used -- currently only for types). The first time appParens is called, it does not -- parenthesize the given document, but changes the environment to ensure that -- subsequent applications are. {- appParens d = do e <- getPPEnv if insideApp e then parens d else withPPEnv (e { insideApp = True }) d -} -- This sets insideApp to True without adding parens as well. --appParensOn = id --updPPEnv (\e->e { insideApp = True }) -- This sets insideApp to False without adding parens as well. Used when other -- forms serve to parenthesize, e.g., to prevent [(M a)]. --appParensOff = id -- updPPEnv (\e->e { insideApp = False }) -- This is only used for lists where people most commonly put their _own_ -- curlies and semis. It is not intended to recreate correct explicit layout -- for Haskell programs, but merely to allow for pretty printing with curlies -- and semis. It might possibly be extendible into something to create -- explicit layout. {- layout :: [Doc] -> Doc layout [] = empty layout docs = do e <- getPPEnv case layoutType e of PPSemiColon -> let (ds, d) = (init docs, last docs) in lcurly <+> (vcat $ (map (\ d -> d <+> semi) ds) ++ [ d <+> rcurly ]) PPUtrecht -> let (d:ds) = docs in vcat $ (lcurly <+> d) : map (semi <+>) ds ++ [ rcurly ] _ -> vcat docs -- all others done as for classic (for the moment) -} blankline :: Doc -> Doc blankline d = do e <- getPPEnv if spacing e && layoutType e /= PPNoLayout then d $$ space else d ppIfDebug debug = ifM (debugInfo # getPPEnv) (ppi debug) empty ppIfUnicode unicode ascii = ifM (useUnicode # getPPEnv) (ppi unicode) (ppi ascii) withUnicode d = updPPEnv (\e->e{useUnicode=True}) d withDebug d = updPPEnv (\e->e{debugInfo=True}) d -------------------------------------------------------------------------------- {- The Printable class is due to Urban Boquist. We define instances for those types we want to pretty print. It should also make the job of extensiblilty much easier. -} class (Show a{-, Eq a-}) => Printable a where -- pp :: a -> String -- Prettyprint ppi :: a -> Doc -- Prettyprint Intelligently ppiList :: [a] -> Doc -- Specialized for Char/String ppis :: a -> [Doc] -- To allow for cases in which we -- can generate a list of Docs from -- a given type wrap :: a -> Doc -- for bracketing -- pp = render . ppi ppi = text . show ppiList = brackets . ppiFSeq ppis a = [ ppi a ] wrap = parens . ppi pp d = render (ppi d) -- pp used to be a method, but no instance defined it... instance Show Doc where show = render instance Printable Doc where ppi = id ppiSeq :: Printable a => [a] -> Doc ppiSeq = ppiSet comma ppiSet :: Printable a => Doc -> [a] -> Doc ppiSet = ppiSep0 sep ppiSep0 :: Printable a => ([Doc] -> Doc) -> Doc -> [a] -> Doc ppiSep0 sepOp separator [] = empty ppiSep0 sepOp separator [d] = ppi d ppiSep0 sepOp separator ds = sepOp $ punctuate separator $ map ppi ds ppiFSeq :: Printable a => [a] -> Doc ppiFSeq = ppiFSet comma ppiFSet :: Printable a => Doc -> [a] -> Doc ppiFSet = ppiSep0 fsep
kmate/HaRe
old/tools/base/pretty/PrettyM.hs
bsd-3-clause
7,873
10
12
1,952
2,100
1,148
952
146
2
{-# LANGUAGE GeneralizedNewtypeDeriving, ConstraintKinds, PatternGuards, TupleSections #-} module Idris.ParseExpr where import Prelude hiding (pi) import Text.Trifecta.Delta import Text.Trifecta hiding (span, stringLiteral, charLiteral, natural, symbol, char, string, whiteSpace, Err) import Text.Parser.LookAhead import Text.Parser.Expression import qualified Text.Parser.Token as Tok import qualified Text.Parser.Char as Chr import qualified Text.Parser.Token.Highlight as Hi import Idris.AbsSyntax import Idris.ParseHelpers import Idris.ParseOps import Idris.DSL import Idris.Core.TT import Control.Applicative import Control.Monad import Control.Monad.State.Strict import Data.Function (on) import Data.Maybe import qualified Data.List.Split as Spl import Data.List import Data.Monoid import Data.Char import qualified Data.HashSet as HS import qualified Data.Text as T import qualified Data.ByteString.UTF8 as UTF8 import Debug.Trace -- | Allow implicit type declarations allowImp :: SyntaxInfo -> SyntaxInfo allowImp syn = syn { implicitAllowed = True } -- | Disallow implicit type declarations disallowImp :: SyntaxInfo -> SyntaxInfo disallowImp syn = syn { implicitAllowed = False } {-| Parses an expression as a whole @ FullExpr ::= Expr EOF_t; @ -} fullExpr :: SyntaxInfo -> IdrisParser PTerm fullExpr syn = do x <- expr syn eof i <- get return $ debindApp syn (desugar syn i x) tryFullExpr :: SyntaxInfo -> IState -> String -> Either Err PTerm tryFullExpr syn st input = case runparser (fullExpr syn) st "" input of Success tm -> Right tm Failure e -> Left (Msg (show e)) {- | Parses an expression @ Expr ::= Pi @ -} expr :: SyntaxInfo -> IdrisParser PTerm expr = pi {- | Parses an expression with possible operator applied @ OpExpr ::= {- Expression Parser with Operators based on Expr' -}; @ -} opExpr :: SyntaxInfo -> IdrisParser PTerm opExpr syn = do i <- get buildExpressionParser (table (idris_infixes i)) (expr' syn) {- | Parses either an internally defined expression or a user-defined one @ Expr' ::= "External (User-defined) Syntax" | InternalExpr; @ -} expr' :: SyntaxInfo -> IdrisParser PTerm expr' syn = try (externalExpr syn) <|> internalExpr syn <?> "expression" {- | Parses a user-defined expression -} externalExpr :: SyntaxInfo -> IdrisParser PTerm externalExpr syn = do i <- get (FC fn start _) <- getFC expr <- extensions syn (syntaxRulesList $ syntax_rules i) (FC _ _ end) <- getFC let outerFC = FC fn start end return (mapPTermFC (fixFC outerFC) (fixFCH fn outerFC) expr) <?> "user-defined expression" where -- Fix non-highlighting FCs by approximating with the span of the syntax application fixFC outer inner | inner `fcIn` outer = inner | otherwise = outer -- Fix highlighting FCs by making them useless, to avoid spurious highlights fixFCH fn outer inner | inner `fcIn` outer = inner | otherwise = FileFC fn {- | Parses a simple user-defined expression -} simpleExternalExpr :: SyntaxInfo -> IdrisParser PTerm simpleExternalExpr syn = do i <- get extensions syn (filter isSimple (syntaxRulesList $ syntax_rules i)) where isSimple (Rule (Expr x:xs) _ _) = False isSimple (Rule (SimpleExpr x:xs) _ _) = False isSimple (Rule [Keyword _] _ _) = True isSimple (Rule [Symbol _] _ _) = True isSimple (Rule (_:xs) _ _) = case last xs of Keyword _ -> True Symbol _ -> True _ -> False isSimple _ = False {- | Tries to parse a user-defined expression given a list of syntactic extensions -} extensions :: SyntaxInfo -> [Syntax] -> IdrisParser PTerm extensions syn rules = extension syn [] (filter isValid rules) <?> "user-defined expression" where isValid :: Syntax -> Bool isValid (Rule _ _ AnySyntax) = True isValid (Rule _ _ PatternSyntax) = inPattern syn isValid (Rule _ _ TermSyntax) = not (inPattern syn) isValid (DeclRule _ _) = False data SynMatch = SynTm PTerm | SynBind FC Name -- ^ the FC is for highlighting information deriving Show extension :: SyntaxInfo -> [Maybe (Name, SynMatch)] -> [Syntax] -> IdrisParser PTerm extension syn ns rules = choice $ flip map (groupBy (ruleGroup `on` syntaxSymbols) rules) $ \rs -> case head rs of -- can never be [] Rule (symb:_) _ _ -> try $ do n <- extensionSymbol symb extension syn (n : ns) [Rule ss t ctx | (Rule (_:ss) t ctx) <- rs] -- If we have more than one Rule in this bucket, our grammar is -- nondeterministic. Rule [] ptm _ -> return (flatten (updateSynMatch (mapMaybe id ns) ptm)) where ruleGroup [] [] = True ruleGroup (s1:_) (s2:_) = s1 == s2 ruleGroup _ _ = False extensionSymbol :: SSymbol -> IdrisParser (Maybe (Name, SynMatch)) extensionSymbol (Keyword n) = do fc <- reservedFC (show n) highlightP fc AnnKeyword return Nothing extensionSymbol (Expr n) = do tm <- expr syn return $ Just (n, SynTm tm) extensionSymbol (SimpleExpr n) = do tm <- simpleExpr syn return $ Just (n, SynTm tm) extensionSymbol (Binding n) = do (b, fc) <- name return $ Just (n, SynBind fc b) extensionSymbol (Symbol s) = do fc <- symbolFC s highlightP fc AnnKeyword return Nothing flatten :: PTerm -> PTerm -- flatten application flatten (PApp fc (PApp _ f as) bs) = flatten (PApp fc f (as ++ bs)) flatten t = t updateSynMatch = update where updateB :: [(Name, SynMatch)] -> (Name, FC) -> (Name, FC) updateB ns (n, fc) = case lookup n ns of Just (SynBind tfc t) -> (t, tfc) _ -> (n, fc) update :: [(Name, SynMatch)] -> PTerm -> PTerm update ns (PRef fc hls n) = case lookup n ns of Just (SynTm t) -> t _ -> PRef fc hls n update ns (PPatvar fc n) = uncurry (flip PPatvar) $ updateB ns (n, fc) update ns (PLam fc n nfc ty sc) = let (n', nfc') = updateB ns (n, nfc) in PLam fc n' nfc' (update ns ty) (update (dropn n ns) sc) update ns (PPi p n fc ty sc) = let (n', nfc') = updateB ns (n, fc) in PPi (updTacImp ns p) n' nfc' (update ns ty) (update (dropn n ns) sc) update ns (PLet fc n nfc ty val sc) = let (n', nfc') = updateB ns (n, nfc) in PLet fc n' nfc' (update ns ty) (update ns val) (update (dropn n ns) sc) update ns (PApp fc t args) = PApp fc (update ns t) (map (fmap (update ns)) args) update ns (PAppBind fc t args) = PAppBind fc (update ns t) (map (fmap (update ns)) args) update ns (PMatchApp fc n) = let (n', nfc') = updateB ns (n, fc) in PMatchApp nfc' n' update ns (PIfThenElse fc c t f) = PIfThenElse fc (update ns c) (update ns t) (update ns f) update ns (PCase fc c opts) = PCase fc (update ns c) (map (pmap (update ns)) opts) update ns (PRewrite fc eq tm mty) = PRewrite fc (update ns eq) (update ns tm) (fmap (update ns) mty) update ns (PPair fc hls p l r) = PPair fc hls p (update ns l) (update ns r) update ns (PDPair fc hls p l t r) = PDPair fc hls p (update ns l) (update ns t) (update ns r) update ns (PAs fc n t) = PAs fc (fst $ updateB ns (n, NoFC)) (update ns t) update ns (PAlternative ms a as) = PAlternative ms a (map (update ns) as) update ns (PHidden t) = PHidden (update ns t) update ns (PGoal fc r n sc) = PGoal fc (update ns r) n (update ns sc) update ns (PDoBlock ds) = PDoBlock $ map (upd ns) ds where upd :: [(Name, SynMatch)] -> PDo -> PDo upd ns (DoExp fc t) = DoExp fc (update ns t) upd ns (DoBind fc n nfc t) = DoBind fc n nfc (update ns t) upd ns (DoLet fc n nfc ty t) = DoLet fc n nfc (update ns ty) (update ns t) upd ns (DoBindP fc i t ts) = DoBindP fc (update ns i) (update ns t) (map (\(l,r) -> (update ns l, update ns r)) ts) upd ns (DoLetP fc i t) = DoLetP fc (update ns i) (update ns t) update ns (PIdiom fc t) = PIdiom fc $ update ns t update ns (PMetavar fc n) = uncurry (flip PMetavar) $ updateB ns (n, fc) update ns (PProof tacs) = PProof $ map (updTactic ns) tacs update ns (PTactics tacs) = PTactics $ map (updTactic ns) tacs update ns (PDisamb nsps t) = PDisamb nsps $ update ns t update ns (PUnifyLog t) = PUnifyLog $ update ns t update ns (PNoImplicits t) = PNoImplicits $ update ns t update ns (PQuasiquote tm mty) = PQuasiquote (update ns tm) (fmap (update ns) mty) update ns (PUnquote t) = PUnquote $ update ns t update ns (PQuoteName n res fc) = let (n', fc') = (updateB ns (n, fc)) in PQuoteName n' res fc' update ns (PRunElab fc t nsp) = PRunElab fc (update ns t) nsp update ns (PConstSugar fc t) = PConstSugar fc $ update ns t -- PConstSugar probably can't contain anything substitutable, but it's hard to track update ns t = t updTactic :: [(Name, SynMatch)] -> PTactic -> PTactic -- handle all the ones with Names explicitly, then use fmap for the rest with PTerms updTactic ns (Intro ns') = Intro $ map (fst . updateB ns . (, NoFC)) ns' updTactic ns (Focus n) = Focus . fst $ updateB ns (n, NoFC) updTactic ns (Refine n bs) = Refine (fst $ updateB ns (n, NoFC)) bs updTactic ns (Claim n t) = Claim (fst $ updateB ns (n, NoFC)) (update ns t) updTactic ns (MatchRefine n) = MatchRefine (fst $ updateB ns (n, NoFC)) updTactic ns (LetTac n t) = LetTac (fst $ updateB ns (n, NoFC)) (update ns t) updTactic ns (LetTacTy n ty tm) = LetTacTy (fst $ updateB ns (n, NoFC)) (update ns ty) (update ns tm) updTactic ns (ProofSearch rec prover depth top psns hints) = ProofSearch rec prover depth (fmap (fst . updateB ns . (, NoFC)) top) (map (fst . updateB ns . (, NoFC)) psns) (map (fst . updateB ns . (, NoFC)) hints) updTactic ns (Try l r) = Try (updTactic ns l) (updTactic ns r) updTactic ns (TSeq l r) = TSeq (updTactic ns l) (updTactic ns r) updTactic ns (GoalType s tac) = GoalType s $ updTactic ns tac updTactic ns (TDocStr (Left n)) = TDocStr . Left . fst $ updateB ns (n, NoFC) updTactic ns t = fmap (update ns) t updTacImp ns (TacImp o st scr) = TacImp o st (update ns scr) updTacImp _ x = x dropn :: Name -> [(Name, a)] -> [(Name, a)] dropn n [] = [] dropn n ((x,t) : xs) | n == x = xs | otherwise = (x,t):dropn n xs {- | Parses a (normal) built-in expression @ InternalExpr ::= UnifyLog | RecordType | SimpleExpr | Lambda | QuoteGoal | Let | If | RewriteTerm | CaseExpr | DoBlock | App ; @ -} internalExpr :: SyntaxInfo -> IdrisParser PTerm internalExpr syn = unifyLog syn <|> runElab syn <|> disamb syn <|> noImplicits syn <|> recordType syn <|> if_ syn <|> lambda syn <|> quoteGoal syn <|> let_ syn <|> rewriteTerm syn <|> doBlock syn <|> caseExpr syn <|> app syn <?> "expression" {- | Parses the "impossible" keyword @ Impossible ::= 'impossible' @ -} impossible :: IdrisParser PTerm impossible = do fc <- reservedFC "impossible" highlightP fc AnnKeyword return PImpossible {- | Parses a case expression @ CaseExpr ::= 'case' Expr 'of' OpenBlock CaseOption+ CloseBlock; @ -} caseExpr :: SyntaxInfo -> IdrisParser PTerm caseExpr syn = do kw1 <- reservedFC "case"; fc <- getFC scr <- expr syn; kw2 <- reservedFC "of"; opts <- indentedBlock1 (caseOption syn) highlightP kw1 AnnKeyword highlightP kw2 AnnKeyword return (PCase fc scr opts) <?> "case expression" {- | Parses a case in a case expression @ CaseOption ::= Expr (Impossible | '=>' Expr) Terminator ; @ -} caseOption :: SyntaxInfo -> IdrisParser (PTerm, PTerm) caseOption syn = do lhs <- expr (syn { inPattern = True }) r <- impossible <|> symbol "=>" *> expr syn return (lhs, r) <?> "case option" warnTacticDeprecation :: FC -> IdrisParser () warnTacticDeprecation fc = do ist <- get let cmdline = opt_cmdline (idris_options ist) unless (NoOldTacticDeprecationWarnings `elem` cmdline) $ put ist { parserWarnings = (fc, Msg "This style of tactic proof is deprecated. See %runElab for the replacement.") : parserWarnings ist } {- | Parses a proof block @ ProofExpr ::= 'proof' OpenBlock Tactic'* CloseBlock ; @ -} proofExpr :: SyntaxInfo -> IdrisParser PTerm proofExpr syn = do kw <- reservedFC "proof" ts <- indentedBlock1 (tactic syn) highlightP kw AnnKeyword warnTacticDeprecation kw return $ PProof ts <?> "proof block" {- | Parses a tactics block @ TacticsExpr := 'tactics' OpenBlock Tactic'* CloseBlock ; @ -} tacticsExpr :: SyntaxInfo -> IdrisParser PTerm tacticsExpr syn = do kw <- reservedFC "tactics" ts <- indentedBlock1 (tactic syn) highlightP kw AnnKeyword warnTacticDeprecation kw return $ PTactics ts <?> "tactics block" {- | Parses a simple expression @ SimpleExpr ::= {- External (User-defined) Simple Expression -} | '?' Name | % 'instance' | 'Refl' ('{' Expr '}')? | ProofExpr | TacticsExpr | FnName | Idiom | List | Alt | Bracketed | Constant | Type | 'Void' | Quasiquote | NameQuote | Unquote | '_' ; @ -} simpleExpr :: SyntaxInfo -> IdrisParser PTerm simpleExpr syn = try (simpleExternalExpr syn) <|> do (x, FC f (l, c) end) <- try (lchar '?' *> name) return (PMetavar (FC f (l, c-1) end) x) <|> do lchar '%'; fc <- getFC; reserved "instance"; return (PResolveTC fc) <|> do reserved "elim_for"; fc <- getFC; t <- fst <$> fnName; return (PRef fc [] (SN $ ElimN t)) <|> proofExpr syn <|> tacticsExpr syn <|> try (do reserved "Type"; symbol "*"; return $ PUniverse AllTypes) <|> do reserved "AnyType"; return $ PUniverse AllTypes <|> PType <$> reservedFC "Type" <|> do reserved "UniqueType"; return $ PUniverse UniqueType <|> do reserved "NullType"; return $ PUniverse NullType <|> do (c, cfc) <- constant fc <- getFC return (modifyConst syn fc (PConstant cfc c)) <|> do symbol "'"; fc <- getFC; str <- fst <$> name return (PApp fc (PRef fc [] (sUN "Symbol_")) [pexp (PConstant NoFC (Str (show str)))]) <|> do (x, fc) <- fnName if inPattern syn then option (PRef fc [fc] x) (do reservedOp "@" s <- simpleExpr syn fcIn <- getFC return (PAs fcIn x s)) else return (PRef fc [fc] x) <|> idiom syn <|> listExpr syn <|> alt syn <|> do reservedOp "!" s <- simpleExpr syn fc <- getFC return (PAppBind fc s []) <|> bracketed (disallowImp syn) <|> quasiquote syn <|> namequote syn <|> unquote syn <|> do lchar '_'; return Placeholder <?> "expression" {- |Parses an expression in braces @ Bracketed ::= '(' Bracketed' @ -} bracketed :: SyntaxInfo -> IdrisParser PTerm bracketed syn = do (FC fn (sl, sc) _) <- getFC lchar '(' <?> "parenthesized expression" bracketed' (FC fn (sl, sc) (sl, sc+1)) syn {- |Parses the rest of an expression in braces @ Bracketed' ::= ')' | Expr ')' | ExprList ')' | Expr '**' Expr ')' | Operator Expr ')' | Expr Operator ')' | Name ':' Expr '**' Expr ')' ; @ -} bracketed' :: FC -> SyntaxInfo -> IdrisParser PTerm bracketed' open syn = do (FC f start (l, c)) <- getFC lchar ')' return $ PTrue (spanFC open (FC f start (l, c+1))) TypeOrTerm <|> try (do (ln, lnfc) <- name colonFC <- lcharFC ':' lty <- expr syn starsFC <- reservedOpFC "**" fc <- getFC r <- expr syn close <- lcharFC ')' return (PDPair fc [open, colonFC, starsFC, close] TypeOrTerm (PRef lnfc [] ln) lty r)) <|> try (do fc <- getFC; o <- operator; e <- expr syn; lchar ')' -- No prefix operators! (bit of a hack here...) if (o == "-" || o == "!") then fail "minus not allowed in section" else return $ PLam fc (sMN 1000 "ARG") NoFC Placeholder (PApp fc (PRef fc [] (sUN o)) [pexp (PRef fc [] (sMN 1000 "ARG")), pexp e])) <|> try (do l <- simpleExpr syn op <- option Nothing (do o <- operator lchar ')' return (Just o)) fc0 <- getFC case op of Nothing -> bracketedExpr syn open l Just o -> return $ PLam fc0 (sMN 1000 "ARG") NoFC Placeholder (PApp fc0 (PRef fc0 [] (sUN o)) [pexp l, pexp (PRef fc0 [] (sMN 1000 "ARG"))])) <|> do l <- expr syn bracketedExpr syn open l -- | Parse the contents of parentheses, after an expression has been parsed. bracketedExpr :: SyntaxInfo -> FC -> PTerm -> IdrisParser PTerm bracketedExpr syn openParenFC e = do lchar ')'; return e <|> do exprs <- many (do comma <- lcharFC ',' r <- expr syn return (r, comma)) closeParenFC <- lcharFC ')' let hilite = [openParenFC, closeParenFC] ++ map snd exprs return $ PPair openParenFC hilite TypeOrTerm e (mergePairs exprs) <|> do starsFC <- reservedOpFC "**" r <- expr syn closeParenFC <- lcharFC ')' return (PDPair starsFC [openParenFC, starsFC, closeParenFC] TypeOrTerm e Placeholder r) <?> "end of bracketed expression" where mergePairs :: [(PTerm, FC)] -> PTerm mergePairs [(t, fc)] = t mergePairs ((t, fc):rs) = PPair fc [] TypeOrTerm t (mergePairs rs) -- bit of a hack here. If the integer doesn't fit in an Int, treat it as a -- big integer, otherwise try fromInteger and the constants as alternatives. -- a better solution would be to fix fromInteger to work with Integer, as the -- name suggests, rather than Int {-| Finds optimal type for integer constant -} modifyConst :: SyntaxInfo -> FC -> PTerm -> PTerm modifyConst syn fc (PConstant inFC (BI x)) | not (inPattern syn) = PConstSugar inFC $ -- wrap in original location for highlighting PAlternative [] FirstSuccess (PApp fc (PRef fc [] (sUN "fromInteger")) [pexp (PConstant NoFC (BI (fromInteger x)))] : consts) | otherwise = PConstSugar inFC $ PAlternative [] FirstSuccess consts where consts = [ PConstant inFC (BI x) , PConstant inFC (I (fromInteger x)) , PConstant inFC (B8 (fromInteger x)) , PConstant inFC (B16 (fromInteger x)) , PConstant inFC (B32 (fromInteger x)) , PConstant inFC (B64 (fromInteger x)) ] modifyConst syn fc x = x {- | Parses an alternative expression @ Alt ::= '(|' Expr_List '|)'; Expr_List ::= Expr' | Expr' ',' Expr_List ; @ -} alt :: SyntaxInfo -> IdrisParser PTerm alt syn = do symbol "(|"; alts <- sepBy1 (expr' syn) (lchar ','); symbol "|)" return (PAlternative [] FirstSuccess alts) {- | Parses a possibly hidden simple expression @ HSimpleExpr ::= '.' SimpleExpr | SimpleExpr ; @ -} hsimpleExpr :: SyntaxInfo -> IdrisParser PTerm hsimpleExpr syn = do lchar '.' e <- simpleExpr syn return $ PHidden e <|> simpleExpr syn <?> "expression" {- | Parses a unification log expression UnifyLog ::= '%' 'unifyLog' SimpleExpr ; -} unifyLog :: SyntaxInfo -> IdrisParser PTerm unifyLog syn = do (FC fn (sl, sc) kwEnd) <- try (lchar '%' *> reservedFC "unifyLog") tm <- simpleExpr syn highlightP (FC fn (sl, sc-1) kwEnd) AnnKeyword return (PUnifyLog tm) <?> "unification log expression" {- | Parses a new-style tactics expression RunTactics ::= '%' 'runElab' SimpleExpr ; -} runElab :: SyntaxInfo -> IdrisParser PTerm runElab syn = do (FC fn (sl, sc) kwEnd) <- try (lchar '%' *> reservedFC "runElab") fc <- getFC tm <- simpleExpr syn highlightP (FC fn (sl, sc-1) kwEnd) AnnKeyword return $ PRunElab fc tm (syn_namespace syn) <?> "new-style tactics expression" {- | Parses a disambiguation expression Disamb ::= '%' 'disamb' NameList Expr ; -} disamb :: SyntaxInfo -> IdrisParser PTerm disamb syn = do kw <- reservedFC "with" ns <- sepBy1 (fst <$> name) (lchar ',') tm <- expr' syn highlightP kw AnnKeyword return (PDisamb (map tons ns) tm) <?> "namespace disambiguation expression" where tons (NS n s) = txt (show n) : s tons n = [txt (show n)] {- | Parses a no implicits expression @ NoImplicits ::= '%' 'noImplicits' SimpleExpr ; @ -} noImplicits :: SyntaxInfo -> IdrisParser PTerm noImplicits syn = do try (lchar '%' *> reserved "noImplicits") tm <- simpleExpr syn return (PNoImplicits tm) <?> "no implicits expression" {- | Parses a function application expression @ App ::= 'mkForeign' Arg Arg* | MatchApp | SimpleExpr Arg* ; MatchApp ::= SimpleExpr '<==' FnName ; @ -} app :: SyntaxInfo -> IdrisParser PTerm app syn = do f <- simpleExpr syn (do try $ reservedOp "<==" fc <- getFC ff <- fst <$> fnName return (PLet fc (sMN 0 "match") NoFC f (PMatchApp fc ff) (PRef fc [] (sMN 0 "match"))) <?> "matching application expression") <|> (do fc <- getFC i <- get args <- many (do notEndApp; arg syn) case args of [] -> return f _ -> return (flattenFromInt fc f args)) <?> "function application" where -- bit of a hack to deal with the situation where we're applying a -- literal to an argument, which we may want for obscure applications -- of fromInteger, and this will help disambiguate better. -- We know, at least, it won't be one of the constants! flattenFromInt fc (PAlternative _ x alts) args | Just i <- getFromInt alts = PApp fc (PRef fc [] (sUN "fromInteger")) (i : args) flattenFromInt fc f args = PApp fc f args getFromInt ((PApp _ (PRef _ _ n) [a]) : _) | n == sUN "fromInteger" = Just a getFromInt (_ : xs) = getFromInt xs getFromInt _ = Nothing {-| Parses a function argument @ Arg ::= ImplicitArg | ConstraintArg | SimpleExpr ; @ -} arg :: SyntaxInfo -> IdrisParser PArg arg syn = implicitArg syn <|> constraintArg syn <|> do e <- simpleExpr syn return (pexp e) <?> "function argument" {-| Parses an implicit function argument @ ImplicitArg ::= '{' Name ('=' Expr)? '}' ; @ -} implicitArg :: SyntaxInfo -> IdrisParser PArg implicitArg syn = do lchar '{' (n, nfc) <- name fc <- getFC v <- option (PRef nfc [nfc] n) (do lchar '=' expr syn) lchar '}' return (pimp n v True) <?> "implicit function argument" {-| Parses a constraint argument (for selecting a named type class instance) > ConstraintArg ::= > '@{' Expr '}' > ; -} constraintArg :: SyntaxInfo -> IdrisParser PArg constraintArg syn = do symbol "@{" e <- expr syn symbol "}" return (pconst e) <?> "constraint argument" {-| Parses a quasiquote expression (for building reflected terms using the elaborator) > Quasiquote ::= '`(' Expr ')' -} quasiquote :: SyntaxInfo -> IdrisParser PTerm quasiquote syn = do startFC <- symbolFC "`(" e <- expr syn { syn_in_quasiquote = (syn_in_quasiquote syn) + 1 , inPattern = False } g <- optional $ do fc <- symbolFC ":" ty <- expr syn { inPattern = False } -- don't allow antiquotes return (ty, fc) endFC <- symbolFC ")" mapM_ (uncurry highlightP) [(startFC, AnnKeyword), (endFC, AnnKeyword), (spanFC startFC endFC, AnnQuasiquote)] case g of Just (_, fc) -> highlightP fc AnnKeyword _ -> return () return $ PQuasiquote e (fst <$> g) <?> "quasiquotation" {-| Parses an unquoting inside a quasiquotation (for building reflected terms using the elaborator) > Unquote ::= ',' Expr -} unquote :: SyntaxInfo -> IdrisParser PTerm unquote syn = do guard (syn_in_quasiquote syn > 0) startFC <- symbolFC "~" e <- simpleExpr syn { syn_in_quasiquote = syn_in_quasiquote syn - 1 } endFC <- getFC highlightP startFC AnnKeyword highlightP (spanFC startFC endFC) AnnAntiquote return $ PUnquote e <?> "unquotation" {-| Parses a quotation of a name (for using the elaborator to resolve boring details) > NameQuote ::= '`{' Name '}' -} namequote :: SyntaxInfo -> IdrisParser PTerm namequote syn = do (startFC, res) <- try (do fc <- symbolFC "`{{" return (fc, False)) <|> (do fc <- symbolFC "`{" return (fc, True)) (n, nfc) <- fnName endFC <- if res then symbolFC "}" else symbolFC "}}" mapM_ (uncurry highlightP) [ (startFC, AnnKeyword) , (endFC, AnnKeyword) , (spanFC startFC endFC, AnnQuasiquote) ] return $ PQuoteName n res nfc <?> "quoted name" {-| Parses a record field setter expression @ RecordType ::= 'record' '{' FieldTypeList '}'; @ @ FieldTypeList ::= FieldType | FieldType ',' FieldTypeList ; @ @ FieldType ::= FnName '=' Expr ; @ -} recordType :: SyntaxInfo -> IdrisParser PTerm recordType syn = do kw <- reservedFC "record" lchar '{' fgs <- fieldGetOrSet lchar '}' fc <- getFC rec <- optional (simpleExpr syn) highlightP kw AnnKeyword case fgs of Left fields -> case rec of Nothing -> return (PLam fc (sMN 0 "fldx") NoFC Placeholder (applyAll fc fields (PRef fc [] (sMN 0 "fldx")))) Just v -> return (applyAll fc fields v) Right fields -> case rec of Nothing -> return (PLam fc (sMN 0 "fldx") NoFC Placeholder (getAll fc (reverse fields) (PRef fc [] (sMN 0 "fldx")))) Just v -> return (getAll fc (reverse fields) v) <?> "record setting expression" where fieldSet :: IdrisParser ([Name], PTerm) fieldSet = do ns <- fieldGet lchar '=' e <- expr syn return (ns, e) <?> "field setter" fieldGet :: IdrisParser [Name] fieldGet = sepBy1 (fst <$> fnName) (symbol "->") fieldGetOrSet :: IdrisParser (Either [([Name], PTerm)] [Name]) fieldGetOrSet = try (do fs <- sepBy1 fieldSet (lchar ',') return (Left fs)) <|> do f <- fieldGet return (Right f) applyAll :: FC -> [([Name], PTerm)] -> PTerm -> PTerm applyAll fc [] x = x applyAll fc ((ns, e) : es) x = applyAll fc es (doUpdate fc ns e x) doUpdate fc [n] e get = PApp fc (PRef fc [] (mkType n)) [pexp e, pexp get] doUpdate fc (n : ns) e get = PApp fc (PRef fc [] (mkType n)) [pexp (doUpdate fc ns e (PApp fc (PRef fc [] n) [pexp get])), pexp get] getAll :: FC -> [Name] -> PTerm -> PTerm getAll fc [n] e = PApp fc (PRef fc [] n) [pexp e] getAll fc (n:ns) e = PApp fc (PRef fc [] n) [pexp (getAll fc ns e)] -- | Creates setters for record types on necessary functions mkType :: Name -> Name mkType (UN n) = sUN ("set_" ++ str n) mkType (MN 0 n) = sMN 0 ("set_" ++ str n) mkType (NS n s) = NS (mkType n) s {- | Parses a type signature @ TypeSig ::= ':' Expr ; @ @ TypeExpr ::= ConstraintList? Expr; @ -} typeExpr :: SyntaxInfo -> IdrisParser PTerm typeExpr syn = do cs <- if implicitAllowed syn then constraintList syn else return [] sc <- expr syn return (bindList (PPi constraint) cs sc) <?> "type signature" {- | Parses a lambda expression @ Lambda ::= '\\' TypeOptDeclList LambdaTail | '\\' SimpleExprList LambdaTail ; @ @ SimpleExprList ::= SimpleExpr | SimpleExpr ',' SimpleExprList ; @ @ LambdaTail ::= Impossible | '=>' Expr @ -} lambda :: SyntaxInfo -> IdrisParser PTerm lambda syn = do lchar '\\' <?> "lambda expression" ((do xt <- try $ tyOptDeclList syn fc <- getFC sc <- lambdaTail return (bindList (PLam fc) xt sc)) <|> (do ps <- sepBy (do fc <- getFC e <- simpleExpr (syn { inPattern = True }) return (fc, e)) (lchar ',') sc <- lambdaTail return (pmList (zip [0..] ps) sc))) <?> "lambda expression" where pmList :: [(Int, (FC, PTerm))] -> PTerm -> PTerm pmList [] sc = sc pmList ((i, (fc, x)) : xs) sc = PLam fc (sMN i "lamp") NoFC Placeholder (PCase fc (PRef fc [] (sMN i "lamp")) [(x, pmList xs sc)]) lambdaTail :: IdrisParser PTerm lambdaTail = impossible <|> symbol "=>" *> expr syn {- | Parses a term rewrite expression @ RewriteTerm ::= 'rewrite' Expr ('==>' Expr)? 'in' Expr ; @ -} rewriteTerm :: SyntaxInfo -> IdrisParser PTerm rewriteTerm syn = do kw <- reservedFC "rewrite" fc <- getFC prf <- expr syn giving <- optional (do symbol "==>"; expr' syn) kw' <- reservedFC "in"; sc <- expr syn highlightP kw AnnKeyword highlightP kw' AnnKeyword return (PRewrite fc (PApp fc (PRef fc [] (sUN "sym")) [pexp prf]) sc giving) <?> "term rewrite expression" {- |Parses a let binding @ Let ::= 'let' Name TypeSig'? '=' Expr 'in' Expr | 'let' Expr' '=' Expr' 'in' Expr TypeSig' ::= ':' Expr' ; @ -} let_ :: SyntaxInfo -> IdrisParser PTerm let_ syn = try (do kw <- reservedFC "let" ls <- indentedBlock (let_binding syn) kw' <- reservedFC "in"; sc <- expr syn highlightP kw AnnKeyword; highlightP kw' AnnKeyword return (buildLets ls sc)) <?> "let binding" where buildLets [] sc = sc buildLets ((fc, PRef nfc _ n, ty, v, []) : ls) sc = PLet fc n nfc ty v (buildLets ls sc) buildLets ((fc, pat, ty, v, alts) : ls) sc = PCase fc v ((pat, buildLets ls sc) : alts) let_binding syn = do fc <- getFC; pat <- expr' (syn { inPattern = True }) ty <- option Placeholder (do lchar ':'; expr' syn) lchar '=' v <- expr syn ts <- option [] (do lchar '|' sepBy1 (do_alt syn) (lchar '|')) return (fc,pat,ty,v,ts) {- | Parses a conditional expression @ If ::= 'if' Expr 'then' Expr 'else' Expr @ -} if_ :: SyntaxInfo -> IdrisParser PTerm if_ syn = (do ifFC <- reservedFC "if" fc <- getFC c <- expr syn thenFC <- reservedFC "then" t <- expr syn elseFC <- reservedFC "else" f <- expr syn mapM_ (flip highlightP AnnKeyword) [ifFC, thenFC, elseFC] return (PIfThenElse fc c t f)) <?> "conditional expression" {- | Parses a quote goal @ QuoteGoal ::= 'quoteGoal' Name 'by' Expr 'in' Expr ; @ -} quoteGoal :: SyntaxInfo -> IdrisParser PTerm quoteGoal syn = do kw1 <- reservedFC "quoteGoal"; n <- fst <$> name; kw2 <- reservedFC "by" r <- expr syn kw3 <- reservedFC "in" fc <- getFC sc <- expr syn mapM_ (flip highlightP AnnKeyword) [kw1, kw2, kw3] return (PGoal fc r n sc) <?> "quote goal expression" {- | Parses a dependent type signature @ Pi ::= PiOpts Static? Pi' @ @ Pi' ::= OpExpr ('->' Pi)? | '(' TypeDeclList ')' '->' Pi | '{' TypeDeclList '}' '->' Pi | '{' 'auto' TypeDeclList '}' '->' Pi | '{' 'default' SimpleExpr TypeDeclList '}' '->' Pi ; @ -} bindsymbol opts st syn = do symbol "->" return (Exp opts st False) explicitPi opts st syn = do xt <- try (lchar '(' *> typeDeclList syn <* lchar ')') binder <- bindsymbol opts st syn sc <- expr syn return (bindList (PPi binder) xt sc) autoImplicit opts st syn = do kw <- reservedFC "auto" when (st == Static) $ fail "auto implicits can not be static" xt <- typeDeclList syn lchar '}' symbol "->" sc <- expr syn highlightP kw AnnKeyword return (bindList (PPi (TacImp [] Dynamic (PTactics [ProofSearch True True 100 Nothing [] []]))) xt sc) defaultImplicit opts st syn = do kw <- reservedFC "default" when (st == Static) $ fail "default implicits can not be static" ist <- get script' <- simpleExpr syn let script = debindApp syn . desugar syn ist $ script' xt <- typeDeclList syn lchar '}' symbol "->" sc <- expr syn highlightP kw AnnKeyword return (bindList (PPi (TacImp [] Dynamic script)) xt sc) normalImplicit opts st syn = do xt <- typeDeclList syn <* lchar '}' symbol "->" cs <- constraintList syn sc <- expr syn let (im,cl) = if implicitAllowed syn then (Imp opts st False (Just (Impl False True)), constraint) else (Imp opts st False (Just (Impl False False)), Imp opts st False (Just (Impl True False))) return (bindList (PPi im) xt (bindList (PPi cl) cs sc)) implicitPi opts st syn = autoImplicit opts st syn <|> defaultImplicit opts st syn <|> normalImplicit opts st syn unboundPi opts st syn = do x <- opExpr syn (do binder <- bindsymbol opts st syn sc <- expr syn return (PPi binder (sUN "__pi_arg") NoFC x sc)) <|> return x pi :: SyntaxInfo -> IdrisParser PTerm pi syn = do opts <- piOpts syn st <- static explicitPi opts st syn <|> try (do lchar '{'; implicitPi opts st syn) <|> unboundPi opts st syn <?> "dependent type signature" {- | Parses Possible Options for Pi Expressions @ PiOpts ::= '.'? @ -} piOpts :: SyntaxInfo -> IdrisParser [ArgOpt] piOpts syn | implicitAllowed syn = lchar '.' *> return [InaccessibleArg] <|> return [] piOpts syn = return [] {- | Parses a type constraint list @ ConstraintList ::= '(' Expr_List ')' '=>' | Expr '=>' ; @ -} constraintList :: SyntaxInfo -> IdrisParser [(Name, FC, PTerm)] constraintList syn = try (constraintList1 syn) <|> return [] constraintList1 :: SyntaxInfo -> IdrisParser [(Name, FC, PTerm)] constraintList1 syn = try (do lchar '(' tys <- sepBy1 nexpr (lchar ',') lchar ')' reservedOp "=>" return tys) <|> try (do t <- opExpr (disallowImp syn) reservedOp "=>" return [(defname, NoFC, t)]) <?> "type constraint list" where nexpr = try (do (n, fc) <- name; lchar ':' e <- expr syn return (n, fc, e)) <|> do e <- expr syn return (defname, NoFC, e) defname = sMN 0 "constrarg" {- | Parses a type declaration list @ TypeDeclList ::= FunctionSignatureList | NameList TypeSig ; @ @ FunctionSignatureList ::= Name TypeSig | Name TypeSig ',' FunctionSignatureList ; @ -} typeDeclList :: SyntaxInfo -> IdrisParser [(Name, FC, PTerm)] typeDeclList syn = try (sepBy1 (do (x, xfc) <- fnName lchar ':' t <- typeExpr (disallowImp syn) return (x, xfc, t)) (lchar ',')) <|> do ns <- sepBy1 name (lchar ',') lchar ':' t <- typeExpr (disallowImp syn) return (map (\(x, xfc) -> (x, xfc, t)) ns) <?> "type declaration list" {- | Parses a type declaration list with optional parameters @ TypeOptDeclList ::= NameOrPlaceholder TypeSig? | NameOrPlaceholder TypeSig? ',' TypeOptDeclList ; @ @ NameOrPlaceHolder ::= Name | '_'; @ -} tyOptDeclList :: SyntaxInfo -> IdrisParser [(Name, FC, PTerm)] tyOptDeclList syn = sepBy1 (do (x, fc) <- nameOrPlaceholder t <- option Placeholder (do lchar ':' expr syn) return (x, fc, t)) (lchar ',') <?> "type declaration list" where nameOrPlaceholder :: IdrisParser (Name, FC) nameOrPlaceholder = fnName <|> do symbol "_" return (sMN 0 "underscore", NoFC) <?> "name or placeholder" {- | Parses a list literal expression e.g. [1,2,3] or a comprehension [ (x, y) | x <- xs , y <- ys ] @ ListExpr ::= '[' ']' | '[' Expr '|' DoList ']' | '[' ExprList ']' ; @ @ DoList ::= Do | Do ',' DoList ; @ @ ExprList ::= Expr | Expr ',' ExprList ; @ -} listExpr :: SyntaxInfo -> IdrisParser PTerm listExpr syn = do (FC f (l, c) _) <- getFC lchar '['; fc <- getFC; (try . token $ do (char ']' <?> "end of list expression") (FC _ _ (l', c')) <- getFC return (mkNil (FC f (l, c) (l', c')))) <|> (do x <- expr syn <?> "expression" (do try (lchar '|') <?> "list comprehension" qs <- sepBy1 (do_ syn) (lchar ',') lchar ']' return (PDoBlock (map addGuard qs ++ [DoExp fc (PApp fc (PRef fc [] (sUN "return")) [pexp x])]))) <|> (do xs <- many (do (FC fn (sl, sc) _) <- getFC lchar ',' <?> "list element" let commaFC = FC fn (sl, sc) (sl, sc + 1) elt <- expr syn return (elt, commaFC)) (FC fn (sl, sc) _) <- getFC lchar ']' <?> "end of list expression" let rbrackFC = FC fn (sl, sc) (sl, sc+1) return (mkList fc rbrackFC ((x, (FC f (l, c) (l, c+1))) : xs)))) <?> "list expression" where mkNil :: FC -> PTerm mkNil fc = PRef fc [fc] (sUN "Nil") mkList :: FC -> FC -> [(PTerm, FC)] -> PTerm mkList errFC nilFC [] = PRef nilFC [nilFC] (sUN "Nil") mkList errFC nilFC ((x, fc) : xs) = PApp errFC (PRef fc [fc] (sUN "::")) [pexp x, pexp (mkList errFC nilFC xs)] addGuard :: PDo -> PDo addGuard (DoExp fc e) = DoExp fc (PApp fc (PRef fc [] (sUN "guard")) [pexp e]) addGuard x = x {- | Parses a do-block @ Do' ::= Do KeepTerminator; @ @ DoBlock ::= 'do' OpenBlock Do'+ CloseBlock ; @ -} doBlock :: SyntaxInfo -> IdrisParser PTerm doBlock syn = do kw <- reservedFC "do" ds <- indentedBlock1 (do_ syn) highlightP kw AnnKeyword return (PDoBlock ds) <?> "do block" {- | Parses an expression inside a do block @ Do ::= 'let' Name TypeSig'? '=' Expr | 'let' Expr' '=' Expr | Name '<-' Expr | Expr' '<-' Expr | Expr ; @ -} do_ :: SyntaxInfo -> IdrisParser PDo do_ syn = try (do kw <- reservedFC "let" (i, ifc) <- name ty <- option Placeholder (do lchar ':' expr' syn) reservedOp "=" fc <- getFC e <- expr syn highlightP kw AnnKeyword return (DoLet fc i ifc ty e)) <|> try (do kw <- reservedFC "let" i <- expr' syn reservedOp "=" fc <- getFC sc <- expr syn highlightP kw AnnKeyword return (DoLetP fc i sc)) <|> try (do (i, ifc) <- name symbol "<-" fc <- getFC e <- expr syn; option (DoBind fc i ifc e) (do lchar '|' ts <- sepBy1 (do_alt syn) (lchar '|') return (DoBindP fc (PRef ifc [ifc] i) e ts))) <|> try (do i <- expr' syn symbol "<-" fc <- getFC e <- expr syn; option (DoBindP fc i e []) (do lchar '|' ts <- sepBy1 (do_alt syn) (lchar '|') return (DoBindP fc i e ts))) <|> do e <- expr syn fc <- getFC return (DoExp fc e) <?> "do block expression" do_alt syn = do l <- expr' syn option (Placeholder, l) (do symbol "=>" r <- expr' syn return (l, r)) {- | Parses an expression in idiom brackets @ Idiom ::= '[|' Expr '|]'; @ -} idiom :: SyntaxInfo -> IdrisParser PTerm idiom syn = do symbol "[|" fc <- getFC e <- expr syn symbol "|]" return (PIdiom fc e) <?> "expression in idiom brackets" {- |Parses a constant or literal expression @ Constant ::= 'Integer' | 'Int' | 'Char' | 'Double' | 'String' | 'Bits8' | 'Bits16' | 'Bits32' | 'Bits64' | Float_t | Natural_t | VerbatimString_t | String_t | Char_t ; @ -} constants :: [(String, Idris.Core.TT.Const)] constants = [ ("Integer", AType (ATInt ITBig)) , ("Int", AType (ATInt ITNative)) , ("Char", AType (ATInt ITChar)) , ("Double", AType ATFloat) , ("String", StrType) , ("prim__WorldType", WorldType) , ("prim__TheWorld", TheWorld) , ("Bits8", AType (ATInt (ITFixed IT8))) , ("Bits16", AType (ATInt (ITFixed IT16))) , ("Bits32", AType (ATInt (ITFixed IT32))) , ("Bits64", AType (ATInt (ITFixed IT64))) ] -- | Parse a constant and its source span constant :: IdrisParser (Idris.Core.TT.Const, FC) constant = choice [ do fc <- reservedFC name; return (ty, fc) | (name, ty) <- constants ] <|> do (f, fc) <- try float; return (Fl f, fc) <|> do (i, fc) <- natural; return (BI i, fc) <|> do (s, fc) <- verbatimStringLiteral; return (Str s, fc) <|> do (s, fc) <- stringLiteral; return (Str s, fc) <|> do (c, fc) <- try charLiteral; return (Ch c, fc) --Currently ambigous with symbols <?> "constant or literal" {- | Parses a verbatim multi-line string literal (triple-quoted) @ VerbatimString_t ::= '\"\"\"' ~'\"\"\"' '\"\"\"' ; @ -} verbatimStringLiteral :: MonadicParsing m => m (String, FC) verbatimStringLiteral = token $ do (FC f start _) <- getFC try $ string "\"\"\"" str <- manyTill anyChar $ try (string "\"\"\"") (FC _ _ end) <- getFC return (str, FC f start end) {- | Parses a static modifier @ Static ::= '[' static ']' ; @ -} static :: IdrisParser Static static = do reserved "[static]"; return Static <|> return Dynamic <?> "static modifier" {- | Parses a tactic script @ Tactic ::= 'intro' NameList? | 'intros' | 'refine' Name Imp+ | 'mrefine' Name | 'rewrite' Expr | 'induction' Expr | 'equiv' Expr | 'let' Name ':' Expr' '=' Expr | 'let' Name '=' Expr | 'focus' Name | 'exact' Expr | 'applyTactic' Expr | 'reflect' Expr | 'fill' Expr | 'try' Tactic '|' Tactic | '{' TacticSeq '}' | 'compute' | 'trivial' | 'solve' | 'attack' | 'state' | 'term' | 'undo' | 'qed' | 'abandon' | ':' 'q' ; Imp ::= '?' | '_'; TacticSeq ::= Tactic ';' Tactic | Tactic ';' TacticSeq ; @ -} -- | A specification of the arguments that tactics can take data TacticArg = NameTArg -- ^ Names: n1, n2, n3, ... n | ExprTArg | AltsTArg | StringLitTArg -- The FIXMEs are Issue #1766 in the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1766 -- | A list of available tactics and their argument requirements tactics :: [([String], Maybe TacticArg, SyntaxInfo -> IdrisParser PTactic)] tactics = [ (["intro"], Nothing, const $ -- FIXME syntax for intro (fresh name) do ns <- sepBy (spaced (fst <$> name)) (lchar ','); return $ Intro ns) , noArgs ["intros"] Intros , noArgs ["unfocus"] Unfocus , (["refine"], Just ExprTArg, const $ do n <- spaced (fst <$> fnName) imps <- many imp return $ Refine n imps) , (["claim"], Nothing, \syn -> do n <- indentPropHolds gtProp *> (fst <$> name) goal <- indentPropHolds gtProp *> expr syn return $ Claim n goal) , (["mrefine"], Just ExprTArg, const $ do n <- spaced (fst <$> fnName) return $ MatchRefine n) , expressionTactic ["rewrite"] Rewrite , expressionTactic ["case"] CaseTac , expressionTactic ["induction"] Induction , expressionTactic ["equiv"] Equiv , (["let"], Nothing, \syn -> -- FIXME syntax for let do n <- (indentPropHolds gtProp *> (fst <$> name)) (do indentPropHolds gtProp *> lchar ':' ty <- indentPropHolds gtProp *> expr' syn indentPropHolds gtProp *> lchar '=' t <- indentPropHolds gtProp *> expr syn i <- get return $ LetTacTy n (desugar syn i ty) (desugar syn i t)) <|> (do indentPropHolds gtProp *> lchar '=' t <- indentPropHolds gtProp *> expr syn i <- get return $ LetTac n (desugar syn i t))) , (["focus"], Just ExprTArg, const $ do n <- spaced (fst <$> name) return $ Focus n) , expressionTactic ["exact"] Exact , expressionTactic ["applyTactic"] ApplyTactic , expressionTactic ["byReflection"] ByReflection , expressionTactic ["reflect"] Reflect , expressionTactic ["fill"] Fill , (["try"], Just AltsTArg, \syn -> do t <- spaced (tactic syn) lchar '|' t1 <- spaced (tactic syn) return $ Try t t1) , noArgs ["compute"] Compute , noArgs ["trivial"] Trivial , noArgs ["unify"] DoUnify , (["search"], Nothing, const $ do depth <- option 10 $ fst <$> natural return (ProofSearch True True (fromInteger depth) Nothing [] [])) , noArgs ["instance"] TCInstance , noArgs ["solve"] Solve , noArgs ["attack"] Attack , noArgs ["state", ":state"] ProofState , noArgs ["term", ":term"] ProofTerm , noArgs ["undo", ":undo"] Undo , noArgs ["qed", ":qed"] Qed , noArgs ["abandon", ":q"] Abandon , noArgs ["skip"] Skip , noArgs ["sourceLocation"] SourceFC , expressionTactic [":e", ":eval"] TEval , expressionTactic [":t", ":type"] TCheck , expressionTactic [":search"] TSearch , (["fail"], Just StringLitTArg, const $ do msg <- fst <$> stringLiteral return $ TFail [Idris.Core.TT.TextPart msg]) , ([":doc"], Just ExprTArg, const $ do whiteSpace doc <- (Right . fst <$> constant) <|> (Left . fst <$> fnName) eof return (TDocStr doc)) ] where expressionTactic names tactic = (names, Just ExprTArg, \syn -> do t <- spaced (expr syn) i <- get return $ tactic (desugar syn i t)) noArgs names tactic = (names, Nothing, const (return tactic)) spaced parser = indentPropHolds gtProp *> parser imp :: IdrisParser Bool imp = do lchar '?'; return False <|> do lchar '_'; return True tactic :: SyntaxInfo -> IdrisParser PTactic tactic syn = choice [ do choice (map reserved names); parser syn | (names, _, parser) <- tactics ] <|> do lchar '{' t <- tactic syn; lchar ';'; ts <- sepBy1 (tactic syn) (lchar ';') lchar '}' return $ TSeq t (mergeSeq ts) <|> ((lchar ':' >> empty) <?> "prover command") <?> "tactic" where mergeSeq :: [PTactic] -> PTactic mergeSeq [t] = t mergeSeq (t:ts) = TSeq t (mergeSeq ts) -- | Parses a tactic as a whole fullTactic :: SyntaxInfo -> IdrisParser PTactic fullTactic syn = do t <- tactic syn eof return t
mrmonday/Idris-dev
src/Idris/ParseExpr.hs
bsd-3-clause
52,608
1
37
19,383
15,979
7,843
8,136
-1
-1
{-# LANGUAGE CPP #-} -- ---------------------------------------------------------------------------- -- | Pretty print helpers for the LLVM Code generator. -- module LlvmCodeGen.Ppr ( pprLlvmHeader, pprLlvmCmmDecl, pprLlvmData, infoSection ) where #include "HsVersions.h" import Llvm import LlvmCodeGen.Base import LlvmCodeGen.Data import CLabel import Cmm import Platform import FastString import Outputable import Unique -- ---------------------------------------------------------------------------- -- * Top level -- -- | Header code for LLVM modules pprLlvmHeader :: SDoc pprLlvmHeader = moduleLayout -- | LLVM module layout description for the host target moduleLayout :: SDoc moduleLayout = sdocWithPlatform $ \platform -> case platform of Platform { platformArch = ArchX86, platformOS = OSDarwin } -> text "target datalayout = \"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-a0:0:64-f80:128:128-n8:16:32\"" $+$ text "target triple = \"i386-apple-darwin9.8\"" Platform { platformArch = ArchX86, platformOS = OSMinGW32 } -> text "target datalayout = \"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-f80:128:128-v64:64:64-v128:128:128-a0:0:64-f80:32:32-n8:16:32\"" $+$ text "target triple = \"i686-pc-win32\"" Platform { platformArch = ArchX86, platformOS = OSLinux } -> text "target datalayout = \"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-a0:0:64-f80:32:32-n8:16:32\"" $+$ text "target triple = \"i386-pc-linux-gnu\"" Platform { platformArch = ArchX86_64, platformOS = OSDarwin } -> text "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64\"" $+$ text "target triple = \"x86_64-apple-darwin10.0.0\"" Platform { platformArch = ArchX86_64, platformOS = OSLinux } -> text "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64\"" $+$ text "target triple = \"x86_64-linux-gnu\"" Platform { platformArch = ArchARM {}, platformOS = OSLinux } -> text "target datalayout = \"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:64:128-a0:0:64-n32\"" $+$ text "target triple = \"armv6-unknown-linux-gnueabihf\"" Platform { platformArch = ArchARM {}, platformOS = OSAndroid } -> text "target datalayout = \"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:64:128-a0:0:64-n32\"" $+$ text "target triple = \"arm-unknown-linux-androideabi\"" Platform { platformArch = ArchARM {}, platformOS = OSQNXNTO } -> text "target datalayout = \"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:64:128-a0:0:64-n32\"" $+$ text "target triple = \"arm-unknown-nto-qnx8.0.0eabi\"" Platform { platformArch = ArchARM {}, platformOS = OSiOS } -> text "target datalayout = \"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:64:128-a0:0:64-n32\"" $+$ text "target triple = \"arm-apple-darwin10\"" Platform { platformArch = ArchX86, platformOS = OSiOS } -> text "target datalayout = \"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-a0:0:64-f80:128:128-n8:16:32\"" $+$ text "target triple = \"i386-apple-darwin11\"" Platform { platformArch = ArchARM64, platformOS = OSiOS } -> text "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-n32:64-S128\"" $+$ text "target triple = \"arm64-apple-ios7.0.0\"" Platform { platformArch = ArchARM64, platformOS = OSLinux } -> text "target datalayout = \"e-m:e-i64:64-i128:128-n32:64-S128\"" $+$ text "target triple = \"aarch64-unknown-linux-gnu\"" _ -> if platformIsCrossCompiling platform then panic "LlvmCodeGen.Ppr: Cross compiling without valid target info." else empty -- If you see the above panic, GHC is missing the required target datalayout -- and triple information. You can obtain this info by compiling a simple -- 'hello world' C program with the clang C compiler eg: -- clang hello.c -emit-llvm -o hello.ll -- and the first two lines of hello.ll should provide the 'target datalayout' -- and 'target triple' lines required. -- | Pretty print LLVM data code pprLlvmData :: LlvmData -> SDoc pprLlvmData (globals, types) = let ppLlvmTys (LMAlias a) = ppLlvmAlias a ppLlvmTys (LMFunction f) = ppLlvmFunctionDecl f ppLlvmTys _other = empty types' = vcat $ map ppLlvmTys types globals' = ppLlvmGlobals globals in types' $+$ globals' -- | Pretty print LLVM code pprLlvmCmmDecl :: LlvmCmmDecl -> LlvmM (SDoc, [LlvmVar]) pprLlvmCmmDecl (CmmData _ lmdata) = return (vcat $ map pprLlvmData lmdata, []) pprLlvmCmmDecl (CmmProc mb_info entry_lbl live (ListGraph blks)) = do let lbl = case mb_info of Nothing -> entry_lbl Just (Statics info_lbl _) -> info_lbl link = if externallyVisibleCLabel lbl then ExternallyVisible else Internal lmblocks = map (\(BasicBlock id stmts) -> LlvmBlock (getUnique id) stmts) blks funDec <- llvmFunSig live lbl link dflags <- getDynFlags let buildArg = fsLit . showSDoc dflags . ppPlainName funArgs = map buildArg (llvmFunArgs dflags live) funSect = llvmFunSection dflags (decName funDec) -- generate the info table prefix <- case mb_info of Nothing -> return Nothing Just (Statics _ statics) -> do infoStatics <- mapM genData statics let infoTy = LMStruct $ map getStatType infoStatics return $ Just $ LMStaticStruc infoStatics infoTy let fun = LlvmFunction funDec funArgs llvmStdFunAttrs funSect prefix lmblocks name = decName $ funcDecl fun defName = name `appendFS` fsLit "$def" funcDecl' = (funcDecl fun) { decName = defName } fun' = fun { funcDecl = funcDecl' } funTy = LMFunction funcDecl' funVar = LMGlobalVar name (LMPointer funTy) link Nothing Nothing Alias defVar = LMGlobalVar defName (LMPointer funTy) (funcLinkage funcDecl') (funcSect fun) (funcAlign funcDecl') Alias alias = LMGlobal funVar (Just $ LMBitc (LMStaticPointer defVar) (LMPointer $ LMInt 8)) return (ppLlvmGlobal alias $+$ ppLlvmFunction fun', []) -- | The section we are putting info tables and their entry code into, should -- be unique since we process the assembly pattern matching this. infoSection :: String infoSection = "X98A__STRIP,__me"
tjakway/ghcjvm
compiler/llvmGen/LlvmCodeGen/Ppr.hs
bsd-3-clause
7,704
0
17
2,003
1,166
607
559
113
14
module Test (R(..)) where data R = R { x :: Char, y :: Int, z :: Float } | S { x :: Char } | T { y :: Int, z:: Float } | W
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/ghci/scripts/T4015.hs
bsd-3-clause
148
0
8
62
71
46
25
5
0
module Oden.Compiler where import Oden.Predefined import Oden.Environment import Oden.Core.Monomorphed import Oden.Core.Typed import Oden.Compiler.Environment import Oden.Compiler.Monomorphization import Control.Arrow data CompilationError = MonomorphError MonomorphError deriving (Show, Eq, Ord) environmentFromPackage :: TypedPackage -> CompileEnvironment environmentFromPackage pkg@(TypedPackage _ imports _) = fromPackage universe `merge` fromPackage pkg `merge` fromPackages imports compile :: CompileEnvironment -> TypedPackage -> Either CompilationError MonomorphedPackage compile env pkg = left MonomorphError $ monomorphPackage env pkg
oden-lang/oden
src/Oden/Compiler.hs
mit
763
0
8
182
160
88
72
17
1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.SourceBuffer (appendBuffer, abort, remove, setMode, getMode, getUpdating, getBuffered, setTimestampOffset, getTimestampOffset, getAudioTracks, getVideoTracks, getTextTracks, setAppendWindowStart, getAppendWindowStart, setAppendWindowEnd, getAppendWindowEnd, updatestart, update, updateend, error, abortEvent, SourceBuffer(..), gTypeSourceBuffer) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.appendBuffer Mozilla SourceBuffer.appendBuffer documentation> appendBuffer :: (MonadDOM m, IsBufferSource data') => SourceBuffer -> data' -> m () appendBuffer self data' = liftDOM (void (self ^. jsf "appendBuffer" [toJSVal data'])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.abort Mozilla SourceBuffer.abort documentation> abort :: (MonadDOM m) => SourceBuffer -> m () abort self = liftDOM (void (self ^. jsf "abort" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.remove Mozilla SourceBuffer.remove documentation> remove :: (MonadDOM m) => SourceBuffer -> Double -> Double -> m () remove self start end = liftDOM (void (self ^. jsf "remove" [toJSVal start, toJSVal end])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.mode Mozilla SourceBuffer.mode documentation> setMode :: (MonadDOM m) => SourceBuffer -> AppendMode -> m () setMode self val = liftDOM (self ^. jss "mode" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.mode Mozilla SourceBuffer.mode documentation> getMode :: (MonadDOM m) => SourceBuffer -> m AppendMode getMode self = liftDOM ((self ^. js "mode") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.updating Mozilla SourceBuffer.updating documentation> getUpdating :: (MonadDOM m) => SourceBuffer -> m Bool getUpdating self = liftDOM ((self ^. js "updating") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.buffered Mozilla SourceBuffer.buffered documentation> getBuffered :: (MonadDOM m) => SourceBuffer -> m TimeRanges getBuffered self = liftDOM ((self ^. js "buffered") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.timestampOffset Mozilla SourceBuffer.timestampOffset documentation> setTimestampOffset :: (MonadDOM m) => SourceBuffer -> Double -> m () setTimestampOffset self val = liftDOM (self ^. jss "timestampOffset" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.timestampOffset Mozilla SourceBuffer.timestampOffset documentation> getTimestampOffset :: (MonadDOM m) => SourceBuffer -> m Double getTimestampOffset self = liftDOM ((self ^. js "timestampOffset") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.audioTracks Mozilla SourceBuffer.audioTracks documentation> getAudioTracks :: (MonadDOM m) => SourceBuffer -> m AudioTrackList getAudioTracks self = liftDOM ((self ^. js "audioTracks") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.videoTracks Mozilla SourceBuffer.videoTracks documentation> getVideoTracks :: (MonadDOM m) => SourceBuffer -> m VideoTrackList getVideoTracks self = liftDOM ((self ^. js "videoTracks") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.textTracks Mozilla SourceBuffer.textTracks documentation> getTextTracks :: (MonadDOM m) => SourceBuffer -> m TextTrackList getTextTracks self = liftDOM ((self ^. js "textTracks") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.appendWindowStart Mozilla SourceBuffer.appendWindowStart documentation> setAppendWindowStart :: (MonadDOM m) => SourceBuffer -> Double -> m () setAppendWindowStart self val = liftDOM (self ^. jss "appendWindowStart" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.appendWindowStart Mozilla SourceBuffer.appendWindowStart documentation> getAppendWindowStart :: (MonadDOM m) => SourceBuffer -> m Double getAppendWindowStart self = liftDOM ((self ^. js "appendWindowStart") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.appendWindowEnd Mozilla SourceBuffer.appendWindowEnd documentation> setAppendWindowEnd :: (MonadDOM m) => SourceBuffer -> Double -> m () setAppendWindowEnd self val = liftDOM (self ^. jss "appendWindowEnd" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.appendWindowEnd Mozilla SourceBuffer.appendWindowEnd documentation> getAppendWindowEnd :: (MonadDOM m) => SourceBuffer -> m Double getAppendWindowEnd self = liftDOM ((self ^. js "appendWindowEnd") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.onupdatestart Mozilla SourceBuffer.onupdatestart documentation> updatestart :: EventName SourceBuffer onupdatestart updatestart = unsafeEventName (toJSString "updatestart") -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.onupdate Mozilla SourceBuffer.onupdate documentation> update :: EventName SourceBuffer onupdate update = unsafeEventName (toJSString "update") -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.onupdateend Mozilla SourceBuffer.onupdateend documentation> updateend :: EventName SourceBuffer onupdateend updateend = unsafeEventName (toJSString "updateend") -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.onerror Mozilla SourceBuffer.onerror documentation> error :: EventName SourceBuffer UIEvent error = unsafeEventNameAsync (toJSString "error") -- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.onabort Mozilla SourceBuffer.onabort documentation> abortEvent :: EventName SourceBuffer UIEvent abortEvent = unsafeEventNameAsync (toJSString "abort")
ghcjs/jsaddle-dom
src/JSDOM/Generated/SourceBuffer.hs
mit
6,924
0
12
827
1,369
760
609
82
1
module Main where import Data.Set.Class as Sets import qualified Data.Set as Set import qualified Data.Map as Map import qualified Data.Sequence as Seq import qualified Data.IntSet as IntSet import qualified Data.IntMap as IntMap import qualified Data.List as List import qualified Data.HashSet as HashSet import qualified Data.HashMap.Lazy as HashMap import qualified Data.Functor.Contravariant as Pred import qualified Data.Set.Ordered.Many as OM import qualified Data.Set.Unordered.Many as UM import qualified Data.Set.Unordered.Unique as UU import qualified Data.Set.Ordered.Unique.Finite as OUF import qualified Data.Set.Ordered.Unique.With as SetWith import qualified Data.Set.Ordered.Many.With as SetsWith import Data.Monoid import Data.Commutative import Criterion.Main import Data.Set.Data import Data.Map.Data import Data.IntSet.Data import Data.IntMap.Data import Data.Set.Ordered.Many.Data import Data.Set.Unordered.Many.Data import Data.Set.Unordered.Unique.Data main :: IO () main = defaultMain [ bgroup "Union" [ bgroup "`Data.Set`" $ benchUnion set1 [set1,set2,set3,set4,set5] , bgroup "`Data.Map`" $ benchUnion map1 [map1,map2,map3,map4,map5] , bgroup "`Data.IntSet`" $ benchUnion iset1 [iset1,iset2,iset3,iset4,iset5] , bgroup "`Data.IntMap`" $ benchUnion imap1 [imap1,imap2,imap3,imap4,imap5] , bgroup "`Data.Set.Ordered.Many`" $ benchUnion omset1 [omset1,omset2,omset3,omset4,omset5] , bgroup "`Data.Set.Unordered.Many`" $ benchUnion umset1 [umset1,umset2,umset3,umset4,umset5] , bgroup "`Data.Set.Unordered.Unique`" $ benchUnion uuset1 [uuset1,uuset2,uuset3,uuset4,uuset5] ] , bgroup "Intersection" [ bgroup "`Data.Set`" $ benchIntersection set1 [set1,set2,set3,set4,set5] , bgroup "`Data.Map`" $ benchIntersection map1 [map1,map2,map3,map4,map5] , bgroup "`Data.IntSet`" $ benchIntersection iset1 [iset1,iset2,iset3,iset4,iset5] , bgroup "`Data.IntMap`" $ benchIntersection imap1 [imap1,imap2,imap3,imap4,imap5] , bgroup "`Data.Set.Ordered.Many`" $ benchIntersection omset1 [omset1,omset2,omset3,omset4,omset5] , bgroup "`Data.Set.Unordered.Many`" $ benchIntersection umset1 [umset1,umset2,umset3,umset4,umset5] , bgroup "`Data.Set.Unordered.Unique`" $ benchIntersection uuset1 [uuset1,uuset2,uuset3,uuset4,uuset5] ] , bgroup "Difference" [ bgroup "`Data.Set`" $ benchDifference set1 [set1,set2,set3,set4,set5] , bgroup "`Data.Map`" $ benchDifference map1 [map1,map2,map3,map4,map5] , bgroup "`Data.IntSet`" $ benchDifference iset1 [iset1,iset2,iset3,iset4,iset5] , bgroup "`Data.IntMap`" $ benchDifference imap1 [imap1,imap2,imap3,imap4,imap5] , bgroup "`Data.Set.Ordered.Many`" $ benchDifference omset1 [omset1,omset2,omset3,omset4,omset5] , bgroup "`Data.Set.Unordered.Many`" $ benchDifference umset1 [umset1,umset2,umset3,umset4,umset5] , bgroup "`Data.Set.Unordered.Unique`" $ benchDifference uuset1 [uuset1,uuset2,uuset3,uuset4,uuset5] ] , bgroup "Insert" [ bgroup "`Data.Set`" $ benchInsert set5 ([10,20,30,40,50] :: [Int]) , bgroup "`Data.IntSet`" $ benchInsert iset5 ([10,20,30,40,50] :: [Int]) , bgroup "`Data.Set.Ordered.Many`" $ benchInsert omset5 ([10,20,30,40,50] :: [Int]) , bgroup "`Data.Set.Unordered.Many`" $ benchInsert umset5 ([10,20,30,40,50] :: [Int]) , bgroup "`Data.Set.Unordered.Unique`" $ benchInsert uuset5 ([10,20,30,40,50] :: [Int]) ] , bgroup "Delete" [ bgroup "`Data.Set`" $ benchDelete set5 ([10,20,30,40,50] :: [Int]) , bgroup "`Data.IntSet`" $ benchDelete iset5 ([10,20,30,40,50] :: [Int]) , bgroup "`Data.Set.Ordered.Many`" $ benchDelete omset5 ([10,20,30,40,50] :: [Int]) , bgroup "`Data.Set.Unordered.Many`" $ benchDelete umset5 ([10,20,30,40,50] :: [Int]) , bgroup "`Data.Set.Unordered.Unique`" $ benchDelete uuset5 ([10,20,30,40,50] :: [Int]) ] ] benchBin :: String -> (s -> s -> s) -> s -> [s] -> [Benchmark] benchBin name bin s1 ss = [ bgroup (name ++ " xs") [ bench (show k) $ whnf (`bin` s1) s | (k,s) <- [(1 :: Int)..] `zip` ss ] , bgroup ("xs " ++ name) [ bench (show k) $ whnf (s1 `bin`) s | (k,s) <- [(1 :: Int)..] `zip` ss ] ] benchUnion :: HasUnion s => s -> [s] -> [Benchmark] benchUnion = benchBin "`union`" Sets.union benchIntersection :: HasIntersection s => s -> [s] -> [Benchmark] benchIntersection = benchBin "`intersection`" Sets.intersection benchDifference :: HasDifference s => s -> [s] -> [Benchmark] benchDifference = benchBin "`difference`" Sets.difference benchElem :: (a -> s -> s) -> s -> [a] -> [Benchmark] benchElem act s0 ss = [ bench (show k) $ whnf (`act` s0) s | (k,s) <- [(1 :: Int)..] `zip` ss ] benchInsert :: HasInsert a s => s -> [a] -> [Benchmark] benchInsert = benchElem Sets.insert benchDelete :: HasDelete a s => s -> [a] -> [Benchmark] benchDelete = benchElem Sets.delete
athanclark/sets
bench/Profile.hs
mit
5,167
0
12
1,039
1,776
1,043
733
118
1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {- | Module : Network.MPD.Applicative.Internal Copyright : (c) Simon Hengel 2012 License : MIT Maintainer : joachifm@fastmail.fm Stability : stable Portability : unportable Applicative MPD command interface. This allows us to combine commands into command lists, as in > (,,) <$> currentSong <*> stats <*> status where the requests are automatically combined into a command list and the result of each command passed to the consumer. -} module Network.MPD.Applicative.Internal ( Parser(..) , liftParser , getResponse , emptyResponse , unexpected , Command(..) , runCommand ) where import Control.Applicative import Control.Monad import Data.ByteString.Char8 (ByteString) import Network.MPD.Core hiding (getResponse) import qualified Network.MPD.Core as Core import Control.Monad.Error -- | A line-oriented parser that returns a value along with any remaining input. newtype Parser a = Parser { runParser :: [ByteString] -> Either String (a, [ByteString]) } deriving Functor instance Monad Parser where fail = Parser . const . Left return a = Parser $ \input -> Right (a, input) p1 >>= p2 = Parser $ runParser p1 >=> uncurry (runParser . p2) instance Applicative Parser where pure = return (<*>) = ap -- | Convert a regular parser. liftParser :: ([ByteString] -> Either String a) -> Parser a liftParser p = Parser $ \input -> case break (== "list_OK") input of (xs, ys) -> fmap (, drop 1 ys) (p xs) -- | Return everything until the next "list_OK". getResponse :: Parser [ByteString] getResponse = Parser $ \input -> case break (== "list_OK") input of (xs, ys) -> Right (xs, drop 1 ys) -- | For commands returning an empty response. emptyResponse :: Parser () emptyResponse = do r <- getResponse unless (null r) $ unexpected r -- | Fail with unexpected response. unexpected :: [ByteString] -> Parser a unexpected = fail . ("unexpected Response: " ++) . show -- | A compound command, comprising a parser for the responses and a -- combined request of an arbitrary number of commands. data Command a = Command { commandParser :: Parser a , commandRequest :: [String] } deriving Functor instance Applicative Command where pure a = Command (pure a) [] (Command p1 c1) <*> (Command p2 c2) = Command (p1 <*> p2) (c1 ++ c2) -- | Execute a 'Command'. runCommand :: MonadMPD m => Command a -> m a runCommand (Command p c) = do r <- Core.getResponse command case runParser p r of Left err -> throwError (Unexpected err) Right (a, []) -> return a Right (_, xs) -> throwError (Unexpected $ "superfluous input: " ++ show xs) where command = case c of [x] -> x xs -> unlines ("command_list_ok_begin" : xs) ++ "command_list_end"
matthewleon/libmpd-haskell
src/Network/MPD/Applicative/Internal.hs
mit
2,998
0
13
733
740
405
335
58
4
{-# LANGUAGE DeriveDataTypeable #-} module Text.Greek.Mounce.Phonology where import Data.Data import Data.Text (Text) data Euphony = Euphony { euphonyName :: Text , euphonyRules :: [EuphonyRule] } deriving (Show, Eq) data EuphonyRule = EuphonyRule { euphonyRuleFirst :: Text , euphonyRuleSecond :: Text , euphonyRuleResult :: Text } deriving (Data, Typeable, Show, Eq)
scott-fleischman/greek-grammar
haskell/greek-grammar/src/Text/Greek/Mounce/Phonology.hs
mit
392
0
9
73
105
64
41
13
0
module Vidar.Parser ( parse ) where import Vidar import Text.ParserCombinators.ReadP import Data.Char import Control.Applicative ((<$>)) parse :: String -> Either ParseError [Vidar] parse s = case readP_to_S (many1 element) s of [(e, "")] -> Right e _ -> Left ParseError data ParseError = ParseError deriving Show token :: ReadP a -> ReadP a token p = skipSpaces >> p symbol :: Char -> ReadP Char symbol = token . char element :: ReadP Element element = (anything +++ (SubBlock <$> block) +++ namedblock +++ binding +++ notElement) <++ (Name <$> name) notElement :: ReadP Element notElement = do _ <- symbol '~' e <- element return $ Not e namedblock :: ReadP Element namedblock = do n <- name b <- block return $ Block n b binding :: ReadP Element binding = do n <- name _ <- symbol '=' e <- element return $ Binding n e block :: ReadP Block block = ordered +++ unordered +++ strict ordered :: ReadP Block ordered = do _ <- symbol '[' contents <- sepBy element (symbol ',') _ <- symbol ']' return $ OrderedBlock contents unordered :: ReadP Block unordered = do _ <- symbol '{' contents <- sepBy element (symbol ',') _ <- symbol '}' return $ UnorderedBlock contents strict :: ReadP Block strict = do _ <- symbol '(' contents <- sepBy element (symbol ',') _ <- symbol ')' return $ StrictBlock contents anything :: ReadP Element anything = token $ char '_' >> return Anything name :: ReadP Name name = anyname +++ exactname +++ somename anyname :: ReadP Name anyname = token $ char '_' >> return AnyName exactname :: ReadP Name exactname = token $ do _ <- char '"' n <- validname _ <- char '"' return $ ExactName n somename :: ReadP Name somename = token $ do n <- validname return $ SomeName n validname :: ReadP String validname = munch1 isAlphaNum
Tayacan/Vidar
Vidar/Parser.hs
mit
1,930
0
12
501
723
350
373
77
2
module Y2016.M10.D03.Exercise where -- below imports available from 1HaskellADay git repository: import Data.BlockChain.Block.Types import Data.Tree.Merkle import Y2016.M09.D22.Exercise (latestTransactions) {- *SIIIIIGGGGGGHHHHHH* <<- imagine the long sigh of a clerical worker when you hand in your forms only in duplicate (not triplicate) and filled out incorrectly, obviously (to the cleric) So, PRINTING out, or the Show instance of Merkle trees was very easily declared but a terrible mess to read, particularly when you're dealing with a block that has 2332 transactions that go into the Merkle tree. When I'm inspecting an instance of a tree-(like-)structure, I am less concerned with all the details of each object of the tree, and am much more concerned with the structure of the tree, itself. One way to go about this is to restructure the tree so that the nodes (which are branches) contain no structural information, so you have separate concerns: the tree(-structure) and the nodes (the values) it contains. That sounds too nice-n-clean for me right now: lots of work, lots of payoff. Wait. Did I just say that? Another way to go about this is to revise the Show instance of the tree-structure so that it shows the structure only, and if you wish to inspect a particular value, well, then, by Gum! You can do that on your own time, Charlie! Let us choose the latter course. Today's #haskell exercise: I've removed the Show derivation from the Branch a and BalancedBranch a data types in Data.Tree.Merkle. Create a show instance of these (containment-)structures that do not show all the messy details of the values contained. --} instance Show (Branch a) where show = undefined -- note: the a-type is not necessarily showable anymore instance Show (BalancedBranch a) where show = undefined -- I'm not too keen on seeing the SHA256 hashed values, either, by-the-bye. -- With the above Show instances defined, load in latestTransactions and -- show the Path to the first and the last transactions in that block lengthToHash :: MerkleTree a -> Hash -> Int lengthToHash tree hash = undefined -- What is the length of the path to the first transaction? -- What is the length of the path to the last transaction? -- What is the mean length to any transaction in the latest block? -- How many transactions were in the latest block? -- THERE! Now isn't that better than looking at the entire tree at the head -- of each path?
geophf/1HaskellADay
exercises/HAD/Y2016/M10/D03/Exercise.hs
mit
2,510
0
7
484
109
68
41
10
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE TemplateHaskell #-} module Yage.TH where import Yage.Prelude import Language.Haskell.TH.Syntax instance Lift FilePath where lift fp = [| fpToString fp |]
MaxDaten/yage-contrib
src/Yage/TH.hs
mit
211
0
6
32
39
25
14
7
0
-- | -- -- Module : AprioriSpec.Data -- License : MIT module TestData ( AprioriTestData(..) , AprioriDebugData(..) , AssocRulesTestData(..) ) where import DataAssociation.Definitions import DataAssociation.APriori.Debug data AprioriTestData set it = AprioriTestData{ tTransactions :: [set it] , tMinsup :: MinSupport , tRuns :: [AprioriDebugData set it] } data AssocRulesTestData set it = AssocRulesTestData{ trTransactions :: [set it] , tLargeItemset :: (set it, Float) , tMinconf :: MinConfidence , tRules :: [AssocRule set it] }
fehu/min-dat--a-priori
core/test/TestData.hs
mit
578
0
10
119
143
91
52
15
0
{-# LANGUAGE OverloadedStrings #-} module Test where import Bencode (Bencode(..), parseBencode, antiParse) import Control.Monad (replicateM) import Data.Attoparsec.Lazy (Result(..), parse) import Data.Map (fromList) import Test.QuickCheck (Arbitrary, Gen, Property, arbitrary, choose, quickCheck, verboseCheck, (==>)) import qualified Data.ByteString.Lazy as BL import qualified Text.Show.ByteString as TSB main :: IO () main = quickCheck prop_bencode_inverse -- TODO: I interpret conformance to the bencoding specification to entail -- not only acceptance of all valid inputs, but also rejection of all invalid -- inputs. I'm a hard-ass, not a follower of Postel's Principle. instance Arbitrary BL.ByteString where arbitrary = do n <- choose (0, 1000) :: Gen Int nbytes <- replicateM n arbitrary return $ TSB.show n `BL.append` ":" `BL.append` BL.pack nbytes instance Arbitrary Bencode where arbitrary = do n <- choose (1, 3) :: Gen Int case n of 1 -> arbitrary >>= return . BString 2 -> arbitrary >>= return . BInt 3 -> choose (0, 2 :: Int) >>= flip replicateM arbitrary >>= return . BList 4 -> choose (0, 2 :: Int) >>= flip replicateM arbitrary >>= return . BDict . fromList -- tests to write: actual unit tests for parseBencode and antiParse -- modulo type details: antiParse . parseBencode is id on BL.ByteString prop_bytestring_inverse :: BL.ByteString -> Property prop_bytestring_inverse bs = bencodedInput bs ==> let (Done "" bencode) = parse parseBencode bs in antiParse bencode == bs where bencodedInput :: BL.ByteString -> Bool bencodedInput bl = case parse parseBencode bl of (Done "" _) -> True _ -> False -- modulo type details: parseBencode . antiParse is id on Bencode -- TODO: return Property instead of Bool? can do True ==>, but that seems dumb -- get rid of call to "error", which should never occur prop_bencode_inverse :: Bencode -> Bool prop_bencode_inverse bencode = case parse parseBencode (antiParse bencode) of (Done "" bencode') -> bencode == bencode' _ -> error "either parseBencode or antiParse is broken"
nabilhassein/bitcurry
test/Test.hs
mit
2,321
3
21
599
532
288
244
40
2
{-# LANGUAGE QuasiQuotes #-} module Y2018.M01.D10.Exercise where {-- Today's Haskell exercise is a bit of a warming-up exercise. Today we'll store packet information in the packet table (the structure of the table matching Packet (see Y2017.M12.D20.Exercise), and also write the fetch function that retrieves packet information from the database from a given id (which we will provide later). We do this for auditing purposes. We wish to store not only the articles that we store, but also information about what we stored and when. Storing packet information is a piece of that puzzle. ... hm. Actually, I don't think a fetch function is necessary given how I'm planning auditing. We shall see. For today, just write the toRow function --} import Data.Functor.Identity (Identity) import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.SqlQQ import Database.PostgreSQL.Simple.ToField (toField) import Database.PostgreSQL.Simple.ToRow -- below import available via 1HaskellADay git repository import Data.LookupTable (LookupTable) import Store.SQL.Util.Indexed import Y2017.M12.D20.Exercise (Packet) import Y2017.M12.D27.Exercise (DatedArticle) import Y2017.M12.D29.Exercise (BlockParser) import Y2018.M01.D04.Exercise hiding (etl) -- hint for bonus insertPacketStmt :: Query insertPacketStmt = [sql|INSERT INTO packet (view,prev,next,total,count) VALUES (?,?,?,?,?)|] insertPackets :: Connection -> [Packet] -> IO () insertPackets conn packs = undefined instance ToRow Packet where toRow pack = undefined {-- Using Y2017.M12.D20.Exercise.readSample, load in the packet and store its information. --} {-- BONUS ----------------------------------------------------------------- Rewrite the etl-process to store the packet information (that is: don't discard packet information anymore) along with the articles. Remember to include logging functionality as well! --} gruntWerk :: LookupTable -> BlockParser Identity Authors -> (Connection -> [IxValue (DatedArticle Authors)] -> IO ()) -> Connection -> Packet -> IO (IxValue (DatedArticle Authors)) gruntWerk lk generator ancillaryFn conn pack = undefined
geophf/1HaskellADay
exercises/HAD/Y2018/M01/D10/Exercise.hs
mit
2,148
0
14
302
273
163
110
24
1
{-# htermination enumFrom :: Bool -> [Bool] #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_enumFrom_7.hs
mit
48
0
2
8
3
2
1
1
0
module Sockets ( newServer, Broadcaster ) where import BasePrelude hiding ((\\)) import Control.Concurrent.Suspend (sDelay) import Control.Concurrent.Timer import Control.Monad.Trans (lift) import Control.Monad.Trans.Maybe (runMaybeT) import qualified Data.Aeson as Aeson import Data.ByteString.Lazy (ByteString) import Data.Map (Map) import qualified Data.Map as Map import Data.UnixTime (UnixTime, getUnixTime, secondsToUnixDiffTime, diffUnixTime) import qualified Network.HTTP.Types.URI as URI import qualified Network.WebSockets as WS import System.IO.Streams.Attoparsec (ParseException) import Types type Broadcaster = Post -> IO () data Client = Client { clientIdentifier :: Unique } deriving (Eq, Ord) data Beat = Beat { beatLastTime :: UnixTime , beatConnection :: WS.Connection } type ServerState = Map Client Beat newServerState :: ServerState newServerState = Map.empty addClient :: Client -> Beat -> ServerState -> ServerState addClient = Map.insert removeClient :: Client -> ServerState -> ServerState removeClient = Map.delete broadcast :: Aeson.ToJSON a => a -> ServerState -> IO () broadcast message state = forM_ (Map.toList state) send where send (_, Beat { beatConnection } ) = WS.sendTextData beatConnection (Aeson.encode message) ping :: WS.Connection -> IO () ping = flip WS.sendPing ("ping" :: ByteString) heartbeatIntervalSeconds :: Int64 heartbeatIntervalSeconds = 20 heartbeat :: MVar ServerState -> IO () heartbeat db = modifyMVar_ db $ \state -> Map.fromList <$> filterM predicate (Map.toList state) where maximumDelta = secondsToUnixDiffTime (heartbeatIntervalSeconds * 2) predicate (_, Beat { beatLastTime, beatConnection } )= do now <- getUnixTime if diffUnixTime now beatLastTime > maximumDelta then do WS.sendClose beatConnection ("pong better" :: ByteString) return False else do ping beatConnection return True newServer :: Aeson.ToJSON a => Chan a -> IO WS.ServerApp newServer chan = do state <- newMVar newServerState repeatedTimer (heartbeat state) (sDelay heartbeatIntervalSeconds) forkIO $ getChanContents chan >>= mapM_ (makeBroadcast state) return $ application state where makeBroadcast db post = readMVar db >>= broadcast post ifAccept :: WS.PendingConnection -> (WS.Connection -> IO ()) -> IO () ifAccept pending callback = case (URI.decodePath . WS.requestPath . WS.pendingRequest) pending of ([], _) -> WS.acceptRequest pending >>= callback _ -> WS.rejectRequest pending "You can only connect to / right now." handleMessages :: IO () -> WS.Connection -> IO () handleMessages onPong conn = void $ (runMaybeT . forever) $ do msg <- lift $ WS.receive conn case msg of WS.DataMessage _ -> pure () WS.ControlMessage cm -> case cm of WS.Close _ _ -> mzero WS.Pong _ -> lift onPong WS.Ping a -> lift (WS.send conn (WS.ControlMessage (WS.Pong a))) application_ :: MVar ServerState -> WS.ServerApp application_ db pending = ifAccept pending $ \conn -> do clientIdentifier <- newUnique let client = Client { clientIdentifier } (`finally` disconnect client) $ do setTime client conn handleMessages (setTime client conn) conn where withState = modifyMVar_ db setTime client conn = withState $ \state -> do beatLastTime <- getUnixTime let beat = Beat { beatLastTime, beatConnection = conn } return $ addClient client beat state disconnect client = withState (return . removeClient client) application :: MVar ServerState -> WS.ServerApp application db pending = (handle connectionExceptions . handle parseExceptions) (application_ db pending) where parseExceptions = const $ throw WS.ConnectionClosed :: ParseException -> IO () connectionExceptions = const $ return () :: WS.ConnectionException -> IO ()
jackbowman/basilica
Sockets.hs
mit
3,991
0
21
858
1,257
648
609
-1
-1
module Melchior.EventSources.Keyboard ( keyDownSignal , keyPressSignal , keyUpSignal , keyCode , presses ) where import Control.Applicative import Melchior.Control import Melchior.Data.String import Melchior.Dom import Melchior.Dom.Events keyDownSignal :: Element -> Signal KeyboardEvent keyDownSignal e = createEventedSignal (Of KeyDown) e (KeyboardEvt KeyDown) keyPressSignal :: Element -> Signal KeyboardEvent keyPressSignal e = createEventedSignal (Of KeyPress) e (KeyboardEvt KeyPress) keyUpSignal :: Element -> Signal KeyboardEvent keyUpSignal e = createEventedSignal (Of KeyUp) e (KeyboardEvt KeyUp) keyCode :: Signal KeyboardEvent -> Signal Int keyCode s = (\x -> code x) <$> s foreign import js "Events.keyCode(%1)" code :: KeyboardEvent -> Int presses :: Element -> Signal (Int, Int) presses el = (\_ -> (sample up, sample down)) <$> merge up down where up = keyCode $ keyUpSignal el down = keyCode $ keyDownSignal el
kjgorman/melchior
Melchior/EventSources/Keyboard.hs
mit
982
1
9
181
296
157
139
25
1
import Text.Trifecta import Data.Word import Data.Bits import Data.Char import Control.Applicative import Data.List -- i guess Word64 is as big as we have? data IPAddress6 = IPAddress6 Word64 Word64 deriving (Eq, Ord) foldNibbles :: [Word8] -> Word64 foldNibbles xs | length xs > 16 = error "foldNibbles overflow" | otherwise = foldl (\acc x -> (fromIntegral x) + (shiftL acc 4)) 0 xs foldWords :: [Word16] -> Word64 foldWords xs | length xs > 4 = error "foldWords overflow" | otherwise = foldl (\acc x -> (fromIntegral x) + (shiftL acc 16)) 0 xs parseHexDigit :: Parser Char parseHexDigit = oneOf hexChars <|> oneOf (toUpper <$> hexChars) parseNibble :: Parser Word8 parseNibble = do c <- toLower <$> parseHexDigit <?> "invalid hex digit" return $ hexValue c parseWord16 :: Parser Word16 parseWord16 = do -- take up to four optional nibbles -- maybe char mc1 <- optional parseNibble mc2 <- optional parseNibble mc3 <- optional parseNibble mc4 <- optional parseNibble let xs = foo [mc1,mc2,mc3,mc4] return $ fromIntegral $ foldNibbles xs padWords :: Int -> [Word16] -> [Word16] padWords 0 xs = xs padWords _ [] = [] padWords n (x:xs) = if x == 0 then replicate (n+1) 0 ++ xs else x : padWords n xs parseWords :: Parser [Word16] parseWords = do words <- parseWord16 `sepBy` char ':' let padBy = 8 - length words return $ padWords padBy words parseAddr6 :: Parser IPAddress6 parseAddr6 = do ws <- parseWords let h = foldWords (take 4 ws) l = foldWords (drop 4 ws) return $ IPAddress6 h l foo :: [Maybe a] -> [a] foo [] = [] foo (x:xs) = case x of Nothing -> [] Just a -> a : foo xs hexChars :: [Char] hexChars = ['0'..'9'] ++ ['a'..'f'] hexValues :: [(Char,Word8)] hexValues = zip hexChars [0..] hexValue :: Char -> Word8 hexValue c = fromIntegral $ maybe 0 id (lookup c hexValues) hexChar :: Word8 -> Char hexChar x = fst (hexValues !! (fromIntegral x)) showWord16 :: Word16 -> String showWord16 = padTo '0' 4 . map hexChar . nibblesBE showAddr6 :: IPAddress6 -> String showAddr6 = concat . intersperse ":" . map showWord16 . addr6ToWords addr6ToWords :: IPAddress6 -> [Word16] addr6ToWords (IPAddress6 h l) = padTo 0 4 highWords ++ padTo 0 4 loWords where highWords = word64ToWords16BE h loWords = word64ToWords16BE l padTo :: a -> Int -> [a] -> [a] padTo c l xs = go (length xs) xs where go l' xs | l' < l = c : go (l'+1) xs | otherwise = xs instance Show IPAddress6 where show = showAddr6 -- break 16bit into 4 bit words, little end first nibblesLE :: Word16 -> [Word8] nibblesLE 0 = [] nibblesLE w16 = r : nibblesLE q where q = w16 `shiftR` 4 r = fromIntegral $ w16 .&. 0xf nibblesBE = reverse . nibblesLE -- break 64bit word into 16 bit words, little end first word64ToWords16LE :: Word64 -> [Word16] word64ToWords16LE 0 = [] word64ToWords16LE w64 = r : word64ToWords16LE q where q = w64 `shiftR` 16 r = fromIntegral $ w64 .&. 0xffff -- big end first word64ToWords16BE = reverse . word64ToWords16LE -- use Integer just for test harness toInteger' :: IPAddress6 -> Integer toInteger' (IPAddress6 h l) = ((fromIntegral h) `shiftL` 64) + fromIntegral l testV6Parse (s,i) = case parseString (toInteger' <$> parseAddr6) mempty s of Failure _ -> False Success i' -> i' == i v6tests = [ ("0:0:0:0:0:ffff:ac10:fe01", 0xffffac10fe01) , ("0:0:0:0:0:ffff:cc78:f", 0xffffcc78000f) , ("FE80:0000:0000:0000:0202:B3FF:FE1E:8329", 0xfe800000000000000202b3fffe1e8329) , ("FE80::::0202:B3FF:FE1E:8329", 0xfe800000000000000202b3fffe1e8329) , ("FE80::0202:B3FF:FE1E:8329", 0xfe800000000000000202b3fffe1e8329) , ("2001:0DB8:0000:0000:0008:0800:200C:417A", 0x20010db80000000000080800200c417a) , ("2001:DB8::8:800:200C:417A", 0x20010db80000000000080800200c417a) ] runV6Tests = all testV6Parse v6tests addr6 :: String -> Maybe IPAddress6 addr6 s = case parseString parseAddr6 mempty s of Failure _ -> Nothing Success r -> Just r main = do putStrLn $ "Passes Parse Tests: " ++ show runV6Tests
JustinUnger/haskell-book
ch24/ch24-ipv6.hs
mit
4,160
181
9
924
1,414
749
665
106
2
{-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-missing-methods #-} module Week6 where import Data.List (foldl') import Data.Bits (xor, popCount) fib :: Integer -> Integer fib 0 = 0 fib 1 = 1 fib n = fib (n - 1) + fib (n - 2) fibs1 :: [Integer] fibs1 = map fib [0..] fibs2 :: [Integer] fibs2 = map snd $ (0, 0) : iterate (\(x, y) -> (y, x + y)) (0, 1) data Stream a = Cons a (Stream a) streamToList :: Stream a -> [a] streamToList (Cons x b) = x : streamToList b instance Show a => Show (Stream a) where show = show . take 20 . streamToList streamRepeat :: a -> Stream a streamRepeat x = Cons x (streamRepeat x) streamMap :: (a -> b) -> Stream a -> Stream b streamMap f (Cons x xs) = Cons (f x) $ streamMap f xs streamFromSeed :: (a -> a) -> a -> Stream a streamFromSeed f x = Cons x $ streamFromSeed f $ f x nats :: Stream Integer nats = streamFromSeed (+1) 0 interleaveStreams :: Stream a -> Stream a -> Stream a interleaveStreams (Cons x xs) ys = Cons x $ interleaveStreams ys xs -- I did not come up with this. I hope to be able to one day. ruler :: Stream Integer ruler = foldr1 interleaveStreams $ map streamRepeat [0..] -- This was my orginal solution to ruler -- ruler :: Stream Integer -- ruler = interleaveStreams (streamRepeat 0) $ -- streamMap snd $ streamFromSeed rulerVal (2, 1) -- rulerVal :: (Integer, Integer) -> (Integer, Integer) -- rulerVal (x, v) = (x', v') -- where -- x' = x + 2 -- v' = fromIntegral $ popCount $ x `xor` x' -- rulerVals = streamMap snd $ streamFromSeed rulerVal (1, 2) -- ruler = interleaveStreams (streamRepeat 0) $ -- streamMap snd $ streamFromSeed rulerVal (2, 1) x :: Stream Integer x = Cons 0 $ Cons 1 $ streamRepeat 0 instance Num (Stream Integer) where (+) (Cons a as) (Cons b bs) = Cons (a + b) $ (+) as bs (*) (Cons a0 as) b@(Cons b0 bs) = Cons (a0 * b0) $ streamMap (a0 *) bs + as * b negate = streamMap negate abs = streamMap abs signum = streamMap signum fromInteger n = Cons n $ streamRepeat 0 instance Fractional (Stream Integer) where (/) (Cons a0 a') (Cons b0 b') = q where q = Cons (a0 `div` b0) $ streamMap (`div` b0) (a' - q * b') fibs3 :: Stream Integer fibs3 = x / (1 - x - x^2) data Matrix a = Matrix a a a a topRight (Matrix _ x _ _) = x instance Num a => Num (Matrix a) where (Matrix a1 b1 c1 d1) * (Matrix a2 b2 c2 d2) = Matrix (a1 * a2 + b1 * c2) (a1 * b2 + b1 * d2) (c1 * a2 + d1 * c2) (c1 * b2 + d1 * d2) fib4 :: Integer -> Integer fib4 0 = 0 fib4 x = topRight $ (Matrix 1 1 1 0) ^ x
taylor1791/cis-194-spring
src/Week6.hs
mit
2,538
0
12
594
1,045
547
498
53
1
module Reverse where rvrs :: String -> String rvrs x = concat [awesome, " ", is, " ", curry] where awesome = drop 9 x curry = take 5 x is = take 2 $ drop 6 x main :: IO () main = print $ rvrs "Curry is awesome" data Mood = Blah | Woot deriving Show changeMood :: Mood -> Mood changeMood Blah = Woot changeMood Woot = Blah isPalindrome :: (Eq a) => [a] -> Bool isPalindrome x = x == reverse x myAbs :: Integer -> Integer myAbs x = if x < 0 then x * (-1) else x f :: (a,b) -> (c,d) -> ((b,d), (a,c)) f x y = ((snd x, snd y), (fst x, fst y)) x = (+) f1 :: [a] -> Int f1 xs = w `x` 1 where w = length xs f2 (a,b) = a
NickAger/LearningHaskell
HaskellProgrammingFromFirstPrinciples/chapter3.hsproj/Chapter3.hs
mit
659
0
8
193
352
195
157
23
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-bucketencryption.html module Stratosphere.ResourceProperties.S3BucketBucketEncryption where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.S3BucketServerSideEncryptionRule -- | Full data type definition for S3BucketBucketEncryption. See -- 's3BucketBucketEncryption' for a more convenient constructor. data S3BucketBucketEncryption = S3BucketBucketEncryption { _s3BucketBucketEncryptionServerSideEncryptionConfiguration :: [S3BucketServerSideEncryptionRule] } deriving (Show, Eq) instance ToJSON S3BucketBucketEncryption where toJSON S3BucketBucketEncryption{..} = object $ catMaybes [ (Just . ("ServerSideEncryptionConfiguration",) . toJSON) _s3BucketBucketEncryptionServerSideEncryptionConfiguration ] -- | Constructor for 'S3BucketBucketEncryption' containing required fields as -- arguments. s3BucketBucketEncryption :: [S3BucketServerSideEncryptionRule] -- ^ 'sbbeServerSideEncryptionConfiguration' -> S3BucketBucketEncryption s3BucketBucketEncryption serverSideEncryptionConfigurationarg = S3BucketBucketEncryption { _s3BucketBucketEncryptionServerSideEncryptionConfiguration = serverSideEncryptionConfigurationarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-bucketencryption.html#cfn-s3-bucket-bucketencryption-serversideencryptionconfiguration sbbeServerSideEncryptionConfiguration :: Lens' S3BucketBucketEncryption [S3BucketServerSideEncryptionRule] sbbeServerSideEncryptionConfiguration = lens _s3BucketBucketEncryptionServerSideEncryptionConfiguration (\s a -> s { _s3BucketBucketEncryptionServerSideEncryptionConfiguration = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/S3BucketBucketEncryption.hs
mit
1,880
0
13
162
177
105
72
24
1
module Main where import qualified Data.ByteString.Char8 as BS8 import Database.PostgreSQL.Simple ( connectPostgreSQL, withTransaction) import Database.PostgreSQL.Simple.Migration (MigrationCommand(..), MigrationContext(..), MigrationResult, runMigration) import System.Environment (getArgs, getEnv) import System.Exit (exitFailure) import AppContext (getContext) main :: IO (MigrationResult String) main = do args <- getArgs case args of [env] -> migrateEnv env _ -> do putStrLn "Usage: stack exec migrate <env>" exitFailure migrateEnv :: String -> IO (MigrationResult String) migrateEnv env = do _ <- getContext env dbUrl <- BS8.pack <$> getEnv "DATABASE_URL" conn <- connectPostgreSQL dbUrl withTransaction conn $ do _ <- runMigration $ MigrationContext MigrationInitialization True conn runMigration $ MigrationContext (MigrationDirectory "db/migrations") True conn
robertjlooby/scotty-story-board
db/Migrate.hs
mit
996
0
13
227
257
135
122
23
2
module NetworkClient (startClient) where import Control.Concurrent import Network import System.Environment import System.Exit import System.IO import Types startClient:: String -> String -> MVar [Object] -> MVar [Object] -> IO () startClient host port getMVar sendMVar = withSocketsDo (handleConnection host (readPortNumber port) getMVar sendMVar) readPortNumber = PortNumber . fromIntegral . read handleConnection host port getMVar sendMVar = do conn <- connectTo host port exit <- newEmptyMVar forkIO $ readNetwork exit conn getMVar forkIO $ sendNetwork sendMVar conn takeMVar exit readNetwork :: MVar () -> Handle -> MVar [Object] -> IO () readNetwork exit net fromNetVar = do hIsEOF net >>= \bool -> case bool of True -> hClose net >> putMVar exit () False -> do line <- hGetLine net putMVar fromNetVar (read line) readNetwork exit net fromNetVar sendNetwork :: MVar [Object] -> Handle -> IO () sendNetwork toNetVar net = do toSend <- takeMVar toNetVar hPutStrLn net (show toSend) hFlush net sendNetwork toNetVar net
NemoNessuno/SuperAwesomePictureChatOfDoom
NetworkClient.hs
gpl-2.0
1,077
0
16
208
382
182
200
30
2
module Expr where import qualified Data.Map as M -- (3 балла) data Value = I Integer | B Bool deriving (Eq, Show) data BinOp = Plus | Mul | Minus | Less | Greater | Equals data UnOp = Neg | Not data Expr = BinOp BinOp Expr Expr | UnOp UnOp Expr | Const Value | Var String data Statement = Assign String Expr | If Expr Program (Maybe Program) | While Expr Program type Program = [Statement] infixr 0 $= ($=) = Assign infix 4 `less`, `greater` less = BinOp Less greater = BinOp Greater infixl 7 `mul` mul = BinOp Mul infixl 6 `plus`, `minus` plus = BinOp Plus minus = BinOp Minus infix 1 `else_` else_ :: (Maybe Program -> Statement) -> Program -> Statement else_ f e = f (Just e) type Error = String -- evalExpr m e интерпретирует e в контексте m, который сопоставлят имени переменной ее значение. -- evalExpr возвращает либо успешно вычисленный результат, либо список ошибок. -- Ошибки бывают двух видов: необъявленная переменная и несоответствие типов. evalExpr :: M.Map String Value -> Expr -> Either [Error] Value evalExpr _ (Const x) = Right x evalExpr context (Var name) | not $ M.member name context = Left ["Variable " ++ name ++ " is undefined"] | otherwise = Right $ context M.! name evalExpr _ (UnOp Not (Const (I _))) = Left ["Not cannot apply to ints"] evalExpr _ (UnOp Neg (Const (B _))) = Left ["Neg cannot apply to bools"] evalExpr _ (BinOp _ (Const (B _)) (Const (I _))) = Left ["Cannot apply binary operation to int & bool"] evalExpr _ (BinOp _ (Const (I _)) (Const (B _))) = Left ["Cannot apply binary operation to bool & int"] evalExpr _ (BinOp Plus (Const (B _)) (Const (B _))) = Left ["Cannot apply plus to bools"] evalExpr _ (BinOp Minus (Const (B _)) (Const (B _))) = Left ["Cannot apply minus to bools"] evalExpr _ (BinOp Mul (Const (B _)) (Const (B _))) = Left ["Cannot apply mul to bools"] evalExpr _ (UnOp Not (Const (B b))) = Right $ B $ not b evalExpr _ (UnOp Neg (Const (I i))) = Right $ I (-i) evalExpr _ (BinOp Plus (Const (I i1)) (Const (I i2))) = Right $ I $ i1 + i2 evalExpr _ (BinOp Minus (Const (I i1)) (Const (I i2))) = Right $ I $ i1 - i2 evalExpr _ (BinOp Mul (Const (I i1)) (Const (I i2))) = Right $ I $ i1 * i2 evalExpr _ (BinOp Less (Const (I i1)) (Const (I i2))) = Right $ B $ i1 < i2 evalExpr _ (BinOp Greater (Const (I i1)) (Const (I i2))) = Right $ B $ i1 > i2 evalExpr _ (BinOp Equals (Const (I i1)) (Const (I i2))) = Right $ B $ i1 == i2 evalExpr _ (BinOp Equals (Const (B b1)) (Const (B b2))) = Right $ B $ b1 == b2 evalExpr context (UnOp op e) = go $ evalExpr context e where go (Left x) = Left x go (Right x) = evalExpr context (UnOp op $ Const x) evalExpr context (BinOp op e1 e2) = go (evalExpr context e1) (evalExpr context e2) where go (Left x1) (Left x2) = Left $ x1 ++ x2 go (Left x1) _ = Left x1 go _ (Left x2) = Left x2 go (Right x1) (Right x2) = evalExpr context (BinOp op (Const x1) (Const x2)) -- evalStatement m e интерпретирует e в контексте m. -- evalStatement возвращает либо обновленный контекст, либо список ошибок. evalStatement :: M.Map String Value -> Statement -> Either [Error] (M.Map String Value) evalStatement context (Assign name expr) = case evalExpr context expr of Left e -> Left e Right value -> Right $ M.insert name value context evalStatement context (If condition body Nothing) = case evalExpr context condition of Left e -> Left e Right (B True) -> evalProgram context body Right _ -> Right context evalStatement context (If condition body (Just otherBody)) = case evalExpr context condition of Left e -> Left e Right (I _) -> Left ["If cannot be applied to an integer"] Right (B True) -> evalProgram context body Right _ -> evalProgram context otherBody evalStatement context (While condition body) = case evalExpr context condition of Left e -> Left e Right (B True) -> case evalProgram context body of Left e -> Left e Right c -> evalStatement c (While condition body) Right _ -> Right context evalProgram :: M.Map String Value -> Program -> Either [Error] (M.Map String Value) evalProgram context [] = Right context evalProgram context (s:xs) = case evalStatement context s of Left e -> Left e Right c -> evalProgram c xs
nkartashov/haskell
hw06/Expr.hs
gpl-2.0
4,674
0
13
1,080
1,921
964
957
75
10
{-# LANGUAGE ViewPatterns #-} module OverlayMsg ( OverlayMsg(..), hGetOverlayMsg, hPutOverlayMsg ) where import Control.Monad import Control.Applicative import Control.Exception import Data.Binary import Data.Binary.Put import Data.Binary.Get import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Char8 as L8 import System.IO data OverlayMsg = OverlayMsgInit { overlayMsgInitWidth :: Int, overlayMsgInitHeight :: Int } | OverlayMsgShmem { overlayMsgShmemName :: String } | OverlayMsgBlit { overlayMsgBlitX :: Int, overlayMsgBlitY :: Int, overlayMsgBlitWidth :: Int, overlayMsgBlitHeight :: Int } | OverlayMsgActive { overlayMsgActiveX :: Int, overlayMsgActiveY :: Int, overlayMsgActiveWidth :: Int, overlayMsgActiveHeight :: Int } | OverlayMsgPid { overlayMsgPidPid :: Int } | OverlayMsgFps { overlayMsgFpsFps :: Float } | OverlayMsgInteractive { overlayMsgInteractiveInteractive :: Bool } deriving (Show) overlayMagicNumber :: Num a => a overlayMagicNumber = 5 getNum32host :: (Num a) => Get a getNum32host = fromIntegral `fmap` getWord32host hGetOverlayMsg :: Handle -> IO OverlayMsg hGetOverlayMsg h = do str <- L.hGet h 8 when (L.length str < 8) $ throw $ userError "hGetOverlayMsg: couldn't read message header" let l = runGet getNum32host (L.drop 4 str) (L.splitAt 4 -> (tstr, bstr)) <- L.hGet h (4 + fromIntegral l) when (L.length bstr < l) $ throw $ userError "hGetOverlayMsg: couldn't read message body" let n = getNum32host s = (L8.unpack . fst . L.break (==0)) `fmap` getRemainingLazyByteString b = toEnum `fmap` getNum32host return . flip runGet bstr $ case runGet getWord32host tstr of 0 -> OverlayMsgInit <$> n <*> n 1 -> OverlayMsgShmem <$> s 2 -> OverlayMsgBlit <$> n <*> n <*> n <*> n 3 -> OverlayMsgActive <$> n <*> n <*> n <*> n 4 -> OverlayMsgPid <$> n 5 -> OverlayMsgFps <$> pure 0 -- (wordToFloat `fmap` getWord32host) 6 -> OverlayMsgInteractive <$> b _ -> throw $ userError "hGetOverlayMsg: unknown message type" hPutOverlayMsg :: Handle -> OverlayMsg -> IO () hPutOverlayMsg pipeHandle msg = do let n = putWord32host . fromIntegral s l str = putLazyByteString (L8.pack str) *> replicateM_ (l - length str) (putWord8 0) let str = runPut $ case msg of OverlayMsgInit w h -> n 0 *> n w *> n h OverlayMsgShmem p -> n 1 *> s 2048 p OverlayMsgBlit x y w h -> n 2 *> n x *> n y *> n w *> n h OverlayMsgActive x y w h -> n 3 *> n x *> n y *> n w *> n h OverlayMsgPid p -> n 4 *> n p OverlayMsgFps f -> n 4 *> n 0 -- putWord32host (floatToWord f) OverlayMsgInteractive i -> n 4 *> n (fromEnum i) let buf = runPut ( putWord32host overlayMagicNumber *> putWord32host (fromIntegral $ L.length str - 4) *> putLazyByteString str) L.hPut pipeHandle buf hFlush pipeHandle
ben0x539/hoverlay
OverlayMsg.hs
gpl-3.0
3,209
1
16
944
956
494
462
78
8
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeOperators #-} module OpenCog.Test where import OpenCog.Test.Template import OpenCog.AtomSpace import Test.SmallCheck.Series import Data.Typeable instance Monad m => Serial m TruthVal where series = cons2 SimpleTV \/ cons3 CountTV \/ cons2 FuzzyTV \/ cons3 ProbTV $(declareInstanceSerialAtom "../../opencog/atomspace/atom_types.script") uncurry0 = id uncurry1 = uncurry uncurry2 f (a,b,c) = (uncurry . uncurry) f ((a,b),c) myappGen2a :: (forall b. (Typeable bb, b <~ bb) => a -> Atom b -> r) -> (a, Gen bb) -> r myappGen2a f (a,Gen b) = f a b myappGen2b :: (forall a b. (Typeable a, Typeable b, a <~ aa,b <~ bb) => (Atom a -> Atom b -> r)) -> (Gen aa, Gen bb) -> r myappGen2b f (Gen a,Gen b) = f a b myappGen3a :: (forall b c. (Typeable b, Typeable c, b <~ bb,c <~ cc) => (a -> Atom b -> Atom c -> r)) -> (a,Gen bb, Gen cc) -> r myappGen3a f (a,Gen b,Gen c) = f a b c myappGen3b :: (forall a b c. (Typeable a,Typeable b, Typeable c, a <~ aa,b <~ bb,c <~ cc) => (Atom a -> Atom b -> Atom c -> r)) -> (Gen aa,Gen bb, Gen cc) -> r myappGen3b f (Gen a,Gen b,Gen c) = f a b c
cosmoharrigan/atomspace
tests/haskell/src/OpenCog/Test.hs
agpl-3.0
1,498
0
13
432
602
318
284
35
1
{-# LANGUAGE ExistentialQuantification #-} -------------------------------------------------------------------------------- {-| Module : Attributes Copyright : (c) Daan Leijen 2003 License : wxWindows Maintainer : wxhaskell-devel@lists.sourceforge.net Stability : provisional Portability : portable Widgets @w@ can have attributes of type @a@ represented by the type 'Attr' @w a@. An example of an attribute is 'Graphics.UI.WX.Classes.text' with type: > text :: Attr (Window a) String This means that any object derived from 'Window' has a 'Graphics.UI.WX.Classes.text' attribute of type 'String'. An attribute can be read with the 'get' function: > get w title :: IO String When an attribute is associated with a value, we call it a /property/ of type 'Prop' @w@. Properties are constructed by assigning a value to an attribute with the (':=') constructor: > text := "hello world" :: Prop (Window a) A list of properties can be set with the 'set' function: > set w [text := "Hi"] :: IO () The (':~') constructor is used to transform an attribute value with an update function. For example, the 'interval' on a timer can be doubled with the following expression. > set timer [interval :~ (*2)] The functions 'get', 'set', (':='), and (':~') are polymorphic and work for all widgets, but the @text@ attribute just works for windows. Many attributes work for different kind of objects and are organised into type classes. Actually, the real type of the 'Graphics.UI.WX.Classes.text' attribute is: > Textual w => Attr w String and 'Window' derived objects are part of this class: > instance Textual (Window a) But also menus and status fields: > instance Textual (Menu a) > instance Textual (StatusField) Sometimes, it is convenient to also get a reference to the object itself when setting a property. The operators ('::=') and ('::~') provide this reference. -} -------------------------------------------------------------------------------- module Graphics.UI.WX.Attributes ( -- * Attributes Attr, Prop((:=),(:~),(::=),(::~)), ReadAttr, WriteAttr, CreateAttr , get, set, swap , mapAttr, mapAttrW -- * Internal -- ** Attributes , newAttr, readAttr, writeAttr, nullAttr, constAttr, makeAttr -- ** Reflection , attrName, propName, containsProperty -- ** Reflective attributes , reflectiveAttr, createAttr, withProperty, findProperty , withStyleProperty, withStylePropertyNot -- *** Filter , PropValue(..) , filterProperty -- ** Cast , castAttr, castProp, castProps ) where import Graphics.UI.WX.Types import Data.Dynamic infixr 0 :=,:~,::=,::~ -- | A property of a widget @w@ is an attribute that -- is already associated with a value. . data Prop w = forall a. Attr w a := a -- ^ Assign a value to an attribute. | forall a. Attr w a :~ (a -> a) -- ^ Apply an update function to an attribute. | forall a. Attr w a ::= (w -> a) -- ^ Assign a value to an attribute with the widget as argument. | forall a. Attr w a ::~ (w -> a -> a) -- ^ Apply an update function to an attribute with the widget as an argument. -- | An attribute that should be specified at creation time. Just for documentation purposes. type CreateAttr w a = Attr w a -- | A read-only attribute. Just for documentation purposes. type ReadAttr w a = Attr w a -- | A write-only attribute. Just for documentation purposes. type WriteAttr w a = Attr w a -- | Widgets @w@ can have attributes of type @a@. data Attr w a = Attr String (Maybe (a -> Dynamic, Dynamic -> Maybe a)) -- name, dynamic conversion (w -> IO a) (w -> a -> IO ()) -- getter setter (w -> (a -> a) -> IO a) -- updater -- | Cast attributes. castAttr :: (v -> w) -> Attr w a -> Attr v a castAttr coerce (Attr name mbdyn getter setter upd) = Attr name mbdyn (\v -> getter (coerce v)) (\v x -> (setter (coerce v) x)) (\v f -> upd (coerce v) f) -- | Cast properties castProp :: (v -> w) -> Prop w -> Prop v castProp coerce prop = case prop of (attr := x) -> (castAttr coerce attr) := x (attr :~ f) -> (castAttr coerce attr) :~ f (attr ::= f) -> (castAttr coerce attr) ::= (\v -> f (coerce v)) (attr ::~ f) -> (castAttr coerce attr) ::~ (\v x -> f (coerce v) x) -- | Cast a list of properties. castProps :: (v -> w) -> [Prop w] -> [Prop v] castProps coerce props = map (castProp coerce) props -- | Create a /reflective/ attribute with a specified name: value can possibly -- retrieved using 'getPropValue'. Note: the use of this function is discouraged -- as it leads to non-compositional code. reflectiveAttr :: Typeable a => String -> (w -> IO a) -> (w -> a -> IO ()) -> Attr w a reflectiveAttr name getter setter = Attr name (Just (toDyn, fromDynamic)) getter setter updater where updater w f = do x <- getter w; setter w (f x); return x -- | Create a /reflective/ attribute with a specified name: value can possibly -- retrieved using 'getPropValue'. Note: the use of this function is discouraged -- as it leads to non-compositional code. createAttr :: Typeable a => String -> (w -> IO a) -> (w -> a -> IO ()) -> CreateAttr w a createAttr name getter setter = reflectiveAttr name getter setter -- | Create a new attribute with a specified name, getter, setter, and updater function. makeAttr :: String -> (w -> IO a) -> (w -> a -> IO ()) -> (w -> (a -> a) -> IO a) -> Attr w a makeAttr name getter setter updater = Attr name Nothing getter setter updater -- | Create a new attribute with a specified name, getter and setter function. newAttr :: String -> (w -> IO a) -> (w -> a -> IO ()) -> Attr w a newAttr name getter setter = makeAttr name getter setter updater where updater w f = do x <- getter w; setter w (f x); return x -- | Define a read-only attribute. readAttr :: String -> (w -> IO a) -> ReadAttr w a readAttr name getter = newAttr name getter (\w x -> ioError (userError ("attribute '" ++ name ++ "' is read-only."))) -- | Define a write-only attribute. writeAttr :: String -> (w -> a -> IO ()) -> WriteAttr w a writeAttr name setter = newAttr name (\w -> ioError (userError ("attribute '" ++ name ++ "' is write-only."))) setter -- | A dummy attribute. nullAttr :: String -> WriteAttr w a nullAttr name = writeAttr name (\w x -> return ()) -- | A constant attribute. constAttr :: Typeable a => String -> a -> Attr w a constAttr name x = newAttr name (\w -> return x) (\w x -> return ()) -- | (@mapAttr get set attr@) maps an attribute of @Attr w a@ to -- @Attr w b@ where (@get :: a -> b@) is used when the attribute is -- requested and (@set :: a -> b -> a@) is applied to current -- value when the attribute is set. mapAttr :: (a -> b) -> (a -> b -> a) -> Attr w a -> Attr w b mapAttr get set (Attr name reflect getter setter updater) = Attr name Nothing (\w -> do a <- getter w; return (get a)) (\w b -> do a <- getter w; setter w (set a b)) (\w f -> do a <- updater w (\a -> set a (f (get a))); return (get a)) -- | (@mapAttrW conv attr@) maps an attribute of @Attr w a@ to -- @Attr v a@ where (@conv :: v -> w@) is used to convert a widget -- @v@ into a widget of type @w@. mapAttrW :: (v -> w) -> Attr w a -> Attr v a mapAttrW f attr = castAttr f attr -- | Get the value of an attribute -- -- > t <- get w text -- get :: w -> Attr w a -> IO a get w (Attr name reflect getter setter updater) = getter w -- | Set a list of properties. -- -- > set w [text := "Hi"] -- set :: w -> [Prop w] -> IO () set w props = mapM_ setprop props where setprop ((Attr name reflect getter setter updater) := x) = setter w x setprop ((Attr name reflect getter setter updater) :~ f) = do updater w f; return () setprop ((Attr name reflect getter setter updater) ::= f) = setter w (f w) setprop ((Attr name reflect getter setter updater) ::~ f) = do updater w (f w); return () -- | Set the value of an attribute and return the old value. swap :: w -> Attr w a -> a -> IO a swap w (Attr name reflect getter setter updater) x = updater w (const x) -- | Retrieve the name of an attribute attrName :: Attr w a -> String attrName (Attr name _ _ _ _) = name -- | Retrieve the name of a property. propName :: Prop w -> String propName (attr := x) = attrName attr propName (attr :~ f) = attrName attr propName (attr ::= f) = attrName attr propName (attr ::~ f) = attrName attr -- | Is a certain property in a list of properties? containsProperty :: Attr w a -> [Prop w] -> Bool containsProperty attr props = containsPropName (attrName attr) props -- | Is a certain property in a list of properties? containsPropName :: String -> [Prop w] -> Bool containsPropName name props = any (\p -> propName p == name) props -- | Property value: used when retrieving a property from a list. data PropValue a = PropValue a | PropModify (a -> a) | PropNone instance Show a => Show (PropValue a) where show (PropValue x) = "PropValue " ++ show x show (PropModify f) = "PropModify" show (PropNone) = "PropNone" -- | Retrieve the value of a property and the list with the property removed. filterProperty :: Typeable a => Attr w a -> [Prop w] -> (PropValue a, [Prop w]) filterProperty (Attr name _ _ _ _) props = walk [] PropNone props where -- Daan: oh, how a simple thing like properties can result into this... ;-) walk :: Typeable a => [Prop w] -> PropValue a -> [Prop w] -> (PropValue a, [Prop w]) walk acc res props = case props of -- Property setter found. (((Attr attr (Just (todyn,fromdyn)) _ _ _) := x):rest) | name == attr -> case fromDynamic (todyn x) of Just x -> walk acc (PropValue x) rest Nothing -> walk acc res props -- Property modifier found. (((Attr attr (Just (todyn,fromdyn)) _ _ _) :~ f):rest) | name == attr -> let dynf x = case fromdyn (toDyn x) of Just xx -> case fromDynamic (todyn (f xx)) of Just y -> y Nothing -> x -- identity Nothing -> x -- identity in case res of PropValue x -> walk acc (PropValue (dynf x)) rest PropModify g -> walk acc (PropModify (dynf . g)) rest PropNone -> walk acc (PropModify dynf) rest -- Property found, but with the wrong arguments (((Attr attr _ _ _ _) := _):rest) | name == attr -> stop (((Attr attr _ _ _ _) :~ _):rest) | name == attr -> stop (((Attr attr _ _ _ _) ::= _):rest) | name == attr -> stop (((Attr attr _ _ _ _) ::~ _):rest) | name == attr -> stop -- Defaults (prop:rest) -> walk (prop:acc) res rest [] -> stop where stop = (res, reverse acc ++ props) -- | Try to find a property value and call the contination function with that value -- and the property list witht the searched property removed. If the property is not -- found, use the default value and the unchanged property list. withProperty :: Typeable a => Attr w a -> a -> (a -> [Prop w] -> b) -> [Prop w] -> b withProperty attr def cont props = case filterProperty attr props of (PropValue x, ps) -> cont x ps (PropModify f, ps) -> cont (f def) ps (PropNone, ps) -> cont def ps -- | Try to find a property value. Return |Nothing| if not found at all. findProperty :: Typeable a => Attr w a -> a -> [Prop w] -> Maybe (a,[Prop w]) findProperty attr def props = case filterProperty attr props of (PropValue x, ps) -> Just (x,ps) (PropModify f, ps) -> Just (f def,ps) (PropNone, ps) -> Nothing -- | Transform the properties based on a style property. withStyleProperty :: Attr w Bool -> Style -> ([Prop w] -> Style -> a) -> [Prop w] -> Style -> a withStyleProperty prop flag = withStylePropertyEx prop (bitsSet flag) (\isSet style -> if isSet then (style .+. flag) else (style .-. flag)) -- | Transform the properties based on a style property. The flag is interpreted negatively, i.e. |True| -- removes the bit instead of setting it. withStylePropertyNot :: Attr w Bool -> Style -> ([Prop w] -> Style -> a) -> [Prop w] -> Style -> a withStylePropertyNot prop flag = withStylePropertyEx prop (not . bitsSet flag) (\isSet style -> if isSet then (style .-. flag) else (style .+. flag)) -- | Transform the properties based on a style property. withStylePropertyEx :: Attr w Bool -> (Style -> Bool) -> (Bool -> Style -> Style) -> ([Prop w] -> Style -> a) -> [Prop w] -> Style -> a withStylePropertyEx prop def transform cont props style = case filterProperty prop props of (PropValue x, ps) -> cont ps (transform x style) (PropModify f, ps) -> cont ps (transform (f (def style)) style) (PropNone, ps) -> cont ps style
thielema/wxhaskell
wx/src/Graphics/UI/WX/Attributes.hs
lgpl-2.1
13,292
2
24
3,528
3,754
1,959
1,795
168
13
{-# LANGUAGE RecordWildCards #-} import Control.Monad (msum) import Data.List (intercalate) {- port from http://www.joshondesign.com/2014/09/17/rustlang -} data Vector = Vector {x,y,z :: Double} data Ray = Ray {orig,dir :: Vector} data Color = Color {r,g,b :: Double} data Sphere = Sphere {center :: Vector, radius :: Double, sphereColor :: Color} data Light = Light {position :: Vector, lightColor :: Color} light :: Light light = Light {position=Vector 0.7 (-1) 1.7, lightColor=Color 1 1 1} scene :: [Sphere] scene = [ Sphere {center=Vector (-1) 0 3, radius=0.3, sphereColor=Color 1 0 0} , Sphere {center=Vector 0 0 3, radius=0.8, sphereColor=Color 0 1 0} , Sphere {center=Vector 1 0 3, radius=0.3, sphereColor=Color 0 0 1}] (<**>) :: Vector -> Double -> Vector Vector{..} <**> s = Vector {x=x*s,y=y*s,z=z*s} scale :: Color -> Double -> Color scale Color{..} s = Color {r=r*s,g=g*s,b=b*s} (<+>) :: Vector -> Vector -> Vector (Vector x1 y1 z1) <+> (Vector x2 y2 z2) = Vector {x=x1+x2,y=y1+y2,z=z1+z2} plus :: Color -> Color -> Color plus (Color r1 g1 b1) (Color r2 g2 b2) = Color {r=r1+r2,g=g1+g2,b=b1+b2} (<->) :: Vector -> Vector -> Vector (Vector x1 y1 z1) <-> (Vector x2 y2 z2) = Vector {x=x1-x2,y=y1-y2,z=z1-z2} (<.>) :: Vector -> Vector -> Double (Vector x1 y1 z1) <.> (Vector x2 y2 z2) = x1*x2 + y1*y2 + z1*z2 magnitude :: Vector -> Double magnitude v = sqrt (v <.> v) normalize :: Vector -> Vector normalize v = v <**> (1 / magnitude v) normal :: Sphere -> Vector -> Vector normal Sphere{..} pt = normalize $ pt <-> center shapePixel :: Ray -> Sphere -> Double -> Int shapePixel Ray{..} obj@Sphere{..} val = let pai = orig <+> (dir <**> val) Color r g b = diffuseShading pai obj light in ceiling $ (r + g + b) * 2 intersectSphere :: Ray -> Sphere -> Maybe (Sphere, Double) intersectSphere Ray{..} obj@Sphere{..} = let l = center <-> orig tca = l <.> dir d2 = l <.> l - tca * tca r2 = radius * radius thc = sqrt $ r2 - d2 t0 = tca - thc in if tca < 0 || d2 > r2 || t0 > 10000 then Nothing else Just (obj, t0) diffuseShading :: Vector -> Sphere -> Light -> Color diffuseShading pai obj@Sphere{..} Light{..} = let n = normal obj pai lam1 = normalize (position <-> pai) <.> n lam2 = min 1 (max 0 lam1) in (lightColor `scale`(lam2 * 0.5)) `plus` (sphereColor `scale` 0.3) render :: Int -> Int -> [String] render w h = [[render' i j | i <- [0 .. w-1]] | j <- [0 .. h-1]] where (fw, fh) = (fromIntegral w, fromIntegral h) lut = ".-+*XM" render' i j = let (fi, fj) = (fromIntegral i, fromIntegral j) ray = Ray { orig=Vector 0 0 0 , dir= normalize $ Vector ((fi-fw/2)/fw) ((fj-fh/2)/fh) 1 } in case msum [intersectSphere ray obj | obj <- scene] of Nothing -> ' ' Just (obj, val) -> lut !! shapePixel ray obj val main :: IO () main = putStrLn . intercalate "\n" $ render (20*4) (10*4) {- Output: ++*** ++++*********XXXX** -+++++********XXXXXXXXXXX --++++++********XXXXXXXXXXXXXX* ----++++++*********XXXXXXXXXXXXXXX* ----++++++++*********XXXXXXXXXXXXXXX* -----+++++++++**********XXXXXXXXXXXXX** + -------+++++++++************XXXXXXXXXX*** * ++****XXXXX--------++++++++++***************************XXXXXXXX* --++****XXXXXXX-------+++++++++++************************XXXXXXXXX*** --+++****XXXXXXX*--------++++++++++++*******************++**XXXXXX****+ ---+++*****XXXXX*---------++++++++++++++***************+++***********++ ----++++*********-----------++++++++++++++++++*****++++++-++******++++- -----+++++****+--------------+++++++++++++++++++++++++++-+++++++++--- ------+++++-------------------+++++++++++++++++++++++------------ - ----------------------+++++++++++++++++-- - ----------------------------+++++------ ------------------------------------- ----------------------------------- ------------------------------- ------------------------- ------------------- ----- -}
scturtle/fun.hs
raytracer.hs
unlicense
4,439
0
19
1,212
1,522
832
690
66
2
module GPartialApplication (koans) where import Test.Hspec import Test.HUnit (assertBool, assertEqual) import Koan __ = error "Replace __ with a valid value" -- the `add` function takes two parameters and adds the results together add x y = x + y koanSimpleApplication = koan "simple standard application" $ do add 1 2 == 3 koanPartiallyApplied = koan "simple partial application" $ do -- we'll take the `add` function, supply 1 as the first parameter, -- and assign the 'partially applied' function to `addMore` -- 'partially applied functions' cant execute until all -- parameters have been satisfied let addMore = add 1 addMore 2 == 3 koanMultipleApplies = koan "multiple partially applied functions" $ do let x = add 2 let y = add 2 y (x 2) == 6 koans :: Koan koans = describe "Partial Application" $ do koanSimpleApplication koanPartiallyApplied koanMultipleApplies
gregberns/HaskellKoans
src/koans/GPartialApplication.hs
apache-2.0
899
0
11
169
193
96
97
20
1
module FRP.Extra.Yampa where import Control.Arrow import FRP.Yampa futureDSwitch :: SF a (b, Event c) -> (c -> SF a b) -> SF a b futureDSwitch sf cont = dSwitch (sf >>> (arr id *** notYet)) cont
no-moree-ria10/utsuEater
src/FRP/Extra/Yampa.hs
apache-2.0
199
0
10
40
93
49
44
5
1
import Data.List import Data.Maybe c [i1,u1,a1,p1] [i2,u2,a2,p2] = if ca /= EQ then ca else if cp /= EQ then cp else ci where ca = compare a2 a1 cp = compare p1 p2 ci = compare i1 i2 r1 h@[i,u,a,p] t = if l < 3 then (h:t) else t where l = length $ filter (\[_,uu,_,_] -> uu == u) t r2 h@[i,u,a,p] t = if l < 2 then (h:t) else t where l = length $ filter (\[_,uu,_,_] -> uu == u) t r3 h@[i,u,a,p] t = if l < 1 then (h:t) else t where l = length $ filter (\[_,uu,_,_] -> uu == u) t chk [] t = t chk a@(h:r) t | l < 10 = chk r t1 | l < 20 = chk r t2 | l < 26 = chk r t3 | otherwise = t where l = length t t1= r1 h t t2= r2 h t t3= r3 h t ans' d = let s = sortBy c d a = map head $ reverse $ chk s [] in a ans ([0]:_) = [] ans ([n]:x) = let d = take n x r = drop n x in (ans' d):(ans r) main = do c <- getContents let i = map (map read) $ map words $ lines c :: [[Int]] o = ans i mapM_ print $ concat o
a143753/AOJ
1043.hs
apache-2.0
1,150
0
14
487
686
365
321
44
3
{-# LANGUAGE RecordWildCards #-} module Choice where import Text.Parsec.Char (char, satisfy) import Text.Parsec.Combinator (sepBy, many1, notFollowedBy, option) import Text.Parsec.Prim (try, many) import ClassyPrelude hiding (try) import JEPFormula import Common -- most of the parsers are stubbed out -- not sure how to deal with -- choices in general atm. data ChoiceTag = ChooseLanguageTag [ChooseLanguage] | ChooseNumberChoicesTag Choices | ChooseNumberTag ChooseNumber | ChooseManyNumbersTag ChooseManyNumbers | ChooseNoChoice () | ChooseSkillTag [ChooseSkill] | ChooseEqBuilder EqBuilder | ChooseSchools [ChooseSchoolType] | ChooseString StringBuilder | ChoosePCStat [PCStat] | ChooseUserInput UserInput -- stubbed out | ChooseSpells () | ChooseSpellLevel () | ChooseAbility () | ChooseClass () | ChooseEquipment () | ChooseFeat () | ChooseFeatSelection () | ChooseStatBonus () | ChooseSkillBonus () | ChooseRace () | ChooseArmorProfBonus () | ChooseWeaponProfBonus () | ChooseShieldProfBonus () deriving (Show, Eq) -- not fully implemented data ChooseLanguage = ChoiceLanguage String | ChoiceLanguageType String deriving (Show, Eq) parseChooseLanguage :: PParser [ChooseLanguage] parseChooseLanguage = do _ <- labeled "CHOOSE:LANG|" parseChoiceLang `sepBy` char ',' where parseChoiceLang = ChoiceLanguageType <$> (labeled "TYPE=" *> parseString) <|> ChoiceLanguage <$> parseString parseChooseNoChoice :: PParser () parseChooseNoChoice = () <$ labeled "CHOOSE:NOCHOICE" -- not fully implemented data ChoiceType = AllChoices | ChoiceType String | ChoiceTitle String -- this is probably incorrect | ChoiceName String deriving (Show, Eq) data Choices = Choices { choiceNumber :: Int , choiceSelection :: String , choices :: [ChoiceType] } deriving (Show, Eq) parseChooseNumChoices :: PParser Choices parseChooseNumChoices = do _ <- labeled "CHOOSE:NUMCHOICES=" choiceNumber <- parseInteger <* char '|' choiceSelection <- parseString choices <- parseChoicesIfSelection choiceSelection return Choices { .. } where parseChoicesIfSelection "NOCHOICE" = return [] parseChoicesIfSelection _ = char '|' *> parseChoiceString `sepBy` char '|' parseChoiceString = AllChoices <$ labeled "ALL" <|> (labeled "TYPE=" *> (ChoiceType <$> parseString)) <|> (labeled "TITLE=" *> (ChoiceTitle <$> parseString)) <|> (ChoiceName <$> parseString) -- not fully implemented -- CHOOSE:NUMBER|v|w|x|y|z -- not implemented. (NOSIGN/MULTIPLE seems to be undocumented) data ChooseNumber = ChooseNumber { chooseMin :: Formula , chooseMax :: Formula , chooseTitle :: String } deriving (Show, Eq) parseChooseNumber :: PParser ChooseNumber parseChooseNumber = do _ <- labeled "CHOOSE:NUMBER" chooseMin <- labeled "|MIN=" *> parseFormula chooseMax <- labeled "|MAX=" *> parseFormula chooseTitle <- labeled "|TITLE=" *> parseStringSemicolon return ChooseNumber { .. } where parseStringSemicolon = many1 $ satisfy $ inClass "-A-Za-z0-9_ &+,./:?!%#'()[]~;" data ChooseManyNumbers = ChooseManyNumbers { chooseManyNumbers :: [Int] , chooseManyMultiple :: Bool , chooseManyTitle :: String } deriving (Show, Eq) parseChooseManyNumbers :: PParser ChooseManyNumbers parseChooseManyNumbers = do _ <- labeled "CHOOSE:NUMBER" chooseManyNumbers <- parseInteger `sepBy` char '|' chooseManyMultiple <- option False (True <$ labeled "MULTIPLE|") chooseManyTitle <- labeled "|TITLE=" *> parseString return ChooseManyNumbers { .. } -- not fully implemented data ChooseSkill = ChoiceSkill String | ChoiceSkillType String | ChoiceSkillTitle String | ChoiceSkillFeat String | ChoiceSkillRanks Int deriving (Show, Eq) parseChooseSkill :: PParser [ChooseSkill] parseChooseSkill = do _ <- labeled "CHOOSE:SKILL|" parseChoiceSkill `sepBy` char '|' where parseChoiceSkill = ChoiceSkillType <$> (labeled "TYPE=" *> parseString) <|> ChoiceSkillTitle <$> (labeled "TITLE=" *> parseString) <|> ChoiceSkillFeat <$> (labeled "FEAT=" *> parseString) <|> ChoiceSkillRanks <$> (labeled "RANKS=" *> parseInteger) <|> ChoiceSkill <$> parseString -- CHOOSE:EQBUILDER.SPELL|w|x|y|z -- w is optional text -- x is optional spell type (not used) -- y is optional minimum level -- z is optional maximum level data EqBuilder = EqBuilder { eqBuilderText :: Maybe String , eqBuilderMinimumLevel :: Formula , eqBuilderMaximumLevel :: Formula } deriving (Show, Eq) parseChooseEqBuilder :: PParser EqBuilder parseChooseEqBuilder = do _ <- labeled "CHOOSE:EQBUILDER.SPELL" eqBuilderText <- tryOption $ char '|' *> parseString <* char '|' eqBuilderMinimumLevel <- option (Number 0) $ parseFormula <* char '|' eqBuilderMaximumLevel <- option (Variable "MAX_LEVEL") parseFormula return EqBuilder { .. } -- CHOOSE:SCHOOLS|x|x|.. -- x is school name or feat or ALL data ChooseSchoolType = SchoolName String | FeatName String | AllSchools deriving (Show, Eq) parseChooseSchools :: PParser [ChooseSchoolType] parseChooseSchools = labeled "CHOOSE:SCHOOLS|" *> parseSchoolTypes `sepBy` char '|' where parseSchoolTypes = (labeled "FEAT=" *> (FeatName <$> parseString)) <|> (AllSchools <$ labeled "ALL") <|> (SchoolName <$> parseString) -- CHOOSE:PCSTAT|x|x|... -- x is stat abbrevation, stat type or ALL data PCStat = StatAbbrevation String | StatType String | NotStatType String | AllStats deriving (Show, Eq) parseChoosePCStat :: PParser [PCStat] parseChoosePCStat = labeled "CHOOSE:PCSTAT|" *> parsePCStat `sepBy` char '|' where parsePCStat = (labeled "TYPE=" *> (StatType <$> parseString)) <|> (labeled "!TYPE=" *> (NotStatType <$> parseString)) <|> (AllStats <$ labeled "ALL") <|> (StatAbbrevation <$> parseString) -- CHOOSE:STRING|x|x..|y -- x is choice to be offered -- y is TITLE=text data ChooseStringType = ChooseStringText String | ChooseStringFeat String deriving (Show, Eq) data StringBuilder = StringBuilder { stringBuilderChoices :: [ChooseStringType] , stringBuilderTitle :: String } deriving (Show, Eq) parseChooseString :: PParser StringBuilder parseChooseString = do _ <- labeled "CHOOSE:STRING" stringBuilderChoices <- many $ try $ char '|' *> parseChoiceString stringBuilderTitle <- option "Please pick a choice" $ labeled "|TITLE=" *> parseString return StringBuilder { .. } where parseChoiceString = notFollowedBy (labeled "TITLE=") *> parseChooseStringType parseChooseStringType = (labeled "FEAT=" *> (ChooseStringFeat <$> parseString)) <|> ChooseStringText <$> parseString -- CHOOSE:USERINPUT|x|y -- x is number of inputs -- y is chooser dialog title data UserInput = UserInput { numberOfInputs :: Int , userInputTitle :: String } deriving (Show, Eq) parseChooseUserInput :: PParser UserInput parseChooseUserInput = do _ <- labeled "CHOOSE:USERINPUT|" numberOfInputs <- option 1 parseInteger userInputTitle <- labeled "TITLE=" *> parseString return UserInput { .. } -- CHOOSE:ABILITY|w|x|y|y[x]|y[x,x]|x,y,y[x],y[x,x] -- not implemented. parseChooseAbility :: PParser () parseChooseAbility = () <$ (labeled "CHOOSE:ABILITY|" >> restOfTag) -- CHOOSE:CLASS|x|y|y[x]|y[x,x]|x,y,y[x],y[x,x] -- not implemented. parseChooseClass :: PParser () parseChooseClass = () <$ (labeled "CHOOSE:CLASS|" >> restOfTag) -- CHOOSE:EQUIPMENT -- not implemented. parseChooseEquipment :: PParser () parseChooseEquipment = () <$ (labeled "CHOOSE:EQUIPMENT|" >> restOfTag) -- CHOOSE:FEAT|w|x|y|y[x]|y[x,x]|x,y,y[x],y[x,x] -- not implemented. parseChooseFeat :: PParser () parseChooseFeat = () <$ (labeled "CHOOSE:FEAT|" >> restOfTag) -- CHOOSE:FEATSELECTION|w|x|y|y[z]|y[x,x]|x,y,y[x],y[x,x] -- not implemented. parseChooseFeatSelection :: PParser () parseChooseFeatSelection = () <$ (labeled "CHOOSE:FEATSELECTION|" >> restOfTag) -- CHOOSE:SPELLS|x,y,y[z]|x|y|y[z;z] -- not implemented. parseChooseSpells :: PParser () parseChooseSpells = () <$ (labeled "CHOOSE:SPELLS|" >> restOfTag) -- CHOOSE:SPELLLEVEL|w|x|y|z|x|y|z -- not implemented. parseChooseSpellLevel :: PParser () parseChooseSpellLevel = () <$ (labeled "CHOOSE:SPELLLEVEL|" >> restOfTag) -- CHOOSE:STATBONUS|w|x|y|z -- not implemented. parseChooseStatBonus :: PParser () parseChooseStatBonus = () <$ (labeled "CHOOSE:STATBONUS|" >> restOfTag) -- CHOOSE:SKILLBONUS|w|x|y|z -- not implemented. parseChooseSkillBonus :: PParser () parseChooseSkillBonus = () <$ (labeled "CHOOSE:SKILLBONUS|" >> restOfTag) -- CHOOSE:RACE|x|y|y[x]|y[x,x]|x,y,y[x],y[x,x] -- not implemented. parseChooseRace :: PParser () parseChooseRace = () <$ (labeled "CHOOSE:RACE|" >> restOfTag) -- CHOOSE:ARMORPROFICIENCY|x -- not implemented (or documented). parseChooseArmorProfBonus :: PParser () parseChooseArmorProfBonus = () <$ (labeled "CHOOSE:ARMORPROFICIENCY|" >> restOfTag) -- CHOOSE:WEAPONPROFICIENCY|x -- not implemented (or documented). parseChooseWeaponProfBonus :: PParser () parseChooseWeaponProfBonus = () <$ (labeled "CHOOSE:WEAPONPROFICIENCY|" >> restOfTag) -- CHOOSE:SHIELDPROFICIENCY|x -- not implemented (or documented). parseChooseShieldProfBonus :: PParser () parseChooseShieldProfBonus = () <$ (labeled "CHOOSE:SHIELDPROFICIENCY|" >> restOfTag) parseChoice :: PParser ChoiceTag parseChoice = ChooseLanguageTag <$> parseChooseLanguage <|> ChooseNumberChoicesTag <$> parseChooseNumChoices -- if this CHOOSE:NUMBER fails, try the next one <|> try (ChooseNumberTag <$> parseChooseNumber) <|> try (ChooseManyNumbersTag <$> parseChooseManyNumbers) <|> ChooseSkillTag <$> parseChooseSkill <|> ChooseNoChoice <$> parseChooseNoChoice <|> ChooseEqBuilder <$> parseChooseEqBuilder <|> ChooseString <$> parseChooseString <|> ChoosePCStat <$> parseChoosePCStat <|> ChooseUserInput <$> parseChooseUserInput <|> ChooseSchools <$> parseChooseSchools <|> ChooseSpells <$> parseChooseSpells <|> ChooseSpellLevel <$> parseChooseSpellLevel <|> ChooseAbility <$> parseChooseAbility <|> ChooseClass <$> parseChooseClass <|> ChooseEquipment <$> parseChooseEquipment <|> ChooseFeat <$> parseChooseFeat <|> ChooseFeatSelection <$> parseChooseFeatSelection <|> ChooseStatBonus <$> parseChooseStatBonus <|> ChooseSkillBonus <$> parseChooseSkillBonus <|> ChooseRace <$> parseChooseRace <|> ChooseArmorProfBonus <$> parseChooseArmorProfBonus <|> ChooseWeaponProfBonus <$> parseChooseWeaponProfBonus <|> ChooseShieldProfBonus <$> parseChooseShieldProfBonus
gamelost/pcgen-rules
src/Choice.hs
apache-2.0
11,931
0
49
3,048
2,358
1,260
1,098
210
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} module Openshift.Apis ( api , API ) where import Openshift.OapivApi (OapivApi) import Data.Proxy type API = OapivApi api :: Proxy API api = Proxy
minhdoboi/deprecated-openshift-haskell-api
openshift/lib/Openshift/Apis.hs
apache-2.0
318
0
5
62
53
34
19
13
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QVariant.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:36 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Core.QVariant ( QVariantType, eBool, eInt, eUInt, eLongLong, eULongLong, eDouble, eChar, eMap, eString, eStringList, eByteArray, eBitArray, eDate, eDateTime, eUrl, eLocale, eRect, eRectF, eSizeF, eLineF, ePoint, ePointF, eLastCoreType, ePixmap, eBrush, ePalette, eIcon, eImage, ePolygon, eRegion, eBitmap, eSizePolicy, eKeySequence, eTextLength, eMatrix, eTransform, eLastGuiType, eLastType ) where import Foreign.C.Types import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CQVariantType a = CQVariantType a type QVariantType = QEnum(CQVariantType Int) ieQVariantType :: Int -> QVariantType ieQVariantType x = QEnum (CQVariantType x) instance QEnumC (CQVariantType Int) where qEnum_toInt (QEnum (CQVariantType x)) = x qEnum_fromInt x = QEnum (CQVariantType x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> QVariantType -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () instance QeInvalid QVariantType where eInvalid = ieQVariantType $ 0 eBool :: QVariantType eBool = ieQVariantType $ 1 eInt :: QVariantType eInt = ieQVariantType $ 2 eUInt :: QVariantType eUInt = ieQVariantType $ 3 eLongLong :: QVariantType eLongLong = ieQVariantType $ 4 eULongLong :: QVariantType eULongLong = ieQVariantType $ 5 eDouble :: QVariantType eDouble = ieQVariantType $ 6 eChar :: QVariantType eChar = ieQVariantType $ 7 eMap :: QVariantType eMap = ieQVariantType $ 8 instance QeList QVariantType where eList = ieQVariantType $ 9 eString :: QVariantType eString = ieQVariantType $ 10 eStringList :: QVariantType eStringList = ieQVariantType $ 11 eByteArray :: QVariantType eByteArray = ieQVariantType $ 12 eBitArray :: QVariantType eBitArray = ieQVariantType $ 13 eDate :: QVariantType eDate = ieQVariantType $ 14 instance QeTime QVariantType where eTime = ieQVariantType $ 15 eDateTime :: QVariantType eDateTime = ieQVariantType $ 16 eUrl :: QVariantType eUrl = ieQVariantType $ 17 eLocale :: QVariantType eLocale = ieQVariantType $ 18 eRect :: QVariantType eRect = ieQVariantType $ 19 eRectF :: QVariantType eRectF = ieQVariantType $ 20 instance QeSize QVariantType where eSize = ieQVariantType $ 21 eSizeF :: QVariantType eSizeF = ieQVariantType $ 22 instance QeLine QVariantType where eLine = ieQVariantType $ 23 eLineF :: QVariantType eLineF = ieQVariantType $ 24 ePoint :: QVariantType ePoint = ieQVariantType $ 25 ePointF :: QVariantType ePointF = ieQVariantType $ 26 instance QeRegExp QVariantType where eRegExp = ieQVariantType $ 27 eLastCoreType :: QVariantType eLastCoreType = ieQVariantType $ 27 instance QeFont QVariantType where eFont = ieQVariantType $ 64 ePixmap :: QVariantType ePixmap = ieQVariantType $ 65 eBrush :: QVariantType eBrush = ieQVariantType $ 66 instance QeColor QVariantType where eColor = ieQVariantType $ 67 ePalette :: QVariantType ePalette = ieQVariantType $ 68 eIcon :: QVariantType eIcon = ieQVariantType $ 69 eImage :: QVariantType eImage = ieQVariantType $ 70 ePolygon :: QVariantType ePolygon = ieQVariantType $ 71 eRegion :: QVariantType eRegion = ieQVariantType $ 72 eBitmap :: QVariantType eBitmap = ieQVariantType $ 73 instance QeCursor QVariantType where eCursor = ieQVariantType $ 74 eSizePolicy :: QVariantType eSizePolicy = ieQVariantType $ 75 eKeySequence :: QVariantType eKeySequence = ieQVariantType $ 76 instance QePen QVariantType where ePen = ieQVariantType $ 77 eTextLength :: QVariantType eTextLength = ieQVariantType $ 78 instance QeTextFormat QVariantType where eTextFormat = ieQVariantType $ 79 eMatrix :: QVariantType eMatrix = ieQVariantType $ 80 eTransform :: QVariantType eTransform = ieQVariantType $ 81 eLastGuiType :: QVariantType eLastGuiType = ieQVariantType $ 81 instance QeUserType QVariantType where eUserType = ieQVariantType $ 127 eLastType :: QVariantType eLastType = ieQVariantType $ -1
keera-studios/hsQt
Qtc/Enums/Core/QVariant.hs
bsd-2-clause
5,599
0
18
1,061
1,413
772
641
196
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} {- - The actual Earley-style parser. -} module NLP.LTAG.Early3.Earley where import Control.Applicative ((<$>)) import Control.Monad (guard) import qualified Control.Monad.State.Strict as St import Control.Monad.Trans.Class (lift) import Data.Maybe (maybeToList) import qualified Data.Set as S import qualified Data.IntMap.Strict as I import qualified Data.Sequence as Seq import Data.Sequence (ViewL(..), (|>)) import qualified Pipes as P import NLP.LTAG.Early3.Core import qualified NLP.LTAG.Early3.Rule as R -------------------------------------------------- -- CHART STATE -------------------------------------------------- -- | Parsing state. data State n t -- | Regular context-free rule. = Init { -- | The head of the rule represented by the state. root :: Sym n -- | Starting position. , beg :: Pos -- | The list of elements yet to process. , right :: [Lab n t] } -- | Auxiliary rule (processing left part) | Aux1 { -- | The head of the rule represented by the state. root :: Sym n -- | Starting position. , beg :: Pos -- | Following the spine of the auxiliary tree. -- `Nothing' if foot node. , down :: Maybe (Sym n) -- | The list of elements yet to process. , right :: [Lab n t] -- | The real right side of the rule, so far not even -- touched. , rest :: [Lab n t] } -- | Auxiliary rule (processing right part) | Aux2 { -- | The head of the rule represented by the state. root :: Sym n -- | Starting position. , beg :: Pos -- | Gap starting position. , gapBeg :: Pos -- | Gap ending position. , gapEnd :: Pos -- | Following the spine of the auxiliary tree. -- `Nothing' if foot node. , down :: Maybe (Sym n) -- | The list of elements yet to process. , right :: [Lab n t] } -- | Auxiliary rule (only left part) | AuxL { -- | The head of the rule represented by the state. root :: Sym n -- | Starting position. , beg :: Pos -- | Following the spine of the auxiliary tree. -- `Nothing' if foot node. , down :: Maybe (Sym n) -- | The list of elements yet to process. , right :: [Lab n t] } deriving (Show, Eq, Ord) -- -- | Parsing state: processed auxiliary rule elements and the elements -- -- yet to process. -- -- TODO: what about rules with left side being empty? -- -- TODO: what about rules with both sides being empty? -- data StateL n t = StateL { -- -- | The head of the rule represented by the state. -- rootL :: Sym n -- -- | Starting position. -- , begL :: Pos -- -- -- | The list of processed elements of the rule. -- -- -- (Stored in the inverse order?) -- -- , leftL :: [Lab n t] -- -- | The list of elements yet to process. -- , rightL :: [Lab n t] -- -- | The real right side of the rule, so far not even -- -- touched. -- , restL :: [Lab n t] -- } deriving (Show, Eq, Ord) -- -- -- -- | Parsing state: processed auxiliary rule elements and the elements -- -- yet to process. Processing the second part of the rule. -- data StateR n t = StateR { -- -- | The head of the rule represented by the state. -- rootR :: Sym n -- -- | Starting position (left part) -- , begR :: Pos -- -- | Ending position (left part) -- , endR :: Pos -- -- | Starting position (right part) -- , newEndR :: Pos -- -- -- | The list of processed elements of the rule. -- -- -- (Stored in the inverse order?) -- -- , leftR :: [Lab n t] -- -- | The list of elements yet to process. -- , rightR :: [Lab n t] -- -- -- | The left part of the rule, already processed and -- -- -- spanning (begR, endR). -- -- , doneR :: [Lab n t] -- } deriving (Show, Eq, Ord) -- -- -- -- | Generic state. -- type State n t = Three (StateI n t) (StateL n t) (StateR n t) -- -- -- -- | Generic function which tells what the state still expects on -- -- the right. -- right :: State n t -> [Lab n t] -- right (One StateI{..}) = rightI -- right (Two StateL{..}) = rightL -- right (Thr StateR{..}) = rightR -- -- -- -- | Consume the given terminal if the rules actually expects it. -- -- Return the rule after consumption. -- consume :: Eq t => t -> State n t -> Maybe (State n t) -- consume t (One st@StateI{..}) = do -- (x, xs) <- decoList rightI -- guard $ labEqTerm t x -- return $ One $ st {rightI = xs} -- consume t (Two st@StateL{..}) = do -- (x, xs) <- decoList rightL -- guard $ labEqTerm t x -- return $ Two $ st {rightL = xs} -- consume t (Thr st@StateR{..}) = do -- (x, xs) <- decoList rightR -- guard $ labEqTerm t x -- return $ Thr $ st {rightR = xs} -------------------------------------------------- -- CHART -------------------------------------------------- -- | Chart entry -- all states ending on the given -- position. type Entry n t = S.Set (State n t) -- | A chart is a map from indiced to chart entries. type Chart n t = I.IntMap (Entry n t) -- | N-th position of the chart. (!?) :: Chart n t -> Int -> Entry n t chart !? k = case I.lookup k chart of Just e -> e Nothing -> error $ "!?: no such index in the chart" -- -- | Complex, "dual" chart entry -- all states ending on the -- -- given position. -- type EntryD -------------------------------------------------- -- CHART MONAD -------------------------------------------------- -- -- | State for the global Earley-style computations. -- data EarSt n t = EarSt { -- -- | The CFG grammar. -- gram :: [R.Rule n t] -- -- | The chart computed so far. -- , chart :: Chart n t -- } deriving (Show, Eq, Ord) -- -- -- -- | Monad for local computations on a given position of the chart. -- type Ear n t = St.StateT (EarSt n t) IO -- -- -- -- | Run the Earley monad. -- execEar -- :: [R.Rule n t] -- ^ The grammar -- -> Int -- ^ Length of the input sentence -- -> Ear n t a -- ^ The computation to perform -- -> IO (Chart n t) -- execEar gr n comp -- = fmap chart $ St.execStateT comp -- $ EarSt {gram=gr, chart=ch0} -- where -- -- ch0 = I.fromList [(i, S.empty) | i <- [0..n]] -- ch0 = undefined -- -- TODO: since we do not implement any prediction yet, we -- -- have to fill the chart with all rules in the beginning! -- -- -- -- | Get the underlying grammar. -- getGram :: Ear n t [R.Rule n t] -- getGram = St.gets gram -- -- -- -- | Get the underlying chart. -- getChart :: Ear n t (Chart n t) -- getChart = St.gets chart -- -- -- -- | Get the underlying chart. -- getEntry :: Pos -> Ear n t (Entry n t) -- getEntry k = (!? k) <$> getChart -- -- -- -- | Check if there is a state in the chart. -- hasState -- :: (Ord n, Ord t) -- => Pos -- ^ Position of the chart -- -> State n t -- ^ State to add at the given position -- -> Ear n t Bool -- hasState k p = S.member p <$> getEntry k -- -- -- -- | Add state to the chart. -- addState -- :: (Ord n, Ord t) -- => Pos -- ^ Position of the chart -- -> State n t -- ^ State to add at the given position -- -> Ear n t () -- addState k p = St.modify $ \s@EarSt{..} -> -- let en = case I.lookup k chart of -- Nothing -> S.singleton p -- Just en -> S.insert p en -- chart' = I.insert k en chart -- in s {chart=chart'} -------------------------------------------------- -- SCAN -------------------------------------------------- -- -- | The scan operation. -- scan -- :: (Show n, Ord n, Ord t) -- => Pos -- ^ The current position -- -> t -- ^ Terminal to scan -- -> Entry n t -- ^ The entry -- -> Ear n t () -- scan k w entry = P.runListT $ do -- -- grm <- lift getGram -- let each = P.Select . P.each -- -- for each state, -- q <- each $ S.toList entry -- -- ... not yet completed ... -- q' <- each $ maybeToList $ consume w q -- -- add a corresponding state. -- lift $ do -- addState (k+1) q' -- -- lift $ do -- -- putStr "[S] " >> printState' k q -- -- putStr " : " >> printState' (k+1) q' -------------------------------------------------- -- COMPLETE -------------------------------------------------- -- -- | The queue of the <completed> states yet to process. -- type ComSt n t = Seq.Seq (State n t) -- -- -- -- | A monad for complete computations. -- type Com n t = St.StateT (ComSt n t) (Ear n t) -- -- -- -- | Run the Com monad given the initial set of states. -- runCom :: [State n t] -> Com n t a -> Ear n t a -- runCom xs com = St.evalStateT com $ Seq.fromList xs -- -- -- -- | Pop item from the queue. -- popQueue :: Com n t (Maybe (State n t)) -- popQueue = St.state $ \seq -> case Seq.viewl seq of -- EmptyL -> (Nothing, seq) -- x :< xs -> (Just x, xs) -- -- -- -- | Push item into the queue. -- pushQueue :: State n t -> Com n t () -- pushQueue x = St.modify $ \xs -> xs |> x -- -- | Update the current entry using `complete' operations. -- complete -- :: (Show n, Ord n, Ord t) -- => Pos -- ^ Current position -- -> Entry n t -- ^ Current entry -- -> Ear n t () -- complete k en0 = -- runCom (S.toList en0) (loop step) -- where -- -- execute the given function as long as the queue is non-empty -- loop f = do -- p <- popQueue -- case p of -- Nothing -> return () -- Just x -> f x >> loop f -- -- p is the state poped from the queue -- step p = P.runListT $ do -- -- make sure that p is completed -- guard $ null $ right p -- -- The chart built so far -- chart <- lift $ lift getChart -- -- For each rule ending on the beg position of p ... -- let each = P.Select . P.each -- q <- each $ S.toList $ chart !? beg p -- -- ... which is not yet completed ... -- (r, rs) <- each $ maybeToList $ decoList $ right q -- -- ... and expects a root non-terminal of the rule -- -- which we know has been completed, -- guard $ r == root p -- return () -- -- -- construct the new state, -- -- let new = q {left=r:left q, right=rs} -- -- lift $ do -- -- -- check if it is already present in the chart, -- -- b <- lift $ hasState k new -- -- -- add it to the chart (for the sake of traces if it is -- -- -- already there) -- -- lift $ addState k new $ Comp q p -- -- when b $ lift . lift $ do -- -- -- if present, only notify, -- -- putStr "[R] " >> printState' (beg p) q -- -- putStr " + " >> printState' k p -- -- putStr " : " >> printState' k new -- -- when (not b) $ do -- -- lift . lift $ do -- -- putStr "[C] " >> printState' (beg p) q -- -- putStr " + " >> printState' k p -- -- putStr " : " >> printState' k new -- -- -- if completed, add it to the queue -- -- when (null $ right new) $ -- -- pushQueue new -------------------------------------------------- -- UTILS -------------------------------------------------- -- | Extension of `Either a b'. data Three a b c = One a | Two b | Thr c deriving (Show, Eq, Ord) -- | Deconstruct list. Utility function. decoList :: [a] -> Maybe (a, [a]) decoList [] = Nothing decoList (y:ys) = Just (y, ys) -- | Label equals terminal? labEqTerm :: Eq t => t -> Lab n t -> Bool labEqTerm x (Right y) = x == y labEqTerm _ _ = False
kawu/ltag
src/NLP/LTAG/Early3/Earley.hs
bsd-2-clause
12,147
0
11
3,827
901
647
254
56
2
{-# LANGUAGE NamedFieldPuns #-} module Language.Epilog.IR.Program ( irProgram ) where -------------------------------------------------------------------------------- import Language.Epilog.AST.Program import Language.Epilog.Common import Language.Epilog.IR.Expression import Language.Epilog.IR.Monad import Language.Epilog.IR.Procedure (irProcedure) import Language.Epilog.IR.TAC (Data (..), Operand (R), Operation (U), TAC (..), Terminator (..), UOp (Id)) import qualified Language.Epilog.IR.TAC as TAC (Program (..)) import Language.Epilog.SymbolTable import Language.Epilog.Type (sizeT) -------------------------------------------------------------------------------- import Control.Lens (use, (.=)) import qualified Data.Map as Map (toList) -------------------------------------------------------------------------------- irProgram :: Program -> IRMonad TAC.Program irProgram Program { procs, scope, strings } = do global .= scope enterScope forM_ (Map.toList strings) $ \(str, idx) -> dataSegment |>= StringData ("_str" <> show idx) str newLabel "main" >>= (#) forM_ (sEntries scope) $ \Entry { eName, eType, eInitialValue } -> do dataSegment |>= VarData { dName = eName , dSpace = fromIntegral $ sizeT eType } insertVar' eName case eInitialValue of Nothing -> pure () Just e -> do t <- irExpression e addTAC $ R eName := U Id t addTAC $ Call "main" addTAC $ Cleanup 0 terminate $ Exit closeModule "_entry" mapM_ irProcedure procs exitScope TAC.Program <$> use dataSegment <*> use modules
adgalad/Epilog
src/Haskell/Language/Epilog/IR/Program.hs
bsd-3-clause
1,837
0
18
516
461
255
206
40
2